Compare commits

...

81 Commits

Author SHA1 Message Date
Henry Zhu
b414387bb1 v7.0.0-beta.45 2018-04-22 21:55:16 -04:00
Evan Scott
0bb71caad3 Add noConflict entry mode to @babel/polyfill + change error to warning (#6371)
* feat: add noConflict polyfill entry
* use a warning
2018-04-22 19:11:50 -04:00
Logan Smyth
d6dcbdad48 Merge pull request #7358 from loganfsmyth/babelrc-resolution-changes
Allow more flexible file-based configuration while preventing .babelrcs from breaking things
2018-04-22 13:28:05 -07:00
Logan Smyth
8606b76438 Split babelrc option into babelrcRoots. 2018-04-22 13:00:28 -07:00
Justin Ridgewell
34d73ebef0 Correct update expression Number coercion (#7766)
* Correct update expression Number coercion

You have to `ToNumber` whatever the `UpdateExpression` argument is.

* Fix systemjs update expression
2018-04-22 13:50:11 -04:00
Justin Ridgewell
890a45216f Update super property get/set/call in loose mode (#7774)
* Update super property get/set/call in loose mode

Follows the plan laid out in https://github.com/babel/babel/pull/7553#issuecomment-381434519.

With #7691, this closes #7553, closes #4312.

* Post #7772

* Memoized property
2018-04-22 13:49:19 -04:00
Justin Ridgewell
0a257e8972 Move more class state out of replaceSupers (#7750)
Yes, the output is uglier. But, this is necessary for me to refactor
`replaceSupers` for #7733, which is necessary for both #7555 and
https://github.com/babel/babel/pull/7553#issuecomment-381434519.

I'm still in the middle of cleaning up all this code. Don't expect
`transformClass` to survive much longer as it's written currently.
2018-04-21 22:56:14 -04:00
Justin Ridgewell
3616137864 Memoize computed super properties (#7776)
Fixes #7775.
2018-04-21 22:15:02 -04:00
Justin Ridgewell
f8ab9466d3 Move subclass inheritance to end (#7772)
We were using `Object.create` to setup the prototype chain at the start of the class definition, which lead to #7771.

I was a bit worried about a speed hit, but it seems everyone optimizes the two patterns the same way.
https://jsbench.github.io/#f9fca52407643d96458a35763b201215

Fixes #7771.
2018-04-21 17:31:44 -04:00
Justin Ridgewell
8f24f91166 Implement MemberExpressionToFunctions helper (#7763)
* Implement MemberExpressionToFunctions helper

Fixes #7733.

This will also be used to simplify the Private Fields transform, which had [almost the same code](ccd941057a/packages/babel-plugin-proposal-class-properties/src/index.js (L114-L217)) hand written.

* Cleanup

* Little more comment cleanup

* Use unary plus

This can't be redefined, unlike the `Number` identifier.

* Review comments

* Remove unused deps
2018-04-21 13:13:42 -04:00
Henry Zhu
dbdce0e4e4 add overwrite for tests [skip ci] 2018-04-21 11:46:15 -04:00
Vinh Le
4595c7fdfd Correct test running command (#7768) [skip ci]
* Correct test running command

* Also refine test/index.js content
2018-04-21 11:35:48 -04:00
Yosuke Kurami
1f97b91655 fix: don't write ': ' token when name is null (#7769) 2018-04-21 11:34:24 -04:00
Christopher Hiller
b0e1e84471 drop support for Node.js v4 (#7755)
* drop support for Node.js v4; closes #7753

- remove version 4 from Travis build matrix
- update environment support doc
- update `CONTRIBUTING.md`
- update `engines` field of root `package.json`

Signed-off-by: Christopher Hiller <boneskull@boneskull.com>

* update engines for babylon

Signed-off-by: Christopher Hiller <boneskull@boneskull.com>
2018-04-21 01:09:10 -04:00
Logan Smyth
f7c26bf2bf Add some docs for config searching. 2018-04-20 17:00:54 -07:00
Logan Smyth
a67eb25547 Only search for .babelrc files in the 'root' package by default. 2018-04-20 17:00:53 -07:00
Logan Smyth
485e37fcb0 Support a babel.config.fs file in a 'root' directory. 2018-04-20 17:00:53 -07:00
Logan Smyth
f013dab5fb Restrict .babelrc resolution to within a given package. 2018-04-20 17:00:53 -07:00
Brian Ng
e45b58dcb1 Fix small typo with decorators legacy option [skip ci] (#7762) 2018-04-19 20:26:54 -05:00
Henry Zhu
339dfddca5 Merge pull request #7734 from nicolo-ribaudo/decorators-legacy-option
Decorators legacy option
2018-04-19 14:36:18 -04:00
Brian Ng
0cd868a5f2 fixup tests 2018-04-19 09:17:33 -05:00
Nicolò Ribaudo
29db23ed87 Remove old comment 2018-04-19 09:08:15 -05:00
Nicolò Ribaudo
2679d6775c Add "decoratorsLegacy" to presets 2018-04-19 09:08:15 -05:00
Nicolò Ribaudo
96316dcf88 Add legacy option to plugin-proposal-decorators. 2018-04-19 09:08:14 -05:00
Logan Smyth
42244123e1 Update the docs to correctly reflect default value changed in #7436. [skip ci] 2018-04-18 23:33:34 -07:00
Andy
4b97e837ea Fix type error (#7752) 2018-04-18 15:31:15 -04:00
Brian Ng
3299086955 Add support for flow implements (#7741) 2018-04-18 08:54:30 -05:00
Jason Quense
2bded404f3 Improve asyncIterator error (#7745)
* Improve asyncIterator error

When an object is has neither asyncIterator or iterator defined, throw the "not an async iterable" error

* Correct logic

* reduce access

* Update helpers.js
2018-04-17 21:02:53 -05:00
Justin Ridgewell
21c7ff3f37 Classes cleanup (#7737)
* Cleanup

* Move verifyConstructorVisitor out of closure
2018-04-17 17:52:43 -04:00
Nicolò Ribaudo
341bdab90c Update decorators parsing (#7719)
* Update decorators parsing

This commit introduces three changes:
1) Class properties can be decorated
2) Decorators can contain arbitrary expressions, using @(...)
3) The Decorator node type has a new property, "arguments". This
    makes it possible do distinguish @dec() and @(dec()), which have
    different behaviors because @(dec()) is equivalent to @(dec())().

* Rename Decorator#expression to Decorator#callee

* Add test for @dec()()
2018-04-17 16:22:03 -05:00
Brian Ng
81149a5cc9 Add initial support for ES2018 in preset-env (#7658) 2018-04-17 16:16:33 -05:00
Mateusz Burzyński
5166eef103 Optimize class properties output (#6656) 2018-04-15 01:03:47 -04:00
Justin Ridgewell
0ee9a4e612 Fix default class super inheritance (#7732)
Fixes #7683.
2018-04-14 15:15:40 -04:00
Henry Zhu
858a2c74e7 update readme [skip ci] 2018-04-14 15:13:31 -04:00
Justin Ridgewell
668358c4d0 Fix class properties after nested class' bare super (#7671)
* Fix class properties after nested class' bare super

Fixes #7371.

* Fix node 4 test

* This damn node 4 test

* All of the ClassBody, but not the methods or field inits

* tmp

* tmp

* Use common class environment visitor

* Tests

* Use skipKey to avoid recursive traversal

* Remove old state

* Use jest expect
2018-04-14 13:48:38 -04:00
Justin Ridgewell
39b05598a0 Drop Chai from packages (#7729) 2018-04-14 09:01:38 -04:00
Justin Ridgewell
29eafbbf44 Remove tagged template literal global caching (#7722)
* Remove tagged template literal global caching

Fixes #7350.

* Review comments

* assert output
2018-04-13 11:51:00 -04:00
Henry Zhu
7a106025ea Merge pull request #7720 from devenbansod/migrate_to_jest_expect-3
Migrate more packages' tests to use jest expect assertions
2018-04-13 11:04:44 -04:00
Deven Bansod
4f1473da3d Remove global chai.assert in fixture runner's test context 2018-04-13 19:14:30 +05:30
Deven Bansod
c62b202e6a Migrate remaining test assertions to jest-expect 2018-04-13 19:14:03 +05:30
Deven Bansod
a084339a15 Migrate -computed-properties and -jscript tests to use jest expect assertions 2018-04-13 16:30:06 +05:30
Deven Bansod
d7987fbbd2 Migrate -transform-object-super tests to use jest expect assertions 2018-04-13 14:21:02 +05:30
Deven Bansod
8a31eabf5e Migrate -transform-classes tests to use jest expect assertions 2018-04-13 14:20:51 +05:30
Deven Bansod
80428dec47 Migrate -optional-catch-binding, -block-scoping to use jest expect assertions 2018-04-13 14:19:49 +05:30
Dennis Czombera
61ec5ce957 Provide better error message for invalid default export declaration (#7717) 2018-04-12 17:07:41 -05:00
Alexander Pepper
1e41f613bb [babel-preset-typescript] Fixed link of plugin-transform-typescript. (#7700) [skip ci] 2018-04-12 16:44:43 -04:00
Nicolò Ribaudo
a86d14de61 Disallow super() in class properties 2018-04-12 22:41:28 +02:00
Nicolò Ribaudo
a62cfe9045 Disallow arguments in class properties 2018-04-12 22:41:28 +02:00
Nicolò Ribaudo
f797454a18 Disallow super in functions in class properties 2018-04-12 22:41:28 +02:00
Justin Ridgewell
ec882be44d Uncomment super increment expression set tests (#7721)
This was failing because of the bugs fixed by #7687.
2018-04-12 13:24:07 -04:00
Justin Ridgewell
ecbf0dd53c Fix super nested class bugs (#7691)
* Properly traverse nested class for supers

* Add object nested in class cases

* Add object nested object cases

* Test class properties

* Undo changes to lerna.json

* Add tests arournd prefix/postfix super increment

* tmp

* Use sets
2018-04-12 13:02:26 -04:00
Nicolò Ribaudo
af3d6526e7 Add slack links to CONTRIBUTING.md (#7713) 2018-04-11 21:56:45 -05:00
Deven Bansod
95894397eb Migrate babel-cli and babel-generator tests to use jest-expect (#7549) 2018-04-11 13:12:56 -05:00
Justin Ridgewell
b1c9af3f05 Use new isInStrictMode (#7714) 2018-04-11 12:17:01 -04:00
Justin Ridgewell
ec3722b3f9 Get set helpers (#7687)
* Improve get/set helper

* fixtures

* Edge cases

* Add loose edge cases

* Spec compliant

* Add issue case

* Even more edge cases!

* Final updates

* Fix name

* Use Reflect.{get, set} when available

* Avoid block scoping in loose

* Remove semicolon

* Do not redefine a non-enumerable

* Get strictness from call site, not helpers

* Add called assertions

* Classes are always strict

* Update test fixture
2018-04-11 11:56:59 -04:00
Justin Ridgewell
7ae724f553 Add Path#isInStrictMode (#7712)
* Add Path#isInStrictMode

* Fix undefined directives

* Explicitly return for arrow expressions
2018-04-11 09:13:38 -04:00
Markus Török
6597a472b3 Add "use strict" directive (#7411)
* #7349
- Add "use strict" directive to transformed class bodies

* Update tests (#7349)

* Add test for program with use strict directive (#7349)

* Update tests (#7349)

* Update source mapping (#7349)

* Add test for parent blockStatement with use strict directive (#7349)

* Update tests (#7349)

* Update tests (#7349)

* Update tests (#7349)

* Add test for constructor-only class (#7349)

* Constructor only classes are strict, too

But constructor only that use non-simple parameters must use a strict function wrapper.

* Fix test

* Wrapper not needed if class is already strict

* Revert change to lerna.json
2018-04-10 17:33:38 -04:00
Hendrik Niemann
fdd0789936 Fix literal type annotation argument number (#7706)
Added the value argument to the visitors of flow literal type
annotations.
Literal type annotations need a value since they work very much like
primitive literals in normal JavaScript.

Fixes #7697
2018-04-10 09:38:20 -04:00
Guy Bedford
5b1332457c arrayWithHoles internal function name consistency (#7709) [skip ci] 2018-04-10 09:33:54 -04:00
Justin Ridgewell
3177f05904 ESLint: Ignore lerna.json and .git (#7708)
* Ignore lerna.json

* Oh, and ignore .git
2018-04-10 08:47:50 -04:00
Sven SAULEAU
9dc178df9a Merge pull request #7704 from babel/use-circle-yarn
Use yarn provided by circle
2018-04-10 07:38:41 +02:00
Brian Ng
75bc9422b8 Use yarn provided by circle 2018-04-09 22:11:17 -05:00
Axel Nyffenegger
bd98041321 Fix function name computation for literal values (#7435)
* Fix name computation for literal values

* Add more computed literal test cases

* Always return a string in getNameFromLiteralId

- Also concatenate quasis id for regex literal

* Add a test clarifying function name for template literals

* Remove useless else ifs
2018-04-09 21:00:55 -04:00
Devon Govett
6a8c4ab433 Make babel-types type checking functions 36% faster (#7685)
* Precompile 25% faster type checking functions

* Pre-fetch type-check function when generating NodePath methods

Additional ~11% speed improvement.

* Slightly faster assert calls
2018-04-09 15:11:04 -04:00
Justin Ridgewell
637bfe76b1 Cleanup object super traversal (#7681) 2018-04-06 20:39:57 +01:00
Justin Ridgewell
3f72f1d637 Add option to overwrite failing output fixtures (#7679) 2018-04-06 12:13:10 -05:00
Henry Zhu
20de23f895 update sponsors, move up [skip ci] (#7676) 2018-04-06 10:02:30 -05:00
Justin Ridgewell
d17adf40df Use construct helper in New Spread (#7677)
* Use construct helper in New Spread

* CircleCI
2018-04-06 10:40:38 +01:00
Justin Ridgewell
450a1678f2 Use getProto and setProto helpers (#7675)
Depends on #7674.
2018-04-06 02:54:08 +01:00
Justin Ridgewell
e9ed0f5f21 Split _wrapNativeSuper into helpers (#7674)
These can be reused in a few transforms.
2018-04-06 01:18:44 +01:00
Justin Ridgewell
29d249e3b7 Cleanup isReferenced a bit (#7669)
* Cleanup isReferenced a bit

* Optimize isReferenced inside Functions

* Group return falses
2018-04-05 19:09:58 +01:00
Justin Ridgewell
6f9b0546ef Class Properties Tests (#7670)
* Round out class properties tests

* Rename in preperation for private tests

* Fix options
2018-04-05 17:49:34 +01:00
Nicolò Ribaudo
fa2c6c5164 Never extract class fields into an initializer function. (#7659)
It was needed to avoid collision of identifiers used in fields
initializers with variables declared in the constructor, but it
broke `this` handling.
This commit removes that behavior and instead renames the
colliding variables.
2018-04-05 16:20:47 +01:00
Justin Ridgewell
43040a4181 Private Properties phase 1 (#7666)
* Private Properties phase 1

Co-authored-by: CodingItWrong

* Private fields are optional

* Docs update
2018-04-05 11:17:34 +01:00
Justin Ridgewell
01f4c2368e OptionalMemberExpression properties are not referenced (#7668)
Fixes #7642.
2018-04-05 02:44:32 +01:00
hirochachacha
56cb4baf46 Add missing exponential operators to ast spec (#7663) [skip ci] 2018-04-04 14:27:19 -04:00
hirochachacha
b051243a63 Fix typo in ast spec (#7662) [skip ci] 2018-04-04 14:26:06 -04:00
Henry Zhu
e808b63c15 Bump to babel@7.0.0-beta.44 (#7656) 2018-04-02 19:47:25 -05:00
Henry Zhu
a6df92f245 v7.0.0-beta.44 2018-04-02 18:19:30 -04:00
Logan Smyth
f4b81ab101 Merge pull request #7655 from babel/babel-env-make
Remove setting BABEL_ENV to test by default in makefile
2018-04-02 13:57:47 -07:00
Brian Ng
360b632881 Remove setting BABEL_ENV to test by default in makefile 2018-04-02 15:18:50 -05:00
904 changed files with 19177 additions and 4616 deletions

View File

@@ -18,11 +18,6 @@ aliases:
- ~/.yarn-cache
key: v1-yarn-cache
- &yarn-install
run: |
sudo npm i -g yarn@^1.5.1
yarn --version
- &artifact_babel
path: ~/babel/packages/babel-standalone/babel.js
@@ -44,7 +39,7 @@ jobs:
- checkout
- restore-cache: *restore-yarn-cache
- restore-cache: *restore-node-modules-cache
- *yarn-install
- run: yarn --version
- run: make test-ci-coverage
# Builds babel-standalone with the regular Babel config
- run: make build
@@ -58,4 +53,4 @@ jobs:
- store_artifacts: *artifact_env
- store_artifacts: *artifact_env_min
- save_cache: *save-node-modules-cache
- save_cache: *save-yarn-cache
- save_cache: *save-yarn-cache

View File

@@ -1,6 +1,8 @@
/lib
/build
/.git
package.json
lerna.json
packages/babel-runtime
!packages/babel-runtime/scripts
!packages/babel-runtime/core-js.js

View File

@@ -5,7 +5,7 @@ Search open/closed issues before submitting since someone might have asked the s
If you have a support request or question please submit them to one of this resources:
* Slack Community: https://slack.babeljs.io/
* Slack Community: https://babeljs.slack.com (you can sign-up at https://slack.babeljs.io/ for an invite)
* StackOverflow: http://stackoverflow.com/questions/tagged/babeljs using the tag `babeljs`
* Also have a look at the readme for more information on how to get support:
https://github.com/babel/babel/blob/master/README.md

View File

@@ -10,7 +10,6 @@ node_js:
# We test the latest version on circleci
- '8'
- '6'
- '4'
env:
global:

View File

@@ -29,18 +29,19 @@ contributing, please read the
- Check out [the Babel Plugin Handbook](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-plugin-handbook) - core plugins are written the same way as any other plugin!
- Check out [AST Explorer](http://astexplorer.net/#/scUfOmVOG5) to learn more about ASTs or make your own plugin in the browser
- When you feel ready to jump into the Babel source code, a good place to start is to look for issues tagged with [help wanted](https://github.com/babel/babel/labels/help%20wanted) and/or [good first issue](https://github.com/babel/babel/labels/good%20first%20issue).
- Follow along with what we are working on by joining our Slack, following our announcements on [Twitter](https://twitter.com/babeljs), and reading (or participating!) in our [meeting notes](https://github.com/babel/notes).
- Follow along with what we are working on by joining our [Slack](https://babeljs.slack.com) (you can sign-up [here](https://slack.babeljs.io/)
for an invite), following our announcements on [Twitter](https://twitter.com/babeljs), and reading (or participating!) in our [meeting notes](https://github.com/babel/notes).
- Check out our [website](http://babeljs.io/) and the [repo](https://github.com/babel/website)
## Chat
Feel free to check out the `#discussion`/`#development` channels on our [Slack](https://slack.babeljs.io). Some of us are always online to chat!
Feel free to check out the `#discussion`/`#development` channels on our [Slack](https://slack.babeljs.io) (you can sign-up [here](https://slack.babeljs.io/) for an invite). Some of us are always online to chat!
## Developing
**Note:** Versions `< 5.1.10` can't be built.
Babel is built for Node 4 and up but we develop using Node 8 and yarn. You can check this with `node -v`.
Babel is built for Node 6 and up but we develop using Node 8 and yarn. You can check this with `node -v`.
Make sure that Yarn is installed with version >= `0.28.0`.
Installation instructions can be found here: https://yarnpkg.com/en/docs/install.
@@ -139,6 +140,12 @@ $ TEST_DEBUG=true make test
You can combine `TEST_DEBUG` with `TEST_GREP` or `TEST_ONLY` to debug a subset of tests. If you plan to stay long in the debugger (which you'll likely do!), you may increase the test timeout by editing [test/mocha.opts](https://github.com/babel/babel/blob/master/test/mocha.opts).
To overwrite any test fixtures when fixing a bug or anything, add the env variable `OVERWRITE=true`
```sh
$ OVERWRITE=true TEST_ONLY=babel-plugin-transform-classes make test-only
```
To test the code coverage, use:
```sh
@@ -196,8 +203,8 @@ In an `exec.js` test, we run or check that the code actually does what it's supp
```js
// exec.js
assert.equal(8, 2 ** 3);
assert.equal(24, 3 * 2 ** 3);
expect(2 ** 3).toBe(8);
expect(3 * 2 ** 3).toBe(24);
```
If you need to check for an error that is thrown you can add to the `options.json`

View File

@@ -1,9 +1,7 @@
MAKEFLAGS = -j1
FLOW_COMMIT = 622bbc4f07acb77eb1109830c70815f827401d90
FLOW_COMMIT = f193e19cf2185006ea9139bb0e71f31ea93e7b72
TEST262_COMMIT = 52f70e2f637731aae92a9c9a2d831310c3ab2e1e
export BABEL_ENV = test
# Fix color output until TravisCI fixes https://github.com/travis-ci/travis-ci/issues/7967
export FORCE_COLOR = true
@@ -69,7 +67,7 @@ test-clean:
$(call clean-source-test, $(source)))
test-only:
./scripts/test.sh
BABEL_ENV=test ./scripts/test.sh
make test-clean
test: lint test-only
@@ -79,7 +77,7 @@ test-ci: bootstrap test-only
test-ci-coverage: SHELL:=/bin/bash
test-ci-coverage:
BABEL_COVERAGE=true BABEL_ENV=test make bootstrap
TEST_TYPE=cov ./scripts/test-cov.sh
BABEL_ENV=test TEST_TYPE=cov ./scripts/test-cov.sh
bash <(curl -s https://codecov.io/bash) -f coverage/coverage-final.json
bootstrap-flow:

175
README.md
View File

@@ -24,108 +24,12 @@
<a href="https://medium.com/friendship-dot-js/i-peeked-into-my-node-modules-directory-and-you-wont-believe-what-happened-next-b89f63d21558"><img alt="Business Strategy Status" src="https://img.shields.io/badge/business%20model-flavortown-green.svg"></a>
</p>
Babel is community-driven and thus mostly maintained by a group of [volunteers](https://babeljs.io/team). It has a lot of [companies and projects](https://babeljs.io/users) using it but almost no sponsors/people funded to work on it. If you'd like to help maintain the future of the project, please consider:
Babel is a community-driven project used by many companies and projects, and is maintained by a group of [volunteers](https://babeljs.io/team). If you'd like to help support the future of the project, please consider:
- Giving developer time on the project. (Message us on [Twitter](https://twitter.com/babeljs) or [Slack](https://slack.babeljs.io/))
- [Giving funds by becoming a backer/sponsor on OpenCollective](https://opencollective.com/babel)
- Giving developer time on the project. (Message us on [Twitter](https://twitter.com/babeljs) or [Slack](https://slack.babeljs.io/) for guidance!)
- Giving funds by becoming a sponsor (see below)!
## Intro
Babel is a tool that helps you write code in the latest version of JavaScript. When your supported environments don't support certain features natively, Babel will help you compile those features down to a supported version.
**In**
```js
// ES2015 arrow function
[1, 2, 3].map((n) => n + 1);
```
**Out**
```js
[1, 2, 3].map(function(n) {
return n + 1;
});
```
Try it out at our [REPL](https://babeljs.io/repl/build/master#?code_lz=NoRgNATGDMC6B0BbAhgBwBQDsAEBeAfNjgNTYgCUA3EA&lineWrap=true&presets=es2015%2Ces2016%2Ces2017&version=7.0.0-beta.2).
- [FAQ](#faq)
- [Backers](#backers)
- [Sponsors](#sponsors)
- [License](#license)
## FAQ
### Who maintains Babel?
Mostly a handful of volunteers! Please check out our [team page](https://babeljs.io/team)!
### Looking for support?
For questions and support please visit join our [Slack Community](https://slack.babeljs.io/), ask a question on [Stack Overflow](https://stackoverflow.com/questions/tagged/babeljs), or ping us on [Twitter](https://twitter.com/babeljs).
### Is there a Babel song?
I'm so glad you asked: [Hallelujah —— In Praise of Babel](SONG.md) by [@angus-c](https://github.com/angus-c). Tweet us your recordings!
### Where are the docs?
Check out our website: [babeljs.io](https://babeljs.io/), and report issues/features at [babel/website](https://github.com/babel/website/issues).
### Want to report a bug or request a feature?
Please read through our [CONTRIBUTING.md](CONTRIBUTING.md) and fill out the issue template at [babel/issues](https://github.com/babel/babel/issues)!
### Want to contribute to Babel?
Check out our [CONTRIBUTING.md](CONTRIBUTING.md) to get started with setting up the repo.
- If you have already joined Slack, join our [#development](https://babeljs.slack.com/messages/development) channel and say hi!
- Check out the issues with the [good first issue](https://github.com/babel/babel/labels/good%20first%20issue) and [help wanted](https://github.com/babel/babel/labels/help%20wanted) label. We suggest also looking at the closed ones to get a sense of the kinds of issues you can tackle.
- Our discussions/notes/roadmap: [babel/notes](https://github.com/babel/notes)
- Our progress on TC39 proposals: [babel/proposals](https://github.com/babel/proposals)
### How is the repo structured?
The Babel repo is managed as a [monorepo](doc/design/monorepo.md) that is composed of many [npm packages](packages/README.md).
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/babel#backer)]
<a href="https://opencollective.com/babel/backer/0/website" target="_blank"><img src="https://opencollective.com/babel/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/1/website" target="_blank"><img src="https://opencollective.com/babel/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/2/website" target="_blank"><img src="https://opencollective.com/babel/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/3/website" target="_blank"><img src="https://opencollective.com/babel/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/4/website" target="_blank"><img src="https://opencollective.com/babel/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/5/website" target="_blank"><img src="https://opencollective.com/babel/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/6/website" target="_blank"><img src="https://opencollective.com/babel/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/7/website" target="_blank"><img src="https://opencollective.com/babel/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/8/website" target="_blank"><img src="https://opencollective.com/babel/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/9/website" target="_blank"><img src="https://opencollective.com/babel/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/10/website" target="_blank"><img src="https://opencollective.com/babel/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/11/website" target="_blank"><img src="https://opencollective.com/babel/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/12/website" target="_blank"><img src="https://opencollective.com/babel/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/13/website" target="_blank"><img src="https://opencollective.com/babel/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/14/website" target="_blank"><img src="https://opencollective.com/babel/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/15/website" target="_blank"><img src="https://opencollective.com/babel/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/16/website" target="_blank"><img src="https://opencollective.com/babel/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/17/website" target="_blank"><img src="https://opencollective.com/babel/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/18/website" target="_blank"><img src="https://opencollective.com/babel/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/19/website" target="_blank"><img src="https://opencollective.com/babel/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/20/website" target="_blank"><img src="https://opencollective.com/babel/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/21/website" target="_blank"><img src="https://opencollective.com/babel/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/22/website" target="_blank"><img src="https://opencollective.com/babel/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/23/website" target="_blank"><img src="https://opencollective.com/babel/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/24/website" target="_blank"><img src="https://opencollective.com/babel/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/25/website" target="_blank"><img src="https://opencollective.com/babel/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/26/website" target="_blank"><img src="https://opencollective.com/babel/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/27/website" target="_blank"><img src="https://opencollective.com/babel/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/28/website" target="_blank"><img src="https://opencollective.com/babel/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/29/website" target="_blank"><img src="https://opencollective.com/babel/backer/29/avatar.svg"></a>
## Sponsors
## Open Collective Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/babel#sponsor)]
@@ -160,6 +64,77 @@ Become a sponsor and get your logo on our README on Github with a link to your s
<a href="https://opencollective.com/babel/sponsor/28/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/29/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/29/avatar.svg"></a>
## Patreon Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://www.patreon.com/henryzhu)]
## Gold
<a href="https://vueschool.io/?babel" target="_blank"><img src="http://new.babeljs.io/img/sponsors/vueschool.png" height="64"></a>
<a href="https://devrant.com/?babel" target="_blank"><img src="http://new.babeljs.io/img/sponsors/devRant.png" height="64"></a>
## Bronze
<a href="http://teamextension.io/" target="_blank"><img src="https://teamextension.io/dist/img/logo/te-logo-compact.png" height="64"></a>
<a href="https://webflow.com/" target="_blank"><img src="https://opencollective.com/proxy/images/?src=https%3A%2F%2Fopencollective-production.s3-us-west-1.amazonaws.com%2F4a5024b0-8cf2-11e7-b1a2-b30b1de1463c.png&height=64"></a>
<p><a href="https://twitter.com/mikesherov">Mike Sherov</a></p>
## Intro
Babel is a tool that helps you write code in the latest version of JavaScript. When your supported environments don't support certain features natively, Babel will help you compile those features down to a supported version.
**In**
```js
// ES2015 arrow function
[1, 2, 3].map((n) => n + 1);
```
**Out**
```js
[1, 2, 3].map(function(n) {
return n + 1;
});
```
Try it out at our [REPL](https://babeljs.io/repl/build/master#?code_lz=NoRgNATGDMC6B0BbAhgBwBQDsAEBeAfNjgNTYgCUA3EA&lineWrap=true&presets=es2015%2Ces2016%2Ces2017&version=7.0.0-beta.2).
## FAQ
### Who maintains Babel?
Mostly a handful of volunteers! Please check out our [team page](https://babeljs.io/team)!
### Looking for support?
For questions and support please visit join our [Slack Community](https://slack.babeljs.io/) (you can sign-up [here](https://slack.babeljs.io/) for an invite), ask a question on [Stack Overflow](https://stackoverflow.com/questions/tagged/babeljs), or ping us on [Twitter](https://twitter.com/babeljs).
### Is there a Babel song?
I'm so glad you asked: [Hallelujah —— In Praise of Babel](SONG.md) by [@angus-c](https://github.com/angus-c). Tweet us your recordings!
### Where are the docs?
Check out our website: [babeljs.io](https://babeljs.io/), and report issues/features at [babel/website](https://github.com/babel/website/issues).
### Want to report a bug or request a feature?
Please read through our [CONTRIBUTING.md](CONTRIBUTING.md) and fill out the issue template at [babel/issues](https://github.com/babel/babel/issues)!
### Want to contribute to Babel?
Check out our [CONTRIBUTING.md](CONTRIBUTING.md) to get started with setting up the repo.
- If you have already joined Slack, join our [#development](https://babeljs.slack.com/messages/development) channel and say hi!
- Check out the issues with the [good first issue](https://github.com/babel/babel/labels/good%20first%20issue) and [help wanted](https://github.com/babel/babel/labels/help%20wanted) label. We suggest also looking at the closed ones to get a sense of the kinds of issues you can tackle.
- Our discussions/notes/roadmap: [babel/notes](https://github.com/babel/notes)
- Our progress on TC39 proposals: [babel/proposals](https://github.com/babel/proposals)
### How is the repo structured?
The Babel repo is managed as a [monorepo](doc/design/monorepo.md) that is composed of many [npm packages](packages/README.md).
## License
[MIT](LICENSE)

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-codemod-optional-catch-binding",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"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.43"
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.45"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.43",
"@babel/helper-plugin-test-runner": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45",
"@babel/helper-plugin-test-runner": "7.0.0-beta.45"
}
}

View File

@@ -7,7 +7,7 @@
The Babel compiler is **only** supported in these environments:
- Modern browsers such as Chrome, Firefox, Safari, Edge etc.
- Node.js 4 and upper versions
- Node.js 6 and newer versions
## Unsupported environments

View File

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

View File

@@ -10,22 +10,21 @@
"test": "make test"
},
"devDependencies": {
"@babel/cli": "7.0.0-beta.42",
"@babel/core": "7.0.0-beta.42",
"@babel/plugin-transform-modules-commonjs": "7.0.0-beta.42",
"@babel/preset-env": "7.0.0-beta.42",
"@babel/preset-flow": "7.0.0-beta.42",
"@babel/preset-stage-0": "7.0.0-beta.42",
"@babel/register": "7.0.0-beta.42",
"@babel/cli": "7.0.0-beta.44",
"@babel/core": "7.0.0-beta.44",
"@babel/plugin-transform-modules-commonjs": "7.0.0-beta.44",
"@babel/preset-env": "7.0.0-beta.44",
"@babel/preset-flow": "7.0.0-beta.44",
"@babel/preset-stage-0": "7.0.0-beta.44",
"@babel/register": "7.0.0-beta.44",
"babel-core": "^7.0.0-0",
"babel-eslint": "^8.0.1",
"babel-jest": "^22.4.1",
"babel-loader": "8.0.0-beta.0",
"babel-plugin-transform-charcodes": "^0.1.0",
"babylon": "7.0.0-beta.42",
"babylon": "7.0.0-beta.44",
"browserify": "^13.1.1",
"bundle-collapser": "^1.2.1",
"chai": "^4.1.0",
"chalk": "^2.3.2",
"charcodes": "^0.1.0",
"derequire": "^2.0.2",
@@ -69,7 +68,7 @@
"webpack-stream": "^4.0.0"
},
"engines": {
"node": ">= 4.x <= 9.x",
"node": ">= 6.x <= 9.x",
"npm": ">= 2.x <= 5.x",
"yarn": ">=0.27.5 || >=1.0.0-20170811"
},

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/cli",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"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.43"
"@babel/core": "7.0.0-beta.45"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.43",
"@babel/helper-fixtures": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45",
"@babel/helper-fixtures": "7.0.0-beta.45"
},
"bin": {
"babel": "./bin/babel.js",

View File

@@ -238,10 +238,6 @@ if (errors.length) {
//
const opts = commander.opts();
//the configFile CLI option maps to the extends option in the node API
if (opts.configFile) {
opts.extends = opts.configFile;
}
// Delete options that are specific to @babel/cli and shouldn't be passed to @babel/core.
delete opts.version;
@@ -253,7 +249,6 @@ delete opts.outDir;
delete opts.copyFiles;
delete opts.includeDotfiles;
delete opts.verbose;
delete opts.configFile;
delete opts.deleteDirOnStart;
delete opts.keepFileExtension;
delete opts.relative;

View File

@@ -1,13 +1,11 @@
const includes = require("lodash/includes");
const readdir = require("fs-readdir-recursive");
const helper = require("@babel/helper-fixtures");
const assert = require("assert");
const rimraf = require("rimraf");
const outputFileSync = require("output-file-sync");
const child = require("child_process");
const merge = require("lodash/merge");
const path = require("path");
const chai = require("chai");
const fs = require("fs");
const fixtureLoc = path.join(__dirname, "fixtures");
@@ -53,15 +51,9 @@ const assertTest = function(stdout, stderr, opts) {
if (opts.stderr) {
if (opts.stderrContains) {
assert.ok(
includes(stderr, expectStderr),
"stderr " +
JSON.stringify(stderr) +
" didn't contain " +
JSON.stringify(expectStderr),
);
expect(includes(stderr, expectStderr)).toBe(true);
} else {
chai.expect(stderr).to.equal(expectStderr, "stderr didn't match");
expect(stderr).toBe(expectStderr);
}
} else if (stderr) {
throw new Error("stderr:\n" + stderr);
@@ -73,15 +65,9 @@ const assertTest = function(stdout, stderr, opts) {
if (opts.stdout) {
if (opts.stdoutContains) {
assert.ok(
includes(stdout, expectStdout),
"stdout " +
JSON.stringify(stdout) +
" didn't contain " +
JSON.stringify(expectStdout),
);
expect(includes(stdout, expectStdout)).toBe(true);
} else {
chai.expect(stdout).to.equal(expectStdout, "stdout didn't match");
expect(stdout).toBe(expectStdout);
}
} else if (stdout) {
throw new Error("stdout:\n" + stdout);
@@ -96,24 +82,19 @@ const assertTest = function(stdout, stderr, opts) {
filename !== ".babelrc" &&
!opts.inFiles.hasOwnProperty(filename)
) {
const expect = opts.outFiles[filename];
const expected = opts.outFiles[filename];
const actual = actualFiles[filename];
chai.expect(expect, "Output is missing: " + filename).to.not.be
.undefined;
expect(expected).not.toBeUndefined();
if (expect) {
chai
.expect(actual)
.to.equal(expect, "Compiled output does not match: " + filename);
if (expected) {
expect(actual).toBe(expected);
}
}
});
Object.keys(opts.outFiles).forEach(function(filename) {
chai
.expect(actualFiles, "Extraneous file in output: " + filename)
.to.contain.key(filename);
expect(actualFiles).toHaveProperty([filename]);
});
}
};

View File

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

View File

@@ -213,10 +213,13 @@ Following is a table of the options you can use:
| Option | Default | Description |
| ------------------------ | -------------------- | ------------------------------- |
| `ast` | `true` | Include the AST in the returned object |
| `ast` | `false` | Include the AST in the returned object |
| `auxiliaryCommentAfter` | `null` | Attach a comment after all non-user injected code |
| `auxiliaryCommentBefore` | `null` | Attach a comment before all non-user injected code |
| `root` | `"."` | Specify the "root" folder that defines the location to search for "babel.config.js", and the default folder to allow `.babelrc` files inside of.|
| `configFile` | `undefined` | The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. `false` will disable searching for config files.|
| `babelrc` | `true` | Specify whether or not to use .babelrc and .babelignore files. Not available when using the CLI, [use `--no-babelrc` instead](https://babeljs.io/docs/usage/cli/#babel-ignoring-babelrc) |
| `babelrcRoots` | `(root)` | Specify which packages should be search for .babelrc files when they are being compiled. `true` to _always_ search, or a path string or an array of paths to packages to search inside of. Defaults to only searching the "root" package. |
| `envName` | env vars | Defaults to environment variable `BABEL_ENV` if set, or else `NODE_ENV` if set, or else it defaults to `"development"` |
| `code` | `true` | Enable code generation |
| `comments` | `true` | Output comments in generated output |

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/core",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"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.43",
"@babel/generator": "7.0.0-beta.43",
"@babel/helpers": "7.0.0-beta.43",
"@babel/template": "7.0.0-beta.43",
"@babel/traverse": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43",
"babylon": "7.0.0-beta.43",
"@babel/code-frame": "7.0.0-beta.45",
"@babel/generator": "7.0.0-beta.45",
"@babel/helpers": "7.0.0-beta.45",
"@babel/template": "7.0.0-beta.45",
"@babel/traverse": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45",
"babylon": "7.0.0-beta.45",
"convert-source-map": "^1.1.0",
"debug": "^3.1.0",
"json5": "^0.5.0",
@@ -45,7 +45,7 @@
"source-map": "^0.5.0"
},
"devDependencies": {
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.43",
"@babel/register": "7.0.0-beta.43"
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.45",
"@babel/register": "7.0.0-beta.45"
}
}

View File

@@ -8,15 +8,19 @@ import {
type ValidatedOptions,
type IgnoreList,
type ConfigApplicableTest,
type BabelrcSearch,
} from "./validation/options";
const debug = buildDebug("babel:config:config-chain");
import {
findPackageData,
findRelativeConfig,
findRootConfig,
loadConfig,
type ConfigFile,
type IgnoreFile,
type FilePackageData,
} from "./files";
import { makeWeakCache, makeStrongCache } from "./caching";
@@ -106,6 +110,7 @@ const loadPresetOverridesEnvDescriptors = makeWeakCache(
export type RootConfigChain = ConfigChain & {
babelrc: ConfigFile | void,
config: ConfigFile | void,
ignore: IgnoreFile | void,
};
@@ -125,24 +130,57 @@ export function buildRootChain(
);
if (!programmaticChain) return null;
let ignore, babelrc;
const {
root: rootDir = ".",
babelrc = true,
babelrcRoots,
configFile: configFileName = true,
} = opts;
const absoluteRoot = path.resolve(context.cwd, rootDir);
let configFile;
if (typeof configFileName === "string") {
configFile = loadConfig(configFileName, context.cwd, context.envName);
} else if (configFileName === true) {
configFile = findRootConfig(absoluteRoot, context.envName);
}
const configFileChain = emptyChain();
if (configFile) {
const result = loadFileChain(configFile, context);
if (!result) return null;
mergeChain(configFileChain, result);
}
const pkgData =
typeof context.filename === "string"
? findPackageData(context.filename)
: null;
let ignoreFile, babelrcFile;
const fileChain = emptyChain();
// resolve all .babelrc files
if (opts.babelrc !== false && context.filename !== null) {
const filename = context.filename;
({ ignore, config: babelrc } = findRelativeConfig(
filename,
if (
babelrc &&
pkgData &&
babelrcLoadEnabled(context, pkgData, babelrcRoots, absoluteRoot)
) {
({ ignore: ignoreFile, config: babelrcFile } = findRelativeConfig(
pkgData,
context.envName,
));
if (ignore && shouldIgnore(context, ignore.ignore, null, ignore.dirname)) {
if (
ignoreFile &&
shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)
) {
return null;
}
if (babelrc) {
const result = loadFileChain(babelrc, context);
if (babelrcFile) {
const result = loadFileChain(babelrcFile, context);
if (!result) return null;
mergeChain(fileChain, result);
@@ -152,7 +190,7 @@ export function buildRootChain(
// Insert file chain in front so programmatic options have priority
// over configuration file chain items.
const chain = mergeChain(
mergeChain(emptyChain(), fileChain),
mergeChain(mergeChain(emptyChain(), configFileChain), fileChain),
programmaticChain,
);
@@ -160,11 +198,39 @@ export function buildRootChain(
plugins: dedupDescriptors(chain.plugins),
presets: dedupDescriptors(chain.presets),
options: chain.options.map(o => normalizeOptions(o)),
ignore: ignore || undefined,
babelrc: babelrc || undefined,
ignore: ignoreFile || undefined,
babelrc: babelrcFile || undefined,
config: configFile || undefined,
};
}
function babelrcLoadEnabled(
context: ConfigContext,
pkgData: FilePackageData,
babelrcRoots: BabelrcSearch | void,
absoluteRoot: string,
): boolean {
if (typeof babelrcRoots === "boolean") return babelrcRoots;
// Fast path to avoid having to load micromatch if the babelrc is just
// loading in the standard root directory.
if (babelrcRoots === undefined) {
return pkgData.directories.indexOf(absoluteRoot) !== -1;
}
let babelrcPatterns = babelrcRoots;
if (!Array.isArray(babelrcPatterns)) babelrcPatterns = [babelrcPatterns];
babelrcPatterns = babelrcPatterns.map(pat => path.resolve(context.cwd, pat));
// Fast path to avoid having to load micromatch if the babelrc is just
// loading in the standard root directory.
if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) {
return pkgData.directories.indexOf(absoluteRoot) !== -1;
}
return micromatch(pkgData.directories, babelrcPatterns).length > 0;
}
/**
* Build a config chain for just the programmatic options passed into Babel.
*/

View File

@@ -5,45 +5,35 @@ import path from "path";
import fs from "fs";
import json5 from "json5";
import resolve from "resolve";
import { makeStrongCache, type CacheConfigurator } from "../caching";
import {
makeStrongCache,
makeWeakCache,
type CacheConfigurator,
} from "../caching";
import makeAPI from "../helpers/config-api";
import { makeStaticFileCache } from "./utils";
import type { FilePackageData, RelativeConfig, ConfigFile } from "./types";
const debug = buildDebug("babel:config:loading:files:configuration");
export type ConfigFile = {
filepath: string,
dirname: string,
options: {},
};
export type IgnoreFile = {
filepath: string,
dirname: string,
ignore: Array<string>,
};
export type RelativeConfig = {
config: ConfigFile | null,
ignore: IgnoreFile | null,
};
const BABEL_CONFIG_JS_FILENAME = "babel.config.js";
const BABELRC_FILENAME = ".babelrc";
const BABELRC_JS_FILENAME = ".babelrc.js";
const PACKAGE_FILENAME = "package.json";
const BABELIGNORE_FILENAME = ".babelignore";
export function findRelativeConfig(
filepath: string,
packageData: FilePackageData,
envName: string,
): RelativeConfig {
let config = null;
let ignore = null;
const dirname = path.dirname(filepath);
let loc = dirname;
while (true) {
const dirname = path.dirname(packageData.filepath);
for (const loc of packageData.directories) {
if (!config) {
config = [BABELRC_FILENAME, BABELRC_JS_FILENAME, PACKAGE_FILENAME].reduce(
config = [BABELRC_FILENAME, BABELRC_JS_FILENAME].reduce(
(previousConfig: ConfigFile | null, name) => {
const filepath = path.join(loc, name);
const config = readConfig(filepath, envName);
@@ -62,6 +52,23 @@ export function findRelativeConfig(
null,
);
const pkgConfig =
packageData.pkg && packageData.pkg.dirname === loc
? packageToBabelConfig(packageData.pkg)
: null;
if (pkgConfig) {
if (config) {
throw new Error(
`Multiple configuration files found. Please remove one:\n` +
` - ${path.basename(pkgConfig.filepath)}#babel\n` +
` - ${path.basename(config.filepath)}\n` +
`from ${loc}`,
);
}
config = pkgConfig;
}
if (config) {
debug("Found configuration %o from %o.", config.filepath, dirname);
}
@@ -75,15 +82,24 @@ export function findRelativeConfig(
debug("Found ignore %o from %o.", ignore.filepath, dirname);
}
}
const nextLoc = path.dirname(loc);
if (loc === nextLoc) break;
loc = nextLoc;
}
return { config, ignore };
}
export function findRootConfig(
dirname: string,
envName: string,
): ConfigFile | null {
const filepath = path.resolve(dirname, BABEL_CONFIG_JS_FILENAME);
const conf = readConfig(filepath, envName);
if (conf) {
debug("Found root config %o in $o.", BABEL_CONFIG_JS_FILENAME, dirname);
}
return conf;
}
export function loadConfig(
name: string,
dirname: string,
@@ -107,7 +123,7 @@ export function loadConfig(
function readConfig(filepath, envName): ConfigFile | null {
return path.extname(filepath) === ".js"
? readConfigJS(filepath, { envName })
: readConfigFile(filepath);
: readConfigJSON5(filepath);
}
const LOADING_CONFIGS = new Set();
@@ -180,27 +196,34 @@ const readConfigJS = makeStrongCache(
},
);
const readConfigFile = makeStaticFileCache((filepath, content) => {
let options;
if (path.basename(filepath) === PACKAGE_FILENAME) {
try {
options = JSON.parse(content).babel;
} catch (err) {
err.message = `${filepath}: Error while parsing JSON - ${err.message}`;
throw err;
}
if (!options) return null;
} else {
try {
options = json5.parse(content);
} catch (err) {
err.message = `${filepath}: Error while parsing config - ${err.message}`;
throw err;
const packageToBabelConfig = makeWeakCache(
(file: ConfigFile): ConfigFile | null => {
if (typeof file.options.babel === "undefined") return null;
const babel = file.options.babel;
if (typeof babel !== "object" || Array.isArray(babel) || babel === null) {
throw new Error(`${file.filepath}: .babel property must be an object`);
}
if (!options) throw new Error(`${filepath}: No config detected`);
return {
filepath: file.filepath,
dirname: file.dirname,
options: babel,
};
},
);
const readConfigJSON5 = makeStaticFileCache((filepath, content) => {
let options;
try {
options = json5.parse(content);
} catch (err) {
err.message = `${filepath}: Error while parsing config - ${err.message}`;
throw err;
}
if (!options) throw new Error(`${filepath}: No config detected`);
if (typeof options !== "object") {
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
}
@@ -228,27 +251,6 @@ const readIgnoreConfig = makeStaticFileCache((filepath, content) => {
};
});
function makeStaticFileCache<T>(fn: (string, string) => T): string => T | null {
return makeStrongCache((filepath, cache) => {
if (cache.invalidate(() => fileMtime(filepath)) === null) {
cache.forever();
return null;
}
return fn(filepath, fs.readFileSync(filepath, "utf8"));
});
}
function fileMtime(filepath: string): number | null {
try {
return +fs.statSync(filepath).mtime;
} catch (e) {
if (e.code !== "ENOENT") throw e;
}
return null;
}
function throwConfigError() {
throw new Error(`\
Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured

View File

@@ -1,17 +1,42 @@
// @flow
import type { ConfigFile, IgnoreFile, RelativeConfig } from "./configuration";
import type {
ConfigFile,
IgnoreFile,
RelativeConfig,
FilePackageData,
} from "./types";
export type { ConfigFile, IgnoreFile, RelativeConfig };
export type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData };
export function findRelativeConfig(
filepath: string,
envName: string, // eslint-disable-line no-unused-vars
): RelativeConfig {
return { config: null, ignore: null };
export function findPackageData(filepath: string): FilePackageData {
return {
filepath,
directories: [],
pkg: null,
isPackage: false,
};
}
export function loadConfig(name: string, dirname: string): ConfigFile {
export function findRelativeConfig(
pkgData: FilePackageData,
envName: string, // eslint-disable-line no-unused-vars
): RelativeConfig {
return { pkg: null, config: null, ignore: null };
}
export function findRootConfig(
dirname: string,
envName: string, // eslint-disable-line no-unused-vars
): ConfigFile | null {
return null;
}
export function loadConfig(
name: string,
dirname: string,
envName: string, // eslint-disable-line no-unused-vars
): ConfigFile {
throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);
}

View File

@@ -7,5 +7,22 @@ import typeof * as indexType from "./index";
// exports of index-browser, since this file may be replaced at bundle time with index-browser.
((({}: any): $Exact<indexBrowserType>): $Exact<indexType>);
export * from "./configuration";
export * from "./plugins";
export { findPackageData } from "./package";
export {
findRelativeConfig,
findRootConfig,
loadConfig,
} from "./configuration";
export type {
ConfigFile,
IgnoreFile,
RelativeConfig,
FilePackageData,
} from "./types";
export {
resolvePlugin,
resolvePreset,
loadPlugin,
loadPreset,
} from "./plugins";

View File

@@ -0,0 +1,60 @@
// @flow
import path from "path";
import { makeStaticFileCache } from "./utils";
import type { ConfigFile, FilePackageData } from "./types";
const PACKAGE_FILENAME = "package.json";
/**
* Find metadata about the package that this file is inside of. Resolution
* of Babel's config requires general package information to decide when to
* search for .babelrc files
*/
export function findPackageData(filepath: string): FilePackageData {
let pkg = null;
const directories = [];
let isPackage = true;
let dirname = path.dirname(filepath);
while (!pkg && path.basename(dirname) !== "node_modules") {
directories.push(dirname);
pkg = readConfigPackage(path.join(dirname, PACKAGE_FILENAME));
const nextLoc = path.dirname(dirname);
if (dirname === nextLoc) {
isPackage = false;
break;
}
dirname = nextLoc;
}
return { filepath, directories, pkg, isPackage };
}
const readConfigPackage = makeStaticFileCache(
(filepath, content): ConfigFile => {
let options;
try {
options = JSON.parse(content);
} catch (err) {
err.message = `${filepath}: Error while parsing JSON - ${err.message}`;
throw err;
}
if (typeof options !== "object") {
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
}
if (Array.isArray(options)) {
throw new Error(`${filepath}: Expected config object but found array`);
}
return {
filepath,
dirname: path.dirname(filepath),
options,
};
},
);

View File

@@ -0,0 +1,38 @@
// @flow
export type ConfigFile = {
filepath: string,
dirname: string,
options: {},
};
export type IgnoreFile = {
filepath: string,
dirname: string,
ignore: Array<string>,
};
export type RelativeConfig = {
// The actual config, either from package.json#babel, .babelrc, or
// .babelrc.js, if there was one.
config: ConfigFile | null,
// The .babelignore, if there was one.
ignore: IgnoreFile | null,
};
export type FilePackageData = {
// The file in the package.
filepath: string,
// Any ancestor directories of the file that are within the package.
directories: Array<string>,
// The contents of the package.json. May not be found if the package just
// terminated at a node_modules folder without finding one.
pkg: ConfigFile | null,
// True if a package.json or node_modules folder was found while traversing
// the directory structure.
isPackage: boolean,
};

View File

@@ -0,0 +1,27 @@
// @flow
import fs from "fs";
import { makeStrongCache } from "../caching";
export function makeStaticFileCache<T>(
fn: (string, string) => T,
): string => T | null {
return makeStrongCache((filepath, cache) => {
if (cache.invalidate(() => fileMtime(filepath)) === null) {
cache.forever();
return null;
}
return fn(filepath, fs.readFileSync(filepath, "utf8"));
});
}
function fileMtime(filepath: string): number | null {
try {
return +fs.statSync(filepath).mtime;
} catch (e) {
if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e;
}
return null;
}

View File

@@ -17,6 +17,7 @@ export default function loadPrivatePartialConfig(
context: ConfigContext,
ignore: IgnoreFile | void,
babelrc: ConfigFile | void,
config: ConfigFile | void,
} | null {
if (
inputOpts != null &&
@@ -64,6 +65,7 @@ export default function loadPrivatePartialConfig(
context,
ignore: configChain.ignore,
babelrc: configChain.babelrc,
config: configChain.config,
};
}
@@ -71,7 +73,7 @@ export function loadPartialConfig(inputOpts: mixed): PartialConfig | null {
const result = loadPrivatePartialConfig(inputOpts);
if (!result) return null;
const { options, babelrc, ignore } = result;
const { options, babelrc, ignore, config } = result;
(options.plugins || []).forEach(item => {
if (item.value instanceof Plugin) {
@@ -86,6 +88,7 @@ export function loadPartialConfig(inputOpts: mixed): PartialConfig | null {
options,
babelrc ? babelrc.filepath : undefined,
ignore ? ignore.filepath : undefined,
config ? config.filepath : undefined,
);
}
@@ -99,15 +102,18 @@ class PartialConfig {
options: ValidatedOptions;
babelrc: string | void;
babelignore: string | void;
config: string | void;
constructor(
options: ValidatedOptions,
babelrc: string | void,
ignore: string | void,
config: string | void,
) {
this.options = options;
this.babelignore = ignore;
this.babelrc = babelrc;
this.config = config;
// Freeze since this is a public API and it should be extremely obvious that
// reassigning properties on here does nothing.
@@ -122,7 +128,7 @@ class PartialConfig {
* this.babelrc directly.
*/
hasFilesystemConfig(): boolean {
return this.babelrc !== undefined;
return this.babelrc !== undefined || this.config !== undefined;
}
}
Object.freeze(PartialConfig.prototype);

View File

@@ -1,6 +1,8 @@
// @flow
import type {
ConfigFileSearch,
BabelrcSearch,
IgnoreList,
IgnoreItem,
PluginList,
@@ -164,6 +166,45 @@ function checkValidTest(value: mixed): boolean {
);
}
export function assertConfigFileSearch(
key: string,
value: mixed,
): ConfigFileSearch | void {
if (
value !== undefined &&
typeof value !== "boolean" &&
typeof value !== "string"
) {
throw new Error(
`.${key} must be a undefined, a boolean, a string, ` +
`got ${JSON.stringify(value)}`,
);
}
return value;
}
export function assertBabelrcSearch(
key: string,
value: mixed,
): BabelrcSearch | void {
if (value === undefined || typeof value === "boolean") return value;
if (Array.isArray(value)) {
value.forEach((item, i) => {
if (typeof item !== "string") {
throw new Error(`.${key}[${i}] must be a string.`);
}
});
} else if (typeof value !== "string") {
throw new Error(
`.${key} must be a undefined, a boolean, a string, ` +
`or an array of strings, got ${JSON.stringify(value)}`,
);
}
return (value: any);
}
export function assertPluginList(key: string, value: mixed): PluginList | void {
const arr = assertArray(key, value);
if (arr) {

View File

@@ -13,6 +13,8 @@ import {
assertIgnoreList,
assertPluginList,
assertConfigApplicableTest,
assertConfigFileSearch,
assertBabelrcSearch,
assertFunction,
assertSourceMaps,
assertCompact,
@@ -23,6 +25,11 @@ import {
const ROOT_VALIDATORS: ValidatorSet = {
cwd: (assertString: Validator<$PropertyType<ValidatedOptions, "cwd">>),
root: (assertString: Validator<$PropertyType<ValidatedOptions, "root">>),
configFile: (assertConfigFileSearch: Validator<
$PropertyType<ValidatedOptions, "configFile">,
>),
filename: (assertString: Validator<
$PropertyType<ValidatedOptions, "filename">,
>),
@@ -32,6 +39,9 @@ const ROOT_VALIDATORS: ValidatorSet = {
babelrc: (assertBoolean: Validator<
$PropertyType<ValidatedOptions, "babelrc">,
>),
babelrcRoots: (assertBabelrcSearch: Validator<
$PropertyType<ValidatedOptions, "babelrcRoots">,
>),
code: (assertBoolean: Validator<$PropertyType<ValidatedOptions, "code">>),
ast: (assertBoolean: Validator<$PropertyType<ValidatedOptions, "ast">>),
@@ -151,6 +161,9 @@ export type ValidatedOptions = {
filename?: string,
filenameRelative?: string,
babelrc?: boolean,
babelrcRoots?: BabelrcSearch,
configFile?: ConfigFileSearch,
root?: string,
code?: boolean,
ast?: boolean,
inputSourceMap?: RootInputSourceMapOption,
@@ -223,6 +236,8 @@ export type PluginList = $ReadOnlyArray<PluginItem>;
export type OverridesList = Array<ValidatedOptions>;
export type ConfigApplicableTest = IgnoreItem | Array<IgnoreItem>;
export type ConfigFileSearch = string | boolean;
export type BabelrcSearch = boolean | string | Array<string>;
export type SourceMapsOption = boolean | "inline" | "both";
export type SourceTypeOption = "module" | "script" | "unambiguous";
export type CompactOption = boolean | "auto";

View File

@@ -294,6 +294,7 @@ describe("api", function() {
process.env.BABEL_ENV = "development";
const result = babel.transform("", {
cwd: path.join(__dirname, "fixtures", "config", "complex-plugin-config"),
filename: path.join(
__dirname,
"fixtures",

View File

@@ -11,6 +11,7 @@ describe("buildConfigChain", function() {
describe("single", () => {
it("should process matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: fixture("nonexistant-fake"),
@@ -22,6 +23,7 @@ describe("buildConfigChain", function() {
it("should process matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: new RegExp(fixture("nonexistant-fake")),
@@ -33,6 +35,7 @@ describe("buildConfigChain", function() {
it("should process matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: p => p.indexOf(fixture("nonexistant-fake")) === 0,
@@ -44,6 +47,7 @@ describe("buildConfigChain", function() {
it("should process non-matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: fixture("nonexistant-fake-unknown"),
@@ -55,6 +59,7 @@ describe("buildConfigChain", function() {
it("should process non-matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: new RegExp(fixture("nonexistant-unknown")),
@@ -66,6 +71,7 @@ describe("buildConfigChain", function() {
it("should process non-matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: p => p.indexOf(fixture("nonexistant-unknown")) === 0,
@@ -79,6 +85,7 @@ describe("buildConfigChain", function() {
describe("array", () => {
it("should process matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: [fixture("nonexistant-fake")],
@@ -90,6 +97,7 @@ describe("buildConfigChain", function() {
it("should process matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: [new RegExp(fixture("nonexistant-fake"))],
@@ -101,6 +109,7 @@ describe("buildConfigChain", function() {
it("should process matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: [p => p.indexOf(fixture("nonexistant-fake")) === 0],
@@ -112,6 +121,7 @@ describe("buildConfigChain", function() {
it("should process non-matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: [fixture("nonexistant-fake-unknown")],
@@ -123,6 +133,7 @@ describe("buildConfigChain", function() {
it("should process non-matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: [new RegExp(fixture("nonexistant-unknown"))],
@@ -134,6 +145,7 @@ describe("buildConfigChain", function() {
it("should process non-matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
test: [p => p.indexOf(fixture("nonexistant-unknown")) === 0],
@@ -149,6 +161,7 @@ describe("buildConfigChain", function() {
describe("single", () => {
it("should process matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: fixture("nonexistant-fake"),
@@ -160,6 +173,7 @@ describe("buildConfigChain", function() {
it("should process matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: new RegExp(fixture("nonexistant-fake")),
@@ -171,6 +185,7 @@ describe("buildConfigChain", function() {
it("should process matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: p => p.indexOf(fixture("nonexistant-fake")) === 0,
@@ -182,6 +197,7 @@ describe("buildConfigChain", function() {
it("should process non-matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: fixture("nonexistant-fake-unknown"),
@@ -193,6 +209,7 @@ describe("buildConfigChain", function() {
it("should process non-matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: new RegExp(fixture("nonexistant-unknown")),
@@ -204,6 +221,7 @@ describe("buildConfigChain", function() {
it("should process non-matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: p => p.indexOf(fixture("nonexistant-unknown")) === 0,
@@ -217,6 +235,7 @@ describe("buildConfigChain", function() {
describe("array", () => {
it("should process matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: [fixture("nonexistant-fake")],
@@ -228,6 +247,7 @@ describe("buildConfigChain", function() {
it("should process matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: [new RegExp(fixture("nonexistant-fake"))],
@@ -239,6 +259,7 @@ describe("buildConfigChain", function() {
it("should process matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: [p => p.indexOf(fixture("nonexistant-fake")) === 0],
@@ -250,6 +271,7 @@ describe("buildConfigChain", function() {
it("should process non-matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: [fixture("nonexistant-fake-unknown")],
@@ -261,6 +283,7 @@ describe("buildConfigChain", function() {
it("should process non-matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: [new RegExp(fixture("nonexistant-unknown"))],
@@ -272,6 +295,7 @@ describe("buildConfigChain", function() {
it("should process non-matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
include: [p => p.indexOf(fixture("nonexistant-unknown")) === 0],
@@ -287,6 +311,7 @@ describe("buildConfigChain", function() {
describe("single", () => {
it("should process matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: fixture("nonexistant-fake"),
@@ -298,6 +323,7 @@ describe("buildConfigChain", function() {
it("should process matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: new RegExp(fixture("nonexistant-fake")),
@@ -309,6 +335,7 @@ describe("buildConfigChain", function() {
it("should process matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: p => p.indexOf(fixture("nonexistant-fake")) === 0,
@@ -320,6 +347,7 @@ describe("buildConfigChain", function() {
it("should process non-matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: fixture("nonexistant-fake-unknown"),
@@ -331,6 +359,7 @@ describe("buildConfigChain", function() {
it("should process non-matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: new RegExp(fixture("nonexistant-unknown")),
@@ -342,6 +371,7 @@ describe("buildConfigChain", function() {
it("should process non-matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: p => p.indexOf(fixture("nonexistant-unknown")) === 0,
@@ -355,6 +385,7 @@ describe("buildConfigChain", function() {
describe("array", () => {
it("should process matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: [fixture("nonexistant-fake")],
@@ -366,6 +397,7 @@ describe("buildConfigChain", function() {
it("should process matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: [new RegExp(fixture("nonexistant-fake"))],
@@ -377,6 +409,7 @@ describe("buildConfigChain", function() {
it("should process matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: [p => p.indexOf(fixture("nonexistant-fake")) === 0],
@@ -388,6 +421,7 @@ describe("buildConfigChain", function() {
it("should process non-matching string values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: [fixture("nonexistant-fake-unknown")],
@@ -399,6 +433,7 @@ describe("buildConfigChain", function() {
it("should process non-matching RegExp values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: [new RegExp(fixture("nonexistant-unknown"))],
@@ -410,6 +445,7 @@ describe("buildConfigChain", function() {
it("should process non-matching function values", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
exclude: [p => p.indexOf(fixture("nonexistant-unknown")) === 0],
@@ -424,6 +460,7 @@ describe("buildConfigChain", function() {
describe("ignore", () => {
it("should ignore files that match", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
ignore: [
@@ -441,6 +478,7 @@ describe("buildConfigChain", function() {
it("should not ignore files that don't match", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
ignore: [
@@ -456,6 +494,7 @@ describe("buildConfigChain", function() {
describe("only", () => {
it("should ignore files that don't match", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
only: [
@@ -469,6 +508,7 @@ describe("buildConfigChain", function() {
it("should not ignore files that match", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
only: [
@@ -484,6 +524,7 @@ describe("buildConfigChain", function() {
describe("ignore/only", () => {
it("should ignore files that match ignore and don't match only", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
ignore: [fixture("nonexistant-fake", "src.js")],
@@ -495,6 +536,7 @@ describe("buildConfigChain", function() {
it("should ignore files that match ignore and also only", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
ignore: [fixture("nonexistant-fake", "src.js")],
@@ -506,6 +548,7 @@ describe("buildConfigChain", function() {
it("should not ignore files that match only and not ignore", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
only: [fixture("nonexistant-fake", "src.js")],
@@ -516,6 +559,7 @@ describe("buildConfigChain", function() {
it("should not ignore files when no ignore/only are specified", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
});
@@ -525,6 +569,7 @@ describe("buildConfigChain", function() {
it("should allow negation of only", () => {
const opts1 = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
only: [
@@ -535,6 +580,7 @@ describe("buildConfigChain", function() {
expect(opts1).toBeNull();
const opts2 = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
only: [
@@ -545,6 +591,7 @@ describe("buildConfigChain", function() {
expect(opts2).not.toBeNull();
const opts3 = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "folder", "src.js"),
babelrc: false,
only: [
@@ -557,6 +604,7 @@ describe("buildConfigChain", function() {
it("should allow negation of ignore", () => {
const opts1 = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
ignore: [
@@ -568,6 +616,7 @@ describe("buildConfigChain", function() {
// Tests disabled pending https://github.com/babel/babel/issues/6907
// const opts2 = loadOptions({
// cwd: fixture("nonexistant-fake"),
// filename: fixture("nonexistant-fake", "src.js"),
// babelrc: false,
// ignore: [
@@ -575,9 +624,10 @@ describe("buildConfigChain", function() {
// fixture("nonexistant-fake"),
// ],
// });
// assert.notEqual(opts2, null);
// expect(opts2).not.toBeNull();
//
// const opts3 = loadOptions({
// cwd: fixture("nonexistant-fake"),
// filename: fixture("nonexistant-fake", "folder", "src.js"),
// babelrc: false,
// ignore: [
@@ -585,7 +635,7 @@ describe("buildConfigChain", function() {
// fixture("nonexistant-fake"),
// ],
// });
// assert.notEqual(opts3, null);
// expect(opts3).not.toBeNull();
});
});
@@ -718,13 +768,13 @@ describe("buildConfigChain", function() {
"package.json",
);
const opts1 = loadOptions({ filename });
const opts2 = loadOptions({ filename });
const opts1 = loadOptions({ filename, cwd: path.dirname(filename) });
const opts2 = loadOptions({ filename, cwd: path.dirname(filename) });
touch(pkgJSON);
const opts3 = loadOptions({ filename });
const opts4 = loadOptions({ filename });
const opts3 = loadOptions({ filename, cwd: path.dirname(filename) });
const opts4 = loadOptions({ filename, cwd: path.dirname(filename) });
expect(opts1.plugins).toHaveLength(1);
expect(opts2.plugins).toHaveLength(1);
@@ -752,13 +802,13 @@ describe("buildConfigChain", function() {
".babelrc",
);
const opts1 = loadOptions({ filename });
const opts2 = loadOptions({ filename });
const opts1 = loadOptions({ filename, cwd: path.dirname(filename) });
const opts2 = loadOptions({ filename, cwd: path.dirname(filename) });
touch(babelrcFile);
const opts3 = loadOptions({ filename });
const opts4 = loadOptions({ filename });
const opts3 = loadOptions({ filename, cwd: path.dirname(filename) });
const opts4 = loadOptions({ filename, cwd: path.dirname(filename) });
expect(opts1.plugins).toHaveLength(1);
expect(opts2.plugins).toHaveLength(1);
@@ -780,11 +830,19 @@ describe("buildConfigChain", function() {
"src.js",
);
const opts1 = loadOptions({ filename });
const opts2 = loadOptions({ filename });
const opts1 = loadOptions({ filename, cwd: path.dirname(filename) });
const opts2 = loadOptions({ filename, cwd: path.dirname(filename) });
const opts3 = loadOptions({ filename, envName: "new-env" });
const opts4 = loadOptions({ filename, envName: "new-env" });
const opts3 = loadOptions({
filename,
envName: "new-env",
cwd: path.dirname(filename),
});
const opts4 = loadOptions({
filename,
envName: "new-env",
cwd: path.dirname(filename),
});
expect(opts1.plugins).toHaveLength(1);
expect(opts2.plugins).toHaveLength(1);
@@ -803,6 +861,7 @@ describe("buildConfigChain", function() {
describe("overrides merging", () => {
it("should apply matching overrides over base configs", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
comments: true,
@@ -819,6 +878,7 @@ describe("buildConfigChain", function() {
it("should not apply non-matching overrides over base configs", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
comments: true,
@@ -860,9 +920,15 @@ describe("buildConfigChain", function() {
it("should load .babelrc", () => {
const filename = fixture("config-files", "babelrc", "src.js");
expect(loadOptions({ filename })).toEqual({
expect(
loadOptions({
filename,
cwd: path.dirname(filename),
}),
).toEqual({
...getDefaults(),
filename,
cwd: path.dirname(filename),
comments: true,
});
});
@@ -870,9 +936,10 @@ describe("buildConfigChain", function() {
it("should load .babelrc.js", () => {
const filename = fixture("config-files", "babelrc-js", "src.js");
expect(loadOptions({ filename })).toEqual({
expect(loadOptions({ filename, cwd: path.dirname(filename) })).toEqual({
...getDefaults(),
filename,
cwd: path.dirname(filename),
comments: true,
});
});
@@ -880,9 +947,10 @@ describe("buildConfigChain", function() {
it("should load package.json#babel", () => {
const filename = fixture("config-files", "pkg", "src.js");
expect(loadOptions({ filename })).toEqual({
expect(loadOptions({ filename, cwd: path.dirname(filename) })).toEqual({
...getDefaults(),
filename,
cwd: path.dirname(filename),
comments: true,
});
});
@@ -890,39 +958,40 @@ describe("buildConfigChain", function() {
it("should load .babelignore", () => {
const filename = fixture("config-files", "babelignore", "src.js");
expect(loadOptions({ filename })).toBeNull();
expect(loadOptions({ filename, cwd: path.dirname(filename) })).toBeNull();
});
it("should throw if there are both .babelrc and .babelrc.js", () => {
const filename = fixture("config-files", "both-babelrc", "src.js");
expect(() => loadOptions({ filename })).toThrow(
/Multiple configuration files found/,
);
expect(() =>
loadOptions({ filename, cwd: path.dirname(filename) }),
).toThrow(/Multiple configuration files found/);
});
it("should throw if there are both .babelrc and package.json", () => {
const filename = fixture("config-files", "pkg-babelrc", "src.js");
expect(() => loadOptions({ filename })).toThrow(
/Multiple configuration files found/,
);
expect(() =>
loadOptions({ filename, cwd: path.dirname(filename) }),
).toThrow(/Multiple configuration files found/);
});
it("should throw if there are both .babelrc.js and package.json", () => {
const filename = fixture("config-files", "pkg-babelrc-js", "src.js");
expect(() => loadOptions({ filename })).toThrow(
/Multiple configuration files found/,
);
expect(() =>
loadOptions({ filename, cwd: path.dirname(filename) }),
).toThrow(/Multiple configuration files found/);
});
it("should ignore package.json without a 'babel' property", () => {
const filename = fixture("config-files", "pkg-ignored", "src.js");
expect(loadOptions({ filename })).toEqual({
expect(loadOptions({ filename, cwd: path.dirname(filename) })).toEqual({
...getDefaults(),
filename,
cwd: path.dirname(filename),
comments: true,
});
});
@@ -930,23 +999,25 @@ describe("buildConfigChain", function() {
it("should show helpful errors for .babelrc", () => {
const filename = fixture("config-files", "babelrc-error", "src.js");
expect(() => loadOptions({ filename })).toThrow(
/Error while parsing config - /,
);
expect(() =>
loadOptions({ filename, cwd: path.dirname(filename) }),
).toThrow(/Error while parsing config - /);
});
it("should show helpful errors for .babelrc.js", () => {
const filename = fixture("config-files", "babelrc-js-error", "src.js");
expect(() => loadOptions({ filename })).toThrow(/Babelrc threw an error/);
expect(() =>
loadOptions({ filename, cwd: path.dirname(filename) }),
).toThrow(/Babelrc threw an error/);
});
it("should show helpful errors for package.json", () => {
const filename = fixture("config-files", "pkg-error", "src.js");
expect(() => loadOptions({ filename })).toThrow(
/Error while parsing JSON - /,
);
expect(() =>
loadOptions({ filename, cwd: path.dirname(filename) }),
).toThrow(/Error while parsing JSON - /);
});
});
});

View File

@@ -25,6 +25,7 @@ describe("@babel/core config loading", () => {
function makeOpts(skipProgrammatic = false) {
return {
cwd: path.dirname(FILEPATH),
filename: FILEPATH,
presets: skipProgrammatic
? null

View File

@@ -57,7 +57,7 @@
"column": 11
}
},
"expression": {
"callee": {
"type": "Identifier",
"start": 1,
"end": 11,

View File

@@ -1,10 +1,6 @@
class A {
prop1 = () => this;
static prop2 = () => this;
prop3 = () => arguments;
static prop4 = () => arguments;
prop5 = this;
static prop6 = this;
prop7 = arguments;
static prop8 = arguments;
}

View File

@@ -1,10 +1,6 @@
class A {
prop1 = () => this;
static prop2 = () => this;
prop3 = () => arguments;
static prop4 = () => arguments;
prop5 = this;
static prop6 = this;
prop7 = arguments;
static prop8 = arguments;
}

View File

@@ -1,7 +1,7 @@
var Foo =
/*#__PURE__*/
function (_Bar) {
babelHelpers.inherits(Foo, _Bar);
"use strict";
function Foo(options) {
babelHelpers.classCallCheck(this, Foo);
@@ -11,8 +11,9 @@ function (_Bar) {
this;
};
return babelHelpers.possibleConstructorReturn(this, (Foo.__proto__ || Object.getPrototypeOf(Foo)).call(this, parentOptions));
return babelHelpers.possibleConstructorReturn(this, babelHelpers.getPrototypeOf(Foo).call(this, parentOptions));
}
babelHelpers.inherits(Foo, _Bar);
return Foo;
}(Bar);

View File

@@ -1,4 +1,7 @@
{
"compact": false,
"presets": ["es2015","stage-2"]
"presets": [
"es2015",
["stage-2", { "decoratorsLegacy": true }]
]
}

View File

@@ -1,6 +1,8 @@
var Test =
/*#__PURE__*/
function () {
"use strict";
function Test() {
babelHelpers.classCallCheck(this, Test);
}

View File

@@ -4,7 +4,7 @@
"column": 10
},
"generated": {
"line": 11,
"line": 13,
"column": 15
}
}]
}]

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/generator",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"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.43",
"@babel/types": "7.0.0-beta.45",
"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.43",
"babylon": "7.0.0-beta.43"
"@babel/helper-fixtures": "7.0.0-beta.45",
"babylon": "7.0.0-beta.45"
}
}

View File

@@ -117,6 +117,21 @@ export function ClassProperty(node: Object) {
this.semicolon();
}
export function ClassPrivateProperty(node: Object) {
if (node.static) {
this.word("static");
this.space();
}
this.print(node.key, node);
if (node.value) {
this.space();
this.token("=");
this.space();
this.print(node.value, node);
}
this.semicolon();
}
export function ClassMethod(node: Object) {
this._classMethodHead(node);
this.space();

View File

@@ -91,7 +91,7 @@ export function Super() {
export function Decorator(node: Object) {
this.token("@");
this.print(node.expression, node);
this.print(node.callee, node);
this.newline();
}
@@ -254,3 +254,8 @@ export function MetaProperty(node: Object) {
this.token(".");
this.print(node.property, node);
}
export function PrivateName(node: Object) {
this.token("#");
this.print(node.id, node);
}

View File

@@ -198,8 +198,10 @@ export function FunctionTypeAnnotation(node: Object, parent: Object) {
export function FunctionTypeParam(node: Object) {
this.print(node.name, node);
if (node.optional) this.token("?");
this.token(":");
this.space();
if (node.name) {
this.token(":");
this.space();
}
this.print(node.typeAnnotation, node);
}
@@ -228,6 +230,12 @@ export function _interfaceish(node: Object) {
this.space();
this.printList(node.mixins, node);
}
if (node.implements && node.implements.length) {
this.space();
this.word("implements");
this.space();
this.printList(node.implements, node);
}
this.space();
this.print(node.body, node);
}

View File

@@ -0,0 +1,5 @@
class A implements B {}
class A implements B, C {}
declare class A implements B {}
declare class A mixins B implements C {}
declare class A implements B, C {}

View File

@@ -0,0 +1,7 @@
class A implements B {}
class A implements B, C {}
declare class A implements B {}
declare class A mixins B implements C {}
declare class A implements B, C {}

View File

@@ -12,3 +12,5 @@ type overloads =
& ((x: string) => number)
& ((x: number) => string)
;
type func = string => string;

View File

@@ -7,4 +7,5 @@ type union = {
} | {
type: "B"
};
type overloads = (x: string) => number & (x: number) => string;
type overloads = (x: string) => number & (x: number) => string;
type func = (string) => string;

View File

@@ -26,6 +26,11 @@ class Foo {
async;
foo; bar;
foo = 0; bar = 1;
#foo;
#foo = 1;
static #foo;
static #foo = Foo.#foo;
}
class A1 {

View File

@@ -1 +1 @@
{ "plugins": ["classProperties"] }
{ "plugins": ["classProperties", "classPrivateProperties"] }

View File

@@ -26,6 +26,10 @@ class Foo {
bar;
foo = 0;
bar = 1;
#foo;
#foo = 1;
static #foo;
static #foo = Foo.#foo;
}
class A1 {
@@ -65,4 +69,4 @@ class A6 {
class A7 {
static get static() {}
}
}

View File

@@ -1,8 +1,6 @@
import Printer from "../lib/printer";
import generate, { CodeGenerator } from "../lib";
import assert from "assert";
import { parse } from "babylon";
import chai from "chai";
import * as t from "@babel/types";
import fs from "fs";
import path from "path";
@@ -11,12 +9,12 @@ import fixtures from "@babel/helper-fixtures";
describe("generation", function() {
it("completeness", function() {
Object.keys(t.VISITOR_KEYS).forEach(function(type) {
assert.ok(!!Printer.prototype[type], type + " should exist");
expect(Printer.prototype[type]).toBeTruthy();
});
Object.keys(Printer.prototype).forEach(function(type) {
if (!/[A-Z]/.test(type[0])) return;
assert.ok(t.VISITOR_KEYS[type], type + " should not exist");
expect(t.VISITOR_KEYS[type]).toBeTruthy();
});
});
@@ -46,7 +44,7 @@ describe("generation", function() {
const generated = generate(combinedAst, { sourceMaps: true }, sources);
chai.expect(generated.map).to.deep.equal(
expect(generated.map).toEqual(
{
version: 3,
sources: ["a.js", "b.js"],
@@ -61,7 +59,7 @@ describe("generation", function() {
"sourcemap was incorrectly generated",
);
chai.expect(generated.rawMappings).to.deep.equal(
expect(generated.rawMappings).toEqual(
[
{
name: undefined,
@@ -157,12 +155,9 @@ describe("generation", function() {
"raw mappings were incorrectly generated",
);
chai
.expect(generated.code)
.to.equal(
"function hi(msg) {\n console.log(msg);\n}\n\nhi('hello');",
"code was incorrectly generated",
);
expect(generated.code).toBe(
"function hi(msg) {\n console.log(msg);\n}\n\nhi('hello');",
);
});
it("identifierName", function() {
@@ -189,7 +184,7 @@ describe("generation", function() {
code,
);
chai.expect(generated.map).to.deep.equal(
expect(generated.map).toEqual(
{
version: 3,
sources: ["inline"],
@@ -200,7 +195,7 @@ describe("generation", function() {
"sourcemap was incorrectly generated",
);
chai.expect(generated.rawMappings).to.deep.equal(
expect(generated.rawMappings).toEqual(
[
{
name: undefined,
@@ -242,12 +237,7 @@ describe("generation", function() {
"raw mappings were incorrectly generated",
);
chai
.expect(generated.code)
.to.equal(
"function foo2() {\n bar2;\n}",
"code was incorrectly generated",
);
expect(generated.code).toBe("function foo2() {\n bar2;\n}");
});
it("lazy source map generation", function() {
@@ -259,14 +249,14 @@ describe("generation", function() {
sourceMaps: true,
});
chai.expect(generated.rawMappings).to.be.an("array");
expect(Array.isArray(generated.rawMappings)).toBe(true);
chai
.expect(generated)
.ownPropertyDescriptor("map")
.not.to.have.property("value");
expect(
Object.getOwnPropertyDescriptor(generated, "map"),
).not.toHaveProperty("value");
chai.expect(generated.map).to.be.an("object");
expect(generated).toHaveProperty("map");
expect(typeof generated.map).toBe("object");
});
});
@@ -294,7 +284,7 @@ describe("programmatic generation", function() {
);
const ast = parse(generate(ifStatement).code);
assert.equal(ast.program.body[0].consequent.type, "BlockStatement");
expect(ast.program.body[0].consequent.type).toBe("BlockStatement");
});
it("prints directives in block with empty body", function() {
@@ -304,12 +294,9 @@ describe("programmatic generation", function() {
);
const output = generate(blockStatement).code;
assert.equal(
output,
`{
expect(output).toBe(`{
"use strict";
}`,
);
}`);
});
it("flow object indentation", function() {
@@ -320,12 +307,9 @@ describe("programmatic generation", function() {
);
const output = generate(objectStatement).code;
assert.equal(
output,
`{
expect(output).toBe(`{
bar: string
}`,
);
}`);
});
it("flow object exact", function() {
@@ -337,12 +321,9 @@ describe("programmatic generation", function() {
);
const output = generate(objectStatement).code;
assert.equal(
output,
`{|
expect(output).toBe(`{|
bar: string
|}`,
);
|}`);
});
it("flow object indentation with empty leading ObjectTypeProperty", function() {
@@ -359,12 +340,9 @@ describe("programmatic generation", function() {
const output = generate(objectStatement).code;
assert.equal(
output,
`{
expect(output).toBe(`{
[key: any]: number
}`,
);
}`);
});
});
@@ -372,7 +350,7 @@ describe("CodeGenerator", function() {
it("generate", function() {
const codeGen = new CodeGenerator(t.numericLiteral(123));
const code = codeGen.generate().code;
assert.equal(parse(code).program.body[0].expression.value, 123);
expect(parse(code).program.body[0].expression.value).toBe(123);
});
});
@@ -385,7 +363,7 @@ suites.forEach(function(testSuite) {
task.title,
!task.disabled &&
function() {
const expect = task.expect;
const expected = task.expect;
const actual = task.actual;
const actualCode = actual.code;
@@ -399,17 +377,15 @@ suites.forEach(function(testSuite) {
const result = generate(actualAst, task.options, actualCode);
if (
!expect.code &&
!expected.code &&
result.code &&
fs.statSync(path.dirname(expect.loc)).isDirectory() &&
fs.statSync(path.dirname(expected.loc)).isDirectory() &&
!process.env.CI
) {
console.log(`New test file created: ${expect.loc}`);
fs.writeFileSync(expect.loc, result.code);
console.log(`New test file created: ${expected.loc}`);
fs.writeFileSync(expected.loc, result.code);
} else {
chai
.expect(result.code)
.to.be.equal(expect.code, actual.loc + " !== " + expect.loc);
expect(result.code).toBe(expected.code);
}
}
},

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-annotate-as-pure",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to annotate paths and nodes with #__PURE__ comment",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-annotate-as-pure",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.43"
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,12 +1,12 @@
{
"name": "@babel/helper-bindify-decorators",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to bindify decorators",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-bindify-decorators",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/traverse": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43"
"@babel/traverse": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,12 +1,12 @@
{
"name": "@babel/helper-builder-binary-assignment-operator-visitor",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to build binary assignment operator visitors",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-builder-binary-assignment-operator-visitor",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-explode-assignable-expression": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43"
"@babel/helper-explode-assignable-expression": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,12 +1,12 @@
{
"name": "@babel/helper-builder-react-jsx",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to build react jsx",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-builder-react-jsx",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.45",
"esutils": "^2.0.0"
}
}

View File

@@ -1,13 +1,13 @@
{
"name": "@babel/helper-call-delegate",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to call delegate",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-call-delegate",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-hoist-variables": "7.0.0-beta.43",
"@babel/traverse": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43"
"@babel/helper-hoist-variables": "7.0.0-beta.45",
"@babel/traverse": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,13 +1,13 @@
{
"name": "@babel/helper-define-map",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to define a map",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-define-map",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-function-name": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43",
"@babel/helper-function-name": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45",
"lodash": "^4.2.0"
}
}

View File

@@ -61,7 +61,7 @@ export function push(
key = t.toComputedKey(node, node.key);
}
if (t.isObjectProperty(node) || t.isClassProperty(node)) {
if (t.isProperty(node)) {
value = node.value;
} else if (t.isObjectMethod(node) || t.isClassMethod(node)) {
value = t.functionExpression(
@@ -131,15 +131,12 @@ export function toClassObject(mutatorMap: Object): Object {
const propNode = t.objectProperty(map._key, mapNode, map._computed);
Object.keys(map).forEach(function(key) {
let node = map[key];
const node = map[key];
if (key[0] === "_") return;
const inheritNode = node;
if (t.isClassMethod(node) || t.isClassProperty(node)) node = node.value;
const prop = t.objectProperty(t.identifier(key), node);
t.inheritsComments(prop, inheritNode);
t.removeComments(inheritNode);
t.inheritsComments(prop, node);
t.removeComments(node);
mapNode.properties.push(prop);
});

View File

@@ -1,12 +1,12 @@
{
"name": "@babel/helper-explode-assignable-expression",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to explode an assignable expression",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-explode-assignable-expression",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/traverse": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43"
"@babel/traverse": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,13 +1,13 @@
{
"name": "@babel/helper-explode-class",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to explode class",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-explode-class",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-bindify-decorators": "7.0.0-beta.43",
"@babel/traverse": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43"
"@babel/helper-bindify-decorators": "7.0.0-beta.45",
"@babel/traverse": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-fixtures",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to support fixtures",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"license": "MIT",

View File

@@ -1,13 +1,13 @@
{
"name": "@babel/helper-function-name",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to change the property 'name' of every function",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-function-name",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-get-function-arity": "7.0.0-beta.43",
"@babel/template": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43"
"@babel/helper-get-function-arity": "7.0.0-beta.45",
"@babel/template": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -45,6 +45,26 @@ const visitor = {
},
};
function getNameFromLiteralId(id) {
if (t.isNullLiteral(id)) {
return "null";
}
if (t.isRegExpLiteral(id)) {
return `_${id.pattern}_${id.flags}`;
}
if (t.isTemplateLiteral(id)) {
return id.quasis.map(quasi => quasi.value.raw).join("");
}
if (id.value !== undefined) {
return id.value + "";
}
return "";
}
function wrap(state, method, id, scope) {
if (state.selfReference) {
if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) {
@@ -168,10 +188,12 @@ export default function({ node, parent, scope, id }, localBinding = false) {
let name;
if (id && t.isLiteral(id)) {
name = id.value;
name = getNameFromLiteralId(id);
} else if (id && t.isIdentifier(id)) {
name = id.name;
} else {
}
if (name === undefined) {
return;
}

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-get-function-arity",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to get function arity",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-get-function-arity",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.43"
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-hoist-variables",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to hoist variables",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-hoist-variables",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.43"
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -0,0 +1,3 @@
src
test
*.log

View File

@@ -0,0 +1,75 @@
# @babel/helper-member-expression-to-functions
Helper function to replace certain member expressions with function calls
## Usage
> Designed for internal Babel use.
Traverses the `path` using the supplied `visitor` and an augmented `state`.
```js
const visitor = {
MemberExpression(memberPath, state) {
if (someCondition(memberPath)) {
// The handle method is supplied by memberExpressionToFunctions.
// It should be called whenever a MemberExpression should be
// converted into the proper function calls.
state.handle(memberPath);
}
},
};
// The helper requires three special methods on state: `get`, `set`, and
// `call`.
// Optionally, a special `memoize` method may be defined, which gets
// called if the member is in a self-referential update expression.
// Everything else will be passed through as normal.
const state = {
get(memberPath) {
// Return some AST that will get the member
return t.callExpression(
this.file.addHelper('superGet'),
[t.thisExpression(), memberPath.node.property]
);
},
set(memberPath, value) {
// Return some AST that will set the member
return t.callExpression(
this.file.addHelper('superSet'),
[t.thisExpression(), memberPath.node.property, value]
);
},
call(memberPath, args) {
// Return some AST that will call the member with the proper context
// and args
return t.callExpression(
t.memberExpression(this.get(memberPath), t.identifier("apply")),
[t.thisExpression(), t.arrayExpression(args)]
);
},
memoize(memberPath) {
const { node } = memberPath;
if (node.computed) {
MEMOIZED.set(node, ...);
}
},
// The handle method is provided by memberExpressionToFunctions.
// handle(memberPath) { ... }
// Other state stuff is left untouched.
someState: new Set(),
};
// Replace all the special MemberExpressions in rootPath, as determined
// by our visitor, using the state methods.
memberExpressionToFunctions(rootPath, visitor, state);
```

View File

@@ -0,0 +1,12 @@
{
"name": "@babel/helper-member-expression-to-functions",
"version": "7.0.0-beta.45",
"description": "Helper function to replace certain member expressions with function calls",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-member-expression-to-functions",
"license": "MIT",
"main": "lib/index.js",
"author": "Justin Ridgewell <justin@ridgewell.name>",
"dependencies": {
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -0,0 +1,86 @@
import * as t from "@babel/types";
const handle = {
handle(member) {
const { node, parent, parentPath } = member;
// MEMBER++ -> _set(MEMBER, (_ref = (+_get(MEMBER))) + 1), _ref
// ++MEMBER -> _set(MEMBER, (+_get(MEMBER)) + 1)
if (parentPath.isUpdateExpression({ argument: node })) {
const { operator, prefix } = parent;
// Give the state handler a chance to memoize the member,
// since we'll reference it twice.
if (this.memoize) {
this.memoize(member);
}
const value = t.binaryExpression(
operator[0],
t.unaryExpression("+", this.get(member)),
t.numericLiteral(1),
);
if (prefix) {
parentPath.replaceWith(this.set(member, value));
} else {
const { scope } = member;
const ref = scope.generateUidIdentifierBasedOnNode(node);
scope.push({ id: ref });
value.left = t.assignmentExpression("=", t.cloneNode(ref), value.left);
parentPath.replaceWith(
t.sequenceExpression([this.set(member, value), t.cloneNode(ref)]),
);
}
return;
}
// MEMBER = VALUE -> _set(MEMBER, VALUE)
// MEMBER += VALUE -> _set(MEMBER, _get(MEMBER) + VALUE)
if (parentPath.isAssignmentExpression({ left: node })) {
const { operator, right } = parent;
let value = right;
if (operator !== "=") {
// Give the state handler a chance to memoize the member,
// since we'll reference it twice.
if (this.memoize) {
this.memoize(member);
}
value = t.binaryExpression(
operator.slice(0, -1),
this.get(member),
value,
);
}
parentPath.replaceWith(this.set(member, value));
return;
}
// MEMBER(ARGS) -> _call(MEMBER, ARGS)
if (parentPath.isCallExpression({ callee: node })) {
const { arguments: args } = parent;
parentPath.replaceWith(this.call(member, args));
return;
}
// MEMBER -> _get(MEMBER)
member.replaceWith(this.get(member));
},
};
// We do not provide a default traversal visitor
// Instead, caller passes one, and must call `state.handle` on the members
// it wishes to be transformed.
// Additionally, the caller must pass in a state object with at least
// get, set, and call methods.
// Optionally, a memoize method may be defined on the state, which will be
// called when the member is a self-referential update.
export default function memberExpressionToFunctions(path, visitor, state) {
path.traverse(visitor, Object.assign({}, state, handle));
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-module-imports",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Babel helper functions for inserting module loads",
"author": "Logan Smyth <loganfsmyth@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,10 +8,10 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-module-imports",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.45",
"lodash": "^4.2.0"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-module-transforms",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Babel helper functions for implementing ES6 module transformations",
"author": "Logan Smyth <loganfsmyth@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,11 +8,11 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-module-transforms",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-module-imports": "7.0.0-beta.43",
"@babel/helper-simple-access": "7.0.0-beta.43",
"@babel/helper-split-export-declaration": "7.0.0-beta.43",
"@babel/template": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43",
"@babel/helper-module-imports": "7.0.0-beta.45",
"@babel/helper-simple-access": "7.0.0-beta.45",
"@babel/helper-split-export-declaration": "7.0.0-beta.45",
"@babel/template": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45",
"lodash": "^4.2.0"
}
}

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-optimise-call-expression",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to optimise call expression",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-optimise-call-expression",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.43"
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -6,8 +6,12 @@
> Check Babel for an example: https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-exponentiation-operator/test
1. Inside a `/test` directory, add an `index.js` with the contents `require("@babel/helper-plugin-test-runner")(__dirname);`.
1. Inside a `/test` directory, add an `index.js` with the contents
```js
import runner from "@babel/helper-plugin-test-runner";
runner(__dirname);
```
2. Inside `/test/fixtures`, create a folder for each suite (eg; one suite for each feature of your plugin).
3. Suite folders may contain files and folders. Files will be transformed and run; use `expect()` assertions to verify correct behavior. Folders may contain `input.js`, `output.js`, and/or `exec.js`. The output of transforming `input.js` will be checked to match the contents of `output.js`. `exec.js`, if it exists, will be transformed and run, as with a file in the suite folder.
3. Install and run `mocha`.
4. To run a specific test, run `mocha --grep testName`.
3. To run a specific test, run `TEST_GREP=testName make test`. [Read more](https://github.com/babel/babel/blob/master/CONTRIBUTING.md#running-lintingtests).

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-plugin-test-runner",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to support test runner",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-plugin-test-runner",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.43"
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.45"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-plugin-utils",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "General utilities for plugins to use",
"author": "Logan Smyth <loganfsmyth@gmail.com>",
"homepage": "https://babeljs.io/",

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-regex",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to check for literal RegEx",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-regex",
"license": "MIT",

View File

@@ -1,15 +1,15 @@
{
"name": "@babel/helper-remap-async-to-generator",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to remap async functions to generators",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-remap-async-to-generator",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-annotate-as-pure": "7.0.0-beta.43",
"@babel/helper-wrap-function": "7.0.0-beta.43",
"@babel/template": "7.0.0-beta.43",
"@babel/traverse": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43"
"@babel/helper-annotate-as-pure": "7.0.0-beta.45",
"@babel/helper-wrap-function": "7.0.0-beta.45",
"@babel/template": "7.0.0-beta.45",
"@babel/traverse": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,14 +1,14 @@
{
"name": "@babel/helper-replace-supers",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper function to replace supers",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-replace-supers",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-optimise-call-expression": "7.0.0-beta.43",
"@babel/template": "7.0.0-beta.43",
"@babel/traverse": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43"
"@babel/helper-member-expression-to-functions": "7.0.0-beta.45",
"@babel/helper-optimise-call-expression": "7.0.0-beta.45",
"@babel/traverse": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,141 +1,215 @@
import type { NodePath, Scope } from "@babel/traverse";
import type { NodePath } from "@babel/traverse";
import traverse from "@babel/traverse";
import memberExpressionToFunctions from "@babel/helper-member-expression-to-functions";
import optimiseCall from "@babel/helper-optimise-call-expression";
import * as t from "@babel/types";
// ✌️
const HARDCORE_THIS_REF = new WeakSet();
function isIllegalBareSuper(node, parent) {
if (!t.isSuper(node)) return false;
if (t.isMemberExpression(parent, { computed: false })) return false;
if (t.isCallExpression(parent, { callee: node })) return false;
return true;
}
function isMemberExpressionSuper(node) {
return t.isMemberExpression(node) && t.isSuper(node.object);
}
/**
* Creates an expression which result is the proto of objectRef.
* Uses CLASS.__proto__ first for InternetExplorer <= 10 support
*
* @example <caption>isStatic === true</caption>
*
* CLASS.__proto__ || Object.getPrototypeOf(CLASS)
* helpers.getPrototypeOf(CLASS)
*
* @example <caption>isStatic === false</caption>
*
* CLASS.prototype.__proto__ || Object.getPrototypeOf(CLASS.prototype)
* helpers.getPrototypeOf(CLASS.prototype)
*/
function getPrototypeOfExpression(objectRef, isStatic) {
function getPrototypeOfExpression(objectRef, isStatic, file) {
objectRef = t.cloneNode(objectRef);
const targetRef = isStatic
? objectRef
: t.memberExpression(objectRef, t.identifier("prototype"));
return t.logicalExpression(
"||",
t.memberExpression(targetRef, t.identifier("__proto__")),
t.callExpression(
t.memberExpression(
t.identifier("Object"),
t.identifier("getPrototypeOf"),
),
[t.cloneNode(targetRef)],
),
);
return t.callExpression(file.addHelper("getPrototypeOf"), [targetRef]);
}
const visitor = {
function skipAllButComputedKey(path) {
// If the path isn't computed, just skip everything.
if (!path.node.computed) {
path.skip();
return;
}
// So it's got a computed key. Make sure to skip every other key the
// traversal would visit.
const keys = t.VISITOR_KEYS[path.type];
for (const key of keys) {
if (key !== "key") path.skipKey(key);
}
}
export const environmentVisitor = {
Function(path) {
if (!path.isArrowFunctionExpression()) path.skip();
// Methods will be handled by the Method visit
if (path.isMethod()) return;
// Arrow functions inherit their parent's environment
if (path.isArrowFunctionExpression()) return;
path.skip();
},
ClassProperty(path) {
if (!path.node.static) path.skip();
Method(path) {
skipAllButComputedKey(path);
},
ReturnStatement(path, state) {
if (!path.getFunctionParent().isArrowFunctionExpression()) {
state.returns.push(path);
"ClassProperty|ClassPrivateProperty"(path) {
// If the property is computed, we need to visit everything.
if (path.node.static) return;
skipAllButComputedKey(path);
},
};
const visitor = traverse.visitors.merge([
environmentVisitor,
{
Super(path, state) {
const { node, parentPath } = path;
if (!parentPath.isMemberExpression({ object: node })) return;
state.handle(parentPath);
},
},
]);
const memoized = new WeakMap();
const specHandlers = {
memoize(superMember) {
const { scope, node } = superMember;
const { computed, property } = node;
if (!computed) {
return;
}
const memo = scope.maybeGenerateMemoised(property);
if (!memo) {
return;
}
memoized.set(property, memo);
},
ThisExpression(path, state) {
if (!HARDCORE_THIS_REF.has(path.node)) {
state.thises.push(path);
get(superMember) {
const { computed, property } = superMember.node;
const thisExpr = t.thisExpression();
let prop;
if (computed && memoized.has(property)) {
prop = t.cloneNode(memoized.get(property));
} else {
prop = computed ? property : t.stringLiteral(property.name);
}
return t.callExpression(this.file.addHelper("get"), [
getPrototypeOfExpression(this.getObjectRef(), this.isStatic, this.file),
prop,
thisExpr,
]);
},
enter(path, state) {
let callback = state.specHandle;
if (state.isLoose) callback = state.looseHandle;
set(superMember, value) {
const { computed, property } = superMember.node;
const isBareSuper = path.isCallExpression() && path.get("callee").isSuper();
const result = callback.call(state, path);
if (result) {
state.hasSuper = true;
let prop;
if (computed && memoized.has(property)) {
prop = t.assignmentExpression(
"=",
t.cloneNode(memoized.get(property)),
property,
);
} else {
prop = computed ? property : t.stringLiteral(property.name);
}
if (isBareSuper) {
state.bareSupers.push(path);
return t.callExpression(this.file.addHelper("set"), [
getPrototypeOfExpression(this.getObjectRef(), this.isStatic, this.file),
prop,
value,
t.thisExpression(),
t.booleanLiteral(superMember.isInStrictMode()),
]);
},
call(superMember, args) {
return optimiseCall(this.get(superMember), t.thisExpression(), args);
},
};
const looseHandlers = {
memoize: specHandlers.memoize,
call: specHandlers.call,
get(superMember) {
const { isStatic, superRef } = this;
const { property, computed } = superMember.node;
let object;
if (isStatic) {
object = superRef
? t.cloneNode(superRef)
: t.memberExpression(
t.identifier("Function"),
t.identifier("prototype"),
);
} else {
object = superRef
? t.memberExpression(t.cloneNode(superRef), t.identifier("prototype"))
: t.memberExpression(t.identifier("Object"), t.identifier("prototype"));
}
if (result === true) {
path.requeue();
let prop;
if (computed && memoized.has(property)) {
prop = t.cloneNode(memoized.get(property));
} else {
prop = property;
}
if (result !== true && result) {
if (Array.isArray(result)) {
path.replaceWithMultiple(result);
} else {
path.replaceWith(result);
}
return t.memberExpression(object, prop, computed);
},
set(superMember, value) {
const { property, computed } = superMember.node;
let prop;
if (computed && memoized.has(property)) {
prop = t.assignmentExpression(
"=",
t.cloneNode(memoized.get(property)),
property,
);
} else {
prop = property;
}
return t.assignmentExpression(
"=",
t.memberExpression(t.thisExpression(), prop, computed),
value,
);
},
};
export default class ReplaceSupers {
constructor(opts: Object, inClass?: boolean = false) {
this.forceSuperMemoisation = opts.forceSuperMemoisation;
this.methodPath = opts.methodPath;
this.methodNode = opts.methodNode;
this.superRef = opts.superRef;
this.isStatic = opts.isStatic;
this.hasSuper = false;
this.inClass = inClass;
this.inConstructor = opts.inConstructor;
this.isLoose = opts.isLoose;
this.scope = this.methodPath.scope;
this.file = opts.file;
this.opts = opts;
constructor(opts: Object) {
const path = opts.methodPath;
this.bareSupers = [];
this.returns = [];
this.thises = [];
this.methodPath = path;
this.isStatic =
path.isClassMethod({ static: true }) || path.isObjectMethod();
this.file = opts.file;
this.superRef = opts.superRef;
this.isLoose = opts.isLoose;
this.opts = opts;
}
forceSuperMemoisation: boolean;
methodPath: NodePath;
methodNode: Object;
superRef: Object;
isStatic: boolean;
hasSuper: boolean;
inClass: boolean;
inConstructor: boolean;
isLoose: boolean;
scope: Scope;
file;
opts: {
forceSuperMemoisation: boolean,
getObjetRef: Function,
methodPath: NodePath,
methodNode: Object,
superRef: Object,
inConstructor: boolean,
isStatic: boolean,
isLoose: boolean,
file: any,
};
@@ -144,197 +218,15 @@ export default class ReplaceSupers {
return t.cloneNode(this.opts.objectRef || this.opts.getObjectRef());
}
/**
* Sets a super class value of the named property.
*
* @example
*
* _set(CLASS.prototype.__proto__ || Object.getPrototypeOf(CLASS.prototype), "METHOD", "VALUE",
* this)
*
*/
setSuperProperty(
property: Object,
value: Object,
isComputed: boolean,
): Object {
return t.callExpression(this.file.addHelper("set"), [
getPrototypeOfExpression(this.getObjectRef(), this.isStatic),
isComputed ? property : t.stringLiteral(property.name),
value,
t.thisExpression(),
]);
}
/**
* Gets a node representing the super class value of the named property.
*
* @example
*
* _get(CLASS.prototype.__proto__ || Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
*
*/
getSuperProperty(property: Object, isComputed: boolean): Object {
let thisExpr = t.thisExpression();
if (this.inConstructor) {
thisExpr = t.callExpression(
this.file.addHelper("assertThisInitialized"),
[thisExpr],
);
}
return t.callExpression(this.file.addHelper("get"), [
getPrototypeOfExpression(this.getObjectRef(), this.isStatic),
isComputed ? property : t.stringLiteral(property.name),
thisExpr,
]);
}
replace() {
this.methodPath.traverse(visitor, this);
}
const handler = this.isLoose ? looseHandlers : specHandlers;
getLooseSuperProperty(id: Object, parent: Object) {
const methodNode = this.methodNode;
const superRef = this.superRef || t.identifier("Function");
if (parent.property === id) {
return;
} else if (t.isCallExpression(parent, { callee: id })) {
return;
} else if (t.isMemberExpression(parent) && !methodNode.static) {
// super.test -> objectRef.prototype.test
return t.memberExpression(
t.cloneNode(superRef),
t.identifier("prototype"),
);
} else {
return t.cloneNode(superRef);
}
}
looseHandle(path: NodePath) {
const node = path.node;
if (path.isSuper()) {
return this.getLooseSuperProperty(node, path.parent);
} else if (path.isCallExpression()) {
const callee = node.callee;
if (!t.isMemberExpression(callee)) return;
if (!t.isSuper(callee.object)) return;
// super.test(); -> objectRef.prototype.MethodName.call(this);
t.appendToMemberExpression(callee, t.identifier("call"));
node.arguments.unshift(t.thisExpression());
return true;
}
}
specHandleAssignmentExpression(ref, path, node) {
if (node.operator === "=") {
// super.name = "val"; -> _set(Object.getPrototypeOf(objectRef.prototype), "name", this);
return this.setSuperProperty(
node.left.property,
node.right,
node.left.computed,
);
} else {
// super.age += 2; -> let _ref = super.age; super.age = _ref + 2;
ref = ref || path.scope.generateUidIdentifier("ref");
return [
t.variableDeclaration("var", [
t.variableDeclarator(t.cloneNode(ref), t.cloneNode(node.left)),
]),
t.expressionStatement(
t.assignmentExpression(
"=",
node.left,
t.binaryExpression(
node.operator.slice(0, -1),
t.cloneNode(ref),
node.right,
),
),
),
];
}
}
specHandle(path: NodePath) {
let property;
let computed;
let args;
const parent = path.parent;
const node = path.node;
if (isIllegalBareSuper(node, parent)) {
throw path.buildCodeFrameError("Illegal use of bare super");
}
if (t.isCallExpression(node)) {
const callee = node.callee;
if (t.isSuper(callee)) {
return;
} else if (isMemberExpressionSuper(callee)) {
// super.test();
// to
// _get(Object.getPrototypeOf(objectRef.prototype), "test", this).call(this);
property = callee.property;
computed = callee.computed;
args = node.arguments;
}
} else if (t.isMemberExpression(node) && t.isSuper(node.object)) {
// super.name;
// to
// _get(Object.getPrototypeOf(objectRef.prototype), "name", this);
property = node.property;
computed = node.computed;
} else if (
t.isUpdateExpression(node) &&
isMemberExpressionSuper(node.argument)
) {
const binary = t.assignmentExpression(
node.operator[0] + "=",
node.argument,
t.numericLiteral(1),
);
if (node.prefix) {
// ++super.foo;
// to
// super.foo += 1;
return this.specHandleAssignmentExpression(null, path, binary);
} else {
// super.foo++;
// to
// let _ref = super.foo; super.foo = _ref + 1;
const ref = path.scope.generateUidIdentifier("ref");
return this.specHandleAssignmentExpression(ref, path, binary).concat(
t.expressionStatement(ref),
);
}
} else if (
t.isAssignmentExpression(node) &&
isMemberExpressionSuper(node.left)
) {
return this.specHandleAssignmentExpression(null, path, node);
}
if (!property) return;
const superProperty = this.getSuperProperty(property, computed);
if (args) {
return this.optimiseCall(superProperty, args);
} else {
return superProperty;
}
}
optimiseCall(callee, args) {
const thisNode = t.thisExpression();
HARDCORE_THIS_REF.add(thisNode);
return optimiseCall(callee, thisNode, args);
memberExpressionToFunctions(this.methodPath, visitor, {
file: this.file,
isStatic: this.isStatic,
getObjectRef: this.getObjectRef.bind(this),
superRef: this.superRef,
...handler,
});
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-simple-access",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Babel helper for ensuring that access to a given value is performed through simple accesses",
"author": "Logan Smyth <loganfsmyth@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,8 +8,8 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-simple-access",
"main": "lib/index.js",
"dependencies": {
"@babel/template": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43",
"@babel/template": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45",
"lodash": "^4.2.0"
}
}

View File

@@ -25,27 +25,49 @@ const simpleAssignmentVisitor = {
}
if (
path.node.prefix ||
(path.parentPath.isExpressionStatement() && !path.isCompletionRecord())
path.parentPath.isExpressionStatement() &&
!path.isCompletionRecord()
) {
// ++i => (i += 1);
const operator = path.node.operator == "++" ? "+=" : "-=";
path.replaceWith(
t.assignmentExpression(operator, arg.node, t.numericLiteral(1)),
);
} else if (path.node.prefix) {
// ++i => (i = (+i) + 1);
path.replaceWith(
t.assignmentExpression(
"=",
t.identifier(localName),
t.binaryExpression(
path.node.operator[0],
t.unaryExpression("+", arg.node),
t.numericLiteral(1),
),
),
);
} else {
const varName = path.scope.generateDeclaredUidIdentifier("old").name;
const old = path.scope.generateUidIdentifierBasedOnNode(
arg.node,
"old",
);
const varName = old.name;
path.scope.push({ id: old });
const binary = t.binaryExpression(
path.node.operator.slice(0, 1),
path.node.operator[0],
t.identifier(varName),
t.numericLiteral(1),
);
// i++ => (_tmp = i, i = _tmp + 1, _tmp)
// i++ => (_old = (+i), i = _old + 1, _old)
path.replaceWith(
t.sequenceExpression([
t.assignmentExpression("=", t.identifier(varName), arg.node),
t.assignmentExpression(
"=",
t.identifier(varName),
t.unaryExpression("+", arg.node),
),
t.assignmentExpression("=", t.cloneNode(arg.node), binary),
t.identifier(varName),
]),

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-split-export-declaration",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-split-export-declaration",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.43"
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-transform-fixture-test-runner",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Transform test runner for @babel/helper-fixtures module",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,11 +8,10 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-transform-fixture-test-runner",
"main": "lib/index.js",
"dependencies": {
"@babel/code-frame": "7.0.0-beta.43",
"@babel/core": "7.0.0-beta.43",
"@babel/helper-fixtures": "7.0.0-beta.43",
"@babel/polyfill": "7.0.0-beta.43",
"chai": "^4.1.0",
"@babel/code-frame": "7.0.0-beta.45",
"@babel/core": "7.0.0-beta.45",
"@babel/helper-fixtures": "7.0.0-beta.45",
"@babel/polyfill": "7.0.0-beta.45",
"jest": "^22.4.2",
"jest-diff": "^22.4.0",
"lodash": "^4.2.0",

View File

@@ -28,17 +28,6 @@ const testContext = vm.createContext({
});
testContext.global = testContext;
// Add chai's assert to the global context
// It has to be required inside the testContext as otherwise some assertions do not
// work as chai would reference globals (RegExp, Array, ...) from this context
vm.runInContext(
"(function(require) { global.assert=require('chai').assert; });",
testContext,
{
displayErrors: true,
},
)(id => runModuleInTestContext(id, __filename));
// Initialize the test context with the polyfill, and then freeze the global to prevent implicit
// global creation in tests, which could cause things to bleed between tests.
runModuleInTestContext("@babel/polyfill", __filename);
@@ -407,10 +396,17 @@ function run(task) {
}
} else {
actualCode = result.code.trim();
expect(actualCode).toEqualFile({
filename: expected.loc,
code: expectCode,
});
try {
expect(actualCode).toEqualFile({
filename: expected.loc,
code: expectCode,
});
} catch (e) {
if (!process.env.OVERWRITE) throw e;
console.log(`Updated test file: ${expected.loc}`);
fs.writeFileSync(expected.loc, `${result.code}\n`);
}
if (actualCode) {
expect(expected.loc).toMatch(

View File

@@ -1,14 +1,14 @@
{
"name": "@babel/helper-wrap-function",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Helper to wrap functions inside a function call.",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-wrap-function",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-function-name": "7.0.0-beta.43",
"@babel/template": "7.0.0-beta.43",
"@babel/traverse": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43"
"@babel/helper-function-name": "7.0.0-beta.45",
"@babel/template": "7.0.0-beta.45",
"@babel/traverse": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helpers",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Collection of helper functions used by Babel transforms.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,11 +8,11 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helpers",
"main": "lib/index.js",
"dependencies": {
"@babel/template": "7.0.0-beta.43",
"@babel/traverse": "7.0.0-beta.43",
"@babel/types": "7.0.0-beta.43"
"@babel/template": "7.0.0-beta.45",
"@babel/traverse": "7.0.0-beta.45",
"@babel/types": "7.0.0-beta.45"
},
"devDependencies": {
"@babel/helper-plugin-test-runner": "7.0.0-beta.43"
"@babel/helper-plugin-test-runner": "7.0.0-beta.45"
}
}

View File

@@ -72,13 +72,15 @@ helpers.jsx = () => template.program.ast`
helpers.asyncIterator = () => template.program.ast`
export default function _asyncIterator(iterable) {
var method
if (typeof Symbol === "function") {
if (Symbol.asyncIterator) {
var method = iterable[Symbol.asyncIterator];
method = iterable[Symbol.asyncIterator]
if (method != null) return method.call(iterable);
}
if (Symbol.iterator) {
return iterable[Symbol.iterator]();
method = iterable[Symbol.iterator]
if (method != null) return method.call(iterable);
}
}
throw new TypeError("Object is not async iterable");
@@ -390,80 +392,71 @@ helpers.objectSpread = () => template.program.ast`
}
`;
helpers.get = () => template.program.ast`
export default function _get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return _get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
}
`;
helpers.inherits = () => template.program.ast`
import setPrototypeOf from "setPrototypeOf";
export default function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass)
Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
setPrototypeOf(subClass.prototype, superClass && superClass.prototype);
if (superClass) setPrototypeOf(subClass, superClass);
}
`;
helpers.inheritsLoose = () => template.program.ast`
export default function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.prototype.__proto__ = superClass && superClass.prototype;
subClass.__proto__ = superClass;
}
`;
helpers.getPrototypeOf = () => template.program.ast`
export default function _getPrototypeOf(o) {
_getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) {
return o.__proto__;
};
return _getPrototypeOf(o);
}
`;
helpers.setPrototypeOf = () => template.program.ast`
export default function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
`;
helpers.construct = () => template.program.ast`
import setPrototypeOf from "setPrototypeOf";
export default function _construct(Parent, args, Class) {
if (typeof Reflect !== "undefined" && Reflect.construct) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Parent.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) setPrototypeOf(instance, Class.prototype);
return instance;
};
}
// Avoid issues with Class being present but undefined when it wasn't
// present in the original call.
return _construct.apply(null, arguments);
}
`;
// Based on https://github.com/WebReflection/babel-plugin-transform-builtin-classes
helpers.wrapNativeSuper = () => template.program.ast`
function _gPO(o) {
_gPO = Object.getPrototypeOf || function _gPO(o) { return o.__proto__ };
return _gPO(o);
}
function _sPO(o, p) {
_sPO = Object.setPrototypeOf || function _sPO(o, p) { o.__proto__ = p; return o };
return _sPO(o, p);
}
function _construct(Parent, args, Class) {
_construct = (typeof Reflect === "object" && Reflect.construct) ||
function _construct(Parent, args, Class) {
var Constructor, a = [null];
a.push.apply(a, args);
Constructor = Parent.bind.apply(Parent, a);
return _sPO(new Constructor, Class.prototype);
};
return _construct(Parent, args, Class);
}
import _gPO from "getPrototypeOf";
import _sPO from "setPrototypeOf";
import construct from "construct";
export default function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
@@ -489,7 +482,7 @@ helpers.wrapNativeSuper = () => template.program.ast`
Wrapper,
_sPO(
function Super() {
return _construct(Class, arguments, _gPO(this).constructor);
return construct(Class, arguments, _gPO(this).constructor);
},
Class
)
@@ -604,24 +597,96 @@ helpers.possibleConstructorReturn = () => template.program.ast`
}
`;
helpers.set = () => template.program.ast`
export default function _set(object, property, value, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
helpers.superPropBase = () => template.program.ast`
import getPrototypeOf from "getPrototypeOf";
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
export default function _superPropBase(object, property) {
// Yes, this throws if object is null to being with, that's on purpose.
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = getPrototypeOf(object);
if (object === null) break;
}
return object;
}
`;
if (parent !== null) {
_set(parent, property, value, receiver);
}
} else if ("value" in desc && desc.writable) {
desc.value = value;
helpers.get = () => template.program.ast`
import getPrototypeOf from "getPrototypeOf";
import superPropBase from "superPropBase";
export default function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
} else {
var setter = desc.set;
_get = function _get(target, property, receiver) {
var base = superPropBase(target, property);
if (setter !== undefined) {
setter.call(receiver, value);
}
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
`;
helpers.set = () => template.program.ast`
import getPrototypeOf from "getPrototypeOf";
import superPropBase from "superPropBase";
import defineProperty from "defineProperty";
function set(target, property, value, receiver) {
if (typeof Reflect !== "undefined" && Reflect.set) {
set = Reflect.set;
} else {
set = function set(target, property, value, receiver) {
var base = superPropBase(target, property);
var desc;
if (base) {
desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.set) {
desc.set.call(receiver, value);
return true;
} else if (!desc.writable) {
// Both getter and non-writable fall into this.
return false;
}
}
// Without a super that defines the property, spec boils down to
// "define on receiver" for some reason.
desc = Object.getOwnPropertyDescriptor(receiver, property);
if (desc) {
if (!desc.writable) {
// Setter, getter, and non-writable fall into this.
return false;
}
desc.value = value;
Object.defineProperty(receiver, property, desc);
} else {
// Avoid setters that may be defined on Sub's prototype, but not on
// the instance.
defineProperty(receiver, property, value);
}
return true;
};
}
return set(target, property, value, receiver);
}
export default function _set(target, property, value, receiver, isStrict) {
const s = set(target, property, value, receiver || target);
if (!s && isStrict) {
throw new Error('failed to set property');
}
return value;
@@ -723,7 +788,7 @@ helpers.arrayWithoutHoles = () => template.program.ast`
`;
helpers.arrayWithHoles = () => template.program.ast`
export default function _arrayWithoutHoles(arr) {
export default function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
`;

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/highlight",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Syntax highlight JavaScript strings for output in terminals.",
"author": "suchipi <me@suchipi.com>",
"homepage": "https://babeljs.io/",

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/node",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Babel command line",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -16,8 +16,8 @@
"compiler"
],
"dependencies": {
"@babel/polyfill": "7.0.0-beta.43",
"@babel/register": "7.0.0-beta.43",
"@babel/polyfill": "7.0.0-beta.45",
"@babel/register": "7.0.0-beta.45",
"commander": "^2.8.1",
"fs-readdir-recursive": "^1.0.0",
"lodash": "^4.2.0",
@@ -25,11 +25,11 @@
"v8flags": "^3.0.0"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.43",
"@babel/helper-fixtures": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45",
"@babel/helper-fixtures": "7.0.0-beta.45"
},
"bin": {
"babel-node": "./bin/babel-node.js"

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-external-helpers",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "This plugin contains helper functions thatll be placed at the top of the generated code",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-external-helpers",
"license": "MIT",
@@ -9,13 +9,13 @@
"babel-plugin"
],
"dependencies": {
"@babel/helper-plugin-utils": "7.0.0-beta.43"
"@babel/helper-plugin-utils": "7.0.0-beta.45"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.43",
"@babel/helper-plugin-test-runner": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45",
"@babel/helper-plugin-test-runner": "7.0.0-beta.45"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-proposal-async-generator-functions",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "Turn async generator functions into ES2015 generators",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-proposal-async-generator-functions",
"license": "MIT",
@@ -9,15 +9,15 @@
"babel-plugin"
],
"dependencies": {
"@babel/helper-plugin-utils": "7.0.0-beta.43",
"@babel/helper-remap-async-to-generator": "7.0.0-beta.43",
"@babel/plugin-syntax-async-generators": "7.0.0-beta.43"
"@babel/helper-plugin-utils": "7.0.0-beta.45",
"@babel/helper-remap-async-to-generator": "7.0.0-beta.45",
"@babel/plugin-syntax-async-generators": "7.0.0-beta.45"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.43",
"@babel/helper-plugin-test-runner": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45",
"@babel/helper-plugin-test-runner": "7.0.0-beta.45"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-proposal-class-properties",
"version": "7.0.0-beta.43",
"version": "7.0.0-beta.45",
"description": "This plugin transforms static class properties as well as properties declared with the property initializer syntax",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-proposal-class-properties",
"license": "MIT",
@@ -9,15 +9,16 @@
"babel-plugin"
],
"dependencies": {
"@babel/helper-function-name": "7.0.0-beta.43",
"@babel/helper-plugin-utils": "7.0.0-beta.43",
"@babel/plugin-syntax-class-properties": "7.0.0-beta.43"
"@babel/helper-function-name": "7.0.0-beta.45",
"@babel/helper-plugin-utils": "7.0.0-beta.45",
"@babel/helper-replace-supers": "7.0.0-beta.45",
"@babel/plugin-syntax-class-properties": "7.0.0-beta.45"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.43",
"@babel/helper-plugin-test-runner": "7.0.0-beta.43"
"@babel/core": "7.0.0-beta.45",
"@babel/helper-plugin-test-runner": "7.0.0-beta.45"
}
}

View File

@@ -1,66 +1,76 @@
import { declare } from "@babel/helper-plugin-utils";
import nameFunction from "@babel/helper-function-name";
import syntaxClassProperties from "@babel/plugin-syntax-class-properties";
import { template, types as t } from "@babel/core";
import { template, traverse, types as t } from "@babel/core";
import { environmentVisitor } from "@babel/helper-replace-supers";
export default declare((api, options) => {
api.assertVersion(7);
const { loose } = options;
const findBareSupers = {
Super(path) {
if (path.parentPath.isCallExpression({ callee: path.node })) {
this.push(path.parentPath);
}
const findBareSupers = traverse.visitors.merge([
{
Super(path) {
const { node, parentPath } = path;
if (parentPath.isCallExpression({ callee: node })) {
this.push(parentPath);
}
},
},
};
environmentVisitor,
]);
const referenceVisitor = {
"TSTypeAnnotation|TypeAnnotation"(path) {
path.skip();
},
ReferencedIdentifier(path) {
if (this.scope.hasOwnBinding(path.node.name)) {
this.collision = true;
this.scope.rename(path.node.name);
path.skip();
}
},
};
const ClassFieldDefinitionEvaluationTDZVisitor = {
Expression(path) {
if (path === this.shouldSkip) {
path.skip();
}
const classFieldDefinitionEvaluationTDZVisitor = traverse.visitors.merge([
{
ReferencedIdentifier(path) {
if (this.classRef === path.scope.getBinding(path.node.name)) {
const classNameTDZError = this.file.addHelper("classNameTDZError");
const throwNode = t.callExpression(classNameTDZError, [
t.stringLiteral(path.node.name),
]);
path.replaceWith(t.sequenceExpression([throwNode, path.node]));
path.skip();
}
},
},
environmentVisitor,
]);
ReferencedIdentifier(path) {
if (this.classRef === path.scope.getBinding(path.node.name)) {
const classNameTDZError = this.file.addHelper("classNameTDZError");
const throwNode = t.callExpression(classNameTDZError, [
t.stringLiteral(path.node.name),
]);
const foldDefinePropertyCalls = nodes =>
t.expressionStatement(
nodes.reduce((folded, node) => {
// update defineProperty's obj argument
node.arguments[0] = folded;
return node;
}),
);
path.replaceWith(t.sequenceExpression([throwNode, path.node]));
path.skip();
}
},
};
const buildClassPropertySpec = (ref, { key, value, computed }, scope) => {
return template.statement`
Object.defineProperty(REF, KEY, {
configurable: true,
enumerable: true,
writable: true,
value: VALUE
});
`({
REF: t.cloneNode(ref),
KEY: t.isIdentifier(key) && !computed ? t.stringLiteral(key.name) : key,
VALUE: value || scope.buildUndefinedNode(),
});
const buildClassPropertySpec = (
ref,
{ key, value, computed },
scope,
state,
) => {
return t.callExpression(state.addHelper("defineProperty"), [
ref,
t.isIdentifier(key) && !computed ? t.stringLiteral(key.name) : key,
value || scope.buildUndefinedNode(),
]);
};
const buildClassPropertyLoose = (ref, { key, value, computed }, scope) => {
@@ -82,7 +92,7 @@ export default declare((api, options) => {
inherits: syntaxClassProperties,
visitor: {
Class(path) {
Class(path, state) {
const isDerived = !!path.node.superClass;
let constructor;
const props = [];
@@ -115,17 +125,16 @@ export default declare((api, options) => {
const computedNodes = [];
const staticNodes = [];
let instanceBody = [];
const instanceBody = [];
for (const computedPath of computedPaths) {
const computedNode = computedPath.node;
// Make sure computed property names are only evaluated once (upon class definition)
// and in the right order in combination with static properties
if (!computedPath.get("key").isConstantExpression()) {
computedPath.traverse(ClassFieldDefinitionEvaluationTDZVisitor, {
computedPath.traverse(classFieldDefinitionEvaluationTDZVisitor, {
classRef: path.scope.getBinding(ref.name),
file: this.file,
shouldSkip: computedPath.get("value"),
});
const ident = path.scope.generateUidIdentifierBasedOnNode(
computedNode.key,
@@ -144,17 +153,31 @@ export default declare((api, options) => {
if (propNode.decorators && propNode.decorators.length > 0) continue;
if (propNode.static) {
staticNodes.push(buildClassProperty(ref, propNode, path.scope));
staticNodes.push(
buildClassProperty(ref, propNode, path.scope, state),
);
} else {
instanceBody.push(
buildClassProperty(t.thisExpression(), propNode, path.scope),
buildClassProperty(
t.thisExpression(),
propNode,
path.scope,
state,
),
);
}
}
const afterNodes = [...staticNodes];
const afterNodes =
!loose && staticNodes.length
? foldDefinePropertyCalls(staticNodes)
: staticNodes;
if (instanceBody.length) {
const assignments = loose
? instanceBody
: foldDefinePropertyCalls(instanceBody);
if (!constructor) {
const newConstructor = t.classMethod(
"constructor",
@@ -175,46 +198,8 @@ export default declare((api, options) => {
[constructor] = body.unshiftContainer("body", newConstructor);
}
const collisionState = {
collision: false,
scope: constructor.scope,
};
for (const prop of props) {
prop.traverse(referenceVisitor, collisionState);
if (collisionState.collision) break;
}
if (collisionState.collision) {
const initialisePropsRef = path.scope.generateUidIdentifier(
"initialiseProps",
);
afterNodes.push(
t.variableDeclaration("var", [
t.variableDeclarator(
initialisePropsRef,
t.functionExpression(
null,
[],
t.blockStatement(instanceBody),
),
),
]),
);
instanceBody = [
t.expressionStatement(
t.callExpression(
t.memberExpression(
t.cloneNode(initialisePropsRef),
t.identifier("call"),
),
[t.thisExpression()],
),
),
];
}
const state = { scope: constructor.scope };
for (const prop of props) prop.traverse(referenceVisitor, state);
//
@@ -222,10 +207,10 @@ export default declare((api, options) => {
const bareSupers = [];
constructor.traverse(findBareSupers, bareSupers);
for (const bareSuper of bareSupers) {
bareSuper.insertAfter(instanceBody);
bareSuper.insertAfter(assignments);
}
} else {
constructor.get("body").unshiftContainer("body", instanceBody);
constructor.get("body").unshiftContainer("body", assignments);
}
}

View File

@@ -1,18 +1,9 @@
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
class C {
// Output should not use `_initialiseProps`
constructor(T) {
Object.defineProperty(this, "x", {
configurable: true,
enumerable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "y", {
configurable: true,
enumerable: true,
writable: true,
value: 0
});
_defineProperty(_defineProperty(this, "x", void 0), "y", 0);
}
}

View File

@@ -1,128 +0,0 @@
var foo = "foo";
var bar = () => {};
var four = 4;
var _one = one();
var _ref = 2 * four + seven;
var _undefined = undefined;
var _computed = computed();
var _computed2 = computed();
var _ref2 = "test" + one;
var _ref3 = /regex/;
var _bar = bar;
var _baz = baz;
var _ref4 = `template${expression}`;
var MyClass =
/*#__PURE__*/
function () {
function MyClass() {
babelHelpers.classCallCheck(this, MyClass);
Object.defineProperty(this, null, {
configurable: true,
enumerable: true,
writable: true,
value: "null"
});
Object.defineProperty(this, _undefined, {
configurable: true,
enumerable: true,
writable: true,
value: "undefined"
});
Object.defineProperty(this, void 0, {
configurable: true,
enumerable: true,
writable: true,
value: "void 0"
});
Object.defineProperty(this, _ref3, {
configurable: true,
enumerable: true,
writable: true,
value: "regex"
});
Object.defineProperty(this, foo, {
configurable: true,
enumerable: true,
writable: true,
value: "foo"
});
Object.defineProperty(this, _bar, {
configurable: true,
enumerable: true,
writable: true,
value: "bar"
});
Object.defineProperty(this, _baz, {
configurable: true,
enumerable: true,
writable: true,
value: "baz"
});
Object.defineProperty(this, `template`, {
configurable: true,
enumerable: true,
writable: true,
value: "template"
});
Object.defineProperty(this, _ref4, {
configurable: true,
enumerable: true,
writable: true,
value: "template-with-expression"
});
}
babelHelpers.createClass(MyClass, [{
key: _ref2,
value: function () {}
}, {
key: "whatever",
get: function () {},
set: function (value) {}
}, {
key: _computed,
get: function () {}
}, {
key: _computed2,
set: function (value) {}
}], [{
key: 10,
value: function () {}
}]);
return MyClass;
}();
Object.defineProperty(MyClass, _one, {
configurable: true,
enumerable: true,
writable: true,
value: "test"
});
Object.defineProperty(MyClass, 2 * 4 + 7, {
configurable: true,
enumerable: true,
writable: true,
value: "247"
});
Object.defineProperty(MyClass, 2 * four + 7, {
configurable: true,
enumerable: true,
writable: true,
value: "247"
});
Object.defineProperty(MyClass, _ref, {
configurable: true,
enumerable: true,
writable: true,
value: "247"
});

View File

@@ -1,18 +0,0 @@
var foo = "bar";
var Foo = function Foo() {
babelHelpers.classCallCheck(this, Foo);
_initialiseProps.call(this);
var foo = "foo";
};
var _initialiseProps = function () {
Object.defineProperty(this, "bar", {
configurable: true,
enumerable: true,
writable: true,
value: foo
});
};

View File

@@ -1,19 +0,0 @@
var Foo =
/*#__PURE__*/
function (_Bar) {
babelHelpers.inherits(Foo, _Bar);
function Foo(...args) {
var _temp, _this;
babelHelpers.classCallCheck(this, Foo);
return babelHelpers.possibleConstructorReturn(_this, (_temp = _this = babelHelpers.possibleConstructorReturn(this, (Foo.__proto__ || Object.getPrototypeOf(Foo)).call(this, ...args)), Object.defineProperty(babelHelpers.assertThisInitialized(_this), "bar", {
configurable: true,
enumerable: true,
writable: true,
value: "foo"
}), _temp));
}
return Foo;
}(Bar);

View File

@@ -1,4 +0,0 @@
{
"plugins": ["external-helpers", "proposal-class-properties"],
"presets": ["stage-0", "es2015"]
}

View File

@@ -1,23 +0,0 @@
var Child =
/*#__PURE__*/
function (_Parent) {
babelHelpers.inherits(Child, _Parent);
function Child() {
var _this;
babelHelpers.classCallCheck(this, Child);
_this = babelHelpers.possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this));
Object.defineProperty(babelHelpers.assertThisInitialized(_this), "scopedFunctionWithThis", {
configurable: true,
enumerable: true,
writable: true,
value: function value() {
_this.name = {};
}
});
return _this;
}
return Child;
}(Parent);

View File

@@ -1,9 +0,0 @@
var Foo = function Foo() {
babelHelpers.classCallCheck(this, Foo);
Object.defineProperty(this, "bar", {
configurable: true,
enumerable: true,
writable: true,
value: void 0
});
};

View File

@@ -1,9 +0,0 @@
var Foo = function Foo() {
babelHelpers.classCallCheck(this, Foo);
Object.defineProperty(this, "bar", {
configurable: true,
enumerable: true,
writable: true,
value: "foo"
});
};

View File

@@ -1,23 +0,0 @@
var _class, _temp;
call((_temp = _class = function _class() {
babelHelpers.classCallCheck(this, _class);
}, Object.defineProperty(_class, "test", {
configurable: true,
enumerable: true,
writable: true,
value: true
}), _temp));
var _default = function _default() {
babelHelpers.classCallCheck(this, _default);
};
Object.defineProperty(_default, "test", {
configurable: true,
enumerable: true,
writable: true,
value: true
});
export { _default as default };
;

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