Compare commits

...

137 Commits

Author SHA1 Message Date
Henry Zhu
90fb82a535 v7.0.0 2018-08-27 17:41:21 -04:00
Henry Zhu
8a45fba510 testing temp tag [skip ci] 2018-08-27 17:32:28 -04:00
Logan Smyth
079780b432 Make it easier to re-run local prod builds (#8556) [skip ci] 2018-08-27 13:43:45 -04:00
Henry Zhu
4e64807afc use temp tag while having publishing issues [skip ci] 2018-08-27 13:16:39 -04:00
Henry Zhu
814c564c45 v7.0.0-rc.4 2018-08-27 12:42:00 -04:00
Henry Zhu
7a104e3e1d bump source-map-support (#8553) 2018-08-27 12:32:42 -04:00
Henry Zhu
b98799557a Lerna: remove exact [skip ci] (#8554)
We only wanted all the dependencies to be exact in the pre-release because of breaking changes. This will make it use the default `^`
2018-08-27 12:27:32 -04:00
Logan Smyth
1ac46a256d Merge pull request #8547 from loganfsmyth/runtime-cleanup
Remove nonstandard functions and fake prototype methods from babel-runtime
2018-08-26 21:25:50 -07:00
Logan Smyth
50d3c09883 Add support for asyncIterator. 2018-08-26 13:59:33 -07:00
Logan Smyth
508bfad55a Remove non-standard and prototype methods from constructor property use. 2018-08-26 13:59:33 -07:00
Logan Smyth
130814342a Enable a few disabled core-js utils now that we're reading for them in 7.x. 2018-08-26 13:52:19 -07:00
Logan Smyth
e0ee0570be Default highlightCode:true for the parser highlighting. (#8546) 2018-08-26 13:23:43 -07:00
Justin Ridgewell
edbffda091 Cleanup getLineInfo (#8540)
Removes an ignore control comment
2018-08-26 13:27:06 -04:00
Justin Ridgewell
72ee1816a4 Update to ES6 String methods (#8541) 2018-08-26 13:26:51 -04:00
tsangint
e875fc7bc1 Update url in buildUnknownError tips (#8544) 2018-08-26 15:00:32 +02:00
Justin Ridgewell
524d847763 Flatten TokenType class hierarchy (#8537)
`KeywordTokenType` and `BinopTokenType` were just meant to be factory
helpers, there's no reason for a class hierarchy.
2018-08-25 20:02:32 -04:00
Justin Ridgewell
5899940156 Update parser whitespace for clarity (#8539)
* Update parser whitespace for clarity

Has the nice benefit of not requiring a charCode to String conversion.

* Remove test262 exceptions

Per https://github.com/tc39/ecma262/pull/1218#issuecomment-395340891,
ECMA262 follows whatever the latest Unicode version specifies for Zs
Space_Separator category. MONGOLIAN VOWEL SEPARATOR was moved to the Cf
Other_Format category in Unicode 8.
2018-08-25 19:12:38 -04:00
Logan Smyth
595240f071 Add a 'whitelist' option for the external-helpers plugin to mirror the helper builder. (#8531) 2018-08-24 15:10:46 -07:00
Henry Zhu
cada040bec v7.0.0-rc.3 2018-08-24 14:06:00 -04:00
Nicolò Ribaudo
1f9b2a5c41 [_wrapNativeSuper] Don't wrap non-native constructors (#8501) 2018-08-24 19:58:49 +02:00
Logan Smyth
39fa102ee8 Use supportsStaticESM to toggle runtime module usage. (#8520) 2018-08-24 10:48:47 -07:00
Honza Javorek
e841ccca34 Upgrade slash (#8527) [skip ci]
The 1.x versions do not contain a full license text.
2018-08-24 11:31:27 -04:00
Artem Yavorsky
4249dbc8ea Add browserslist 4 support. (#8509) 2018-08-23 20:09:18 -05:00
Standa Opichal
a7cc3325cd Add LICENSE file to published npm packages [skip ci] (#8409) 2018-08-23 19:49:27 -04:00
Logan Smyth
023044c1d4 Reference the CommonJS helpers when a file is not explicitly a module. (#8518) 2018-08-23 15:09:14 -07:00
Rafael de Oleza
22bcfbe469 Fix path.scope.rename() to not change break clauses (#8478)
* Make labels on break and continue statements not referenced

* Add test for imports and labels with the same name
2018-08-23 14:20:57 -07:00
Jason Quense
47e05d70f3 Fixed issue with non-simple property paths in object-rest-spread loose mode (#8514)
* fix: object rest with default values bug

fixes #8323

* rename variable
2018-08-23 15:53:31 +02:00
Nicolò Ribaudo
c5e3b6d4bc [decorators] Don't set writable on accessors (#8513) 2018-08-23 00:54:28 +02:00
Logan Smyth
b04de1196a Rename exported functions where name conflicts with param. (#8505) 2018-08-21 13:54:29 -07:00
Henry Zhu
d07cef244e Update Babel to rc.2 (#8504) 2018-08-21 15:31:07 -05:00
dnalborczyk
6c68ca8e0a adjust supported npm versions to v3 (#8359) [skip ci] 2018-08-21 15:44:17 -04:00
Henry Zhu
f1d774b34f v7.0.0-rc.2 2018-08-21 15:22:07 -04:00
Jarda Snajdr
8874c5c481 Add missing es7.promise.finally polyfill when using useBuiltIns: usage (#8500)
Usage of a `finally` instance method should trigger import of the `es7.promise.finally` polyfill, but it doesn't. This PR adds the missing definition and a test.
2018-08-21 14:53:11 -04:00
Yi Li
b439013cd4 Fix trailingComments for FunctionExpression that is CallExpression arguments (#8488) 2018-08-21 12:29:11 -05:00
Nicolò Ribaudo
f8b0a5579f Remove File#resolveModuleSource (#8470) 2018-08-20 12:14:55 -07:00
Logan Smyth
2a4f162366 Merge pull request #8485 from loganfsmyth/caller-option
Allow preset-env to toggle module handling based on flags from the caller (like babel-loader)
2018-08-20 10:44:11 -07:00
Brian Ng
55295cc545 Add initial ES2019 and saf12/elec3 support in env (#8438) 2018-08-20 12:32:18 -05:00
Nicolò Ribaudo
59e9c6322b Remove hub.file usage from babel-core 2018-08-20 19:30:29 +02:00
Yongxu Ren
0fd3da110d Rewrite Hub as interface #5047 2018-08-20 19:30:29 +02:00
Logan Smyth
d60c5e1736 Expose caller.supportsStaticESM as a flag to change preset-env behavior. 2018-08-20 10:27:55 -07:00
Logan Smyth
90bebe7186 Pass the caller.name option in Babel's own callers. 2018-08-20 10:27:54 -07:00
Logan Smyth
8d6ed7e0aa Expose an api.caller(...) handler for presets to access caller metadata. 2018-08-20 10:27:54 -07:00
Logan Smyth
8f4bae8ea4 Expose optional caller metadata to Babel ignore/only/test/include/exclude functions. 2018-08-20 10:27:54 -07:00
Logan Smyth
2c3c12fdf7 Enforce a limited set of cache key values for plugins/presets for future caching. 2018-08-20 10:12:19 -07:00
Logan Smyth
25d2f59018 Ensure that presets properly flatten their options. 2018-08-20 10:12:19 -07:00
Logan Smyth
3a399d1eb9 Cache individual programmatic descriptors along with the overall list. (#8494) 2018-08-20 10:08:21 -07:00
Logan Smyth
c2a2e24965 Take top-level config source into consideration when processing nested env/overrides. (#8493) 2018-08-19 21:46:09 -07:00
Logan Smyth
ef68114d67 Fix typo in sourcemap filtering. 2018-08-19 16:37:29 -07:00
Logan Smyth
ca639b4262 Preserve 'false'-options for disabled plugins/presets so that callers can use that to toggle behavior. (#8474) 2018-08-19 16:22:27 -07:00
wtgtybhertgeghgtwtg
7a51d72345 Bump js-tokens in @babel/highlight. (#8490) 2018-08-19 07:35:16 -04:00
dnalborczyk
ab8555a867 Update dependencies (#8364) 2018-08-17 10:26:25 -05:00
Nicolò Ribaudo
0136a26af7 Fix conflict in tests (#8486) 2018-08-17 11:36:10 +02:00
Yeonghoon Park
c75a00bd56 Fix default descriptor setting for class properties with decorators (#7429)
(legacy decorators)
2018-08-17 10:49:03 +02:00
Logan Smyth
ffa8e6cbae Allow babel-plugin/preset to be in package names outside the prefix, when used in a scope. (#8473) 2018-08-16 15:13:52 -07:00
Nikolay Emrikh
5043ec78bc Fixes setter paratemer default value (#8479)
* Fixes setter paratemer default value

* Not changes doesn't mutate loose variable
2018-08-16 01:54:50 -04:00
Nicolò Ribaudo
3989213e37 Remove unused file (#8472) 2018-08-15 09:08:28 +02:00
Nicolò Ribaudo
d79b5eeeff Require decoratorsBeforeExport option for decorators (#8465)
* Require decoratorsBeforeExport option for syntax-decorators

* Also babylon

* Enable test
2018-08-15 09:04:52 +02:00
Logan Smyth
1e0b649485 Allow transform-runtime to insert runtime references with absolute paths. (#8435) 2018-08-14 16:11:19 -07:00
Laxman
8c65230258 Fix link to babel-parser (#8464) [skip ci] 2018-08-13 15:54:07 +02:00
Mauro Bringolf
427aff559f Fix decorators interop bug with class field tdz
Co-authored-by: Jan Buschtöns <jan@buschtoens.me>
2018-08-13 08:57:09 +02:00
wtgtybhertgeghgtwtg
de16ac08be Remove lodash where it isn't used. (#8446) 2018-08-09 23:21:41 -04:00
Henry Zhu
0a958861c9 v7.0.0-rc.1 2018-08-09 16:06:08 -04:00
Henry Zhu
904bcaffe3 fix peer deps [skip ci] (#8445)
Should be anything 7.x
2018-08-09 15:59:14 -04:00
宋铄运
e855987c51 update sponsor [skip ci] (#8444)
Add issue.sh sponsor from Patreon
2018-08-09 15:58:28 -04:00
Henry Zhu
8b1406127a v7.0.0-rc.0 2018-08-09 11:56:00 -04:00
Henry Zhu
c8bb450032 remove proposals polyfills from default import [skip ci] (#8440)
The default import is replaced with only polyfills that are Stage 4; this is in alignment with how we have removed the Stage presets. This also would mean we would need to add new imports when necessary, but that can be in a future release.
2018-08-09 11:43:45 -04:00
Logan Smyth
b6db036ff7 Require v1.1.0 so that correct filter params are passed. (#8436)
PR #8418 introduced some new logic that uses the third parameter of `fs-readdir-recursive`'s `filter` option, the current directory, but missed that our dependencies only required `^1.0.0`, while that parameter was actually added in `1.1.0`. This means that if some other dependency forced a downgrade in the version to satisfy some range, or the user already had 1.0.0 module installed locally, it could cause problems,
2018-08-07 23:28:36 -04:00
Sam Grace
6476a0d089 Whitelist experimental-modules flag for babel-node (#8336) [skip ci] 2018-08-06 11:45:38 -04:00
Henry Zhu
6695f5e2f7 v7.0.0-beta.56 2018-08-03 21:02:42 -04:00
Henry Zhu
86ce2e4e0d remove old deps [skip ci] 2018-08-03 20:42:45 -04:00
Henry Zhu
8cffbbae75 Split @babel/runtime into 2 modules via @babel/runtime-corejs2 (#8266)
In Babel 6, we had `@babel/runtime` which _always_ uses `core-js` in its helpers, meaning that anyone who wants to use our helpers in a centralized modular way had to also use core-js, which isn't always ideal.

Early in the Babel 7 alpha, we added a `useBuiltins: true` option that would use separate copies of the helpers that would skip loading `core-js`, but this _still_ requires users to have an indirect npm dependency on `core-js`.

This PR splits our setup into two separate runtimes:

* ```
  'plugins': [
    ['transform-runtime'],
  ]
  ```
  with `npm install --save @babel/runtime` that just includes our helpers, and relies on users to globally polyfill any APIs they need.
* ```
  'plugins': [
    ['transform-runtime', { corejs: 2 }],
  ]
  ```
  with `npm install --save @babel/runtime-corejs2` that includes everything `@babel/runtime` does, but also includes a passthrough API for `corejs@2.x` and rewrites all of the helper modules to reference `core-js`.
2018-08-03 15:13:33 -04:00
Jan Schmidle
cb51704745 Babel cli fix recursion in file mode (#8418)
* added test case

* remove unnessecary parameter

* check for type directory as well in readRecursive filter
2018-08-03 09:06:27 -07:00
Logan Smyth
a8224d40e2 Split @babel/runtime into two separate runtime modules. 2018-08-02 19:25:07 -07:00
Logan Smyth
3210a7a873 Default to non-corejs helpers. 2018-08-02 19:24:41 -07:00
Logan Smyth
9c598a8e28 Build an explicit runtime. 2018-08-02 19:23:47 -07:00
Logan Smyth
a149466001 Move build-dist script to the runtime transform. 2018-08-02 19:23:47 -07:00
Logan Smyth
ec8330870e Refactor the runtime build-dist script. 2018-08-02 19:22:23 -07:00
Logan Smyth
363c5923f0 Remove unused options.json file. 2018-08-02 19:21:40 -07:00
Logan Smyth
8173b6e694 Merge pull request #8398 from loganfsmyth/helper-whitelisting
Only reference helpers from external/runtime helpers if they are known to be available.
2018-08-02 19:20:56 -07:00
Logan Smyth
e2d64f146c Only reference helpers from external helpers or runtime helpers if they are known to be available. 2018-08-02 18:44:56 -07:00
Logan Smyth
9392783738 Remove helpersNamespace in favor of helperGenerator. 2018-08-02 18:44:56 -07:00
Logan Smyth
810b7916c2 Expose an API to check if a helper is available in a given version range. 2018-08-02 18:44:56 -07:00
Logan Smyth
eb0e999987 Expose a minimum required Babel version for each helper. 2018-08-02 18:44:56 -07:00
kalenikalexander
5c728ea609 Fix private property parsing in Flow (#8340)
* Fix private property parsing in Flow

* Flow tests updated

* Fix type error

* Appropriate name was given to test folder

* Fix

* Empty

* Correct type annotation

* Add required changes in generator package

* Add required changes in flow-strip-types
2018-08-02 08:38:58 +02:00
Leong Jia Meng
b8f9ebf638 Update Documentation[skip ci] (#8412) 2018-08-01 10:33:11 -05:00
Brian Ng
55ca90b3fc Allow TSInterfaceDeclaration to be default export (#8408)
<!--
Before making a PR, please read our contributing guidelines
https://github.com/babel/babel/blob/master/CONTRIBUTING.md

For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. (it should be underlined in the preview if done correctly)

If you are making a change that should have a docs update: submit another PR to https://github.com/babel/website
-->

| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | Fixes #7118
| Patch: Bug Fix?          | Y
| Major: Breaking Change?  | N
| Minor: New Feature?      | N
| Tests Added + Pass?      | Yes
| Documentation PR Link    | 
| Any Dependency Changes?  |
| License                  | MIT
2018-07-31 12:57:57 -05:00
Brian Ng
1a0fe993f5 Ensure esmodule targets are parsed by browserslist (#8403) 2018-07-31 07:33:02 -05:00
Logan Smyth
02760d0f70 Run transform-runtime on the standalone bundle so it stays ES5-compatible. (#8024) 2018-07-29 16:52:11 -07:00
Henry Zhu
adca165ee9 v7.0.0-beta.55 2018-07-28 18:06:42 -04:00
Henry Zhu
fa86b2ddf0 Remove our own use of stage presets (#8397)
- also update the stage preset error message/readme's to point to the new blog post
2018-07-28 11:24:53 -04:00
Logan Smyth
5eb193c61f Ensure that Identifier source mappings explicitly start and stop on the generated range (#8380)
* Add sourcemap examples for identifiers in code generator.

* Generate sourcemaps with exact mappings for identifiers, even if leading/trailing tokens also use that location.
2018-07-27 16:27:33 -04:00
Nicolò Ribaudo
ec69b4bb12 Save full descriptor instead of only value for private fields. (#8318)
* Save full descriptor instead of only value for private fields.

Decorators can make private fields non-writable, so we need to store this
information somewhere.
The descriptor can also be used to implement private accessors.
2018-07-27 16:24:57 -04:00
Brian Ng
5fdcd29ef9 Ensure preset-env doesn't clobber browserslist defaults (#8391) 2018-07-26 15:22:26 -04:00
Andy
8ee24fdfc0 TypeScript: Support type arguments on tagged templates (#7754)
| Q                        | A
| ------------------------ | ---
| Fixed Issues?            | #7747 (partly)
| Patch: Bug Fix?          | 
| Major: Breaking Change?  | 
| Minor: New Feature?      | Yes
| Tests Added + Pass?      | Yes
| Documentation PR         |
| Any Dependency Changes?  |
| License                  | MIT

@JamesHenry This changes the AST format. CC @DanielRosenwasser for review.
Supports parsing type arguments on tagged template calls.
Should wait on Microsoft/TypeScript#23430 to be merged so we're sure we have the final syntax.
2018-07-26 10:44:43 -05:00
Qix
db2a9fc96e Fix order of optional argument reordering (#8376)
Previously, if the optional `opts` parameter wasn't passed, the _intent_ was to move the function it held into the `callback` parameter and null out the `opts` param - but instead, it was nulling both.
2018-07-26 11:25:35 -04:00
Sven Sauleau
75767e9273 Merge pull request #8381 from wtgtybhertgeghgtwtg/babelrcroots-array
Allow an Array for `babelrcRoots`.
2018-07-25 11:36:57 +02:00
wtgtybhertgeghgtwtg
4346a95b88 Perform check on each member of babelrcroots. 2018-07-24 16:57:24 -07:00
Maximilian Berkmann
26cbbb569f Bumped lodash to 4.17.10 (#8377) 2018-07-24 12:57:43 -04:00
Kevin Gibbons
a811cf78e1 Correctly parse interface methods named 'static' (#8374) 2018-07-24 09:25:55 +02:00
Henry Zhu
c70a32ab9d Throw when using Stage presets (#8293)
* inline stage presets into standalone, throw error with using Stage presets
2018-07-23 22:22:52 -04:00
Thiago Arrais
6f3a800677 Do not mutate ast (#8342)
This clones the given ast prior to working on it to avoid mutating the AST given to `transformFromAST`.
2018-07-23 22:20:55 -04:00
Kevin Gibbons
d781e207c8 Docs: fix typo in path (#8372) [skip ci] 2018-07-23 20:32:44 -04:00
dnalborczyk
8b10a44fe1 remove .then from dynamic import parser exception message (#8355) 2018-07-21 08:26:17 +02:00
dnalborczyk
adae1501ac update jest (major), babel-jest (major) (#8341)
updated `jest` and `babel-jest` to `v23`

fixed breaking change in `jest`:
- https://github.com/facebook/jest/blob/master/CHANGELOG.md#2300
- https://github.com/facebook/jest/pull/5558

_edit:_
forgot to mention. test runner fix is based on: https://github.com/babel/babel/blob/master/packages/babel-parser/test/helpers/runFixtureTests.js#L11
2018-07-19 10:43:35 -04:00
dnalborczyk
c8038f69fe update prettier (#8339) 2018-07-19 09:08:45 -05:00
dnalborczyk
30ea328e97 bump flow (#8338) 2018-07-19 09:41:09 -04:00
dnalborczyk
16b1f8c427 updates eslint, babel-eslint, eslint-plugin-flowtype, eslint-plugin-prettier (#8337) 2018-07-19 09:36:52 -04:00
Henry Zhu
a582cc5bd8 update changelog for .53/.54 [skip ci] 2018-07-18 08:54:05 -04:00
Henry Zhu
84282f199b v7.0.0-beta.54 2018-07-16 13:59:43 -04:00
Logan Smyth
52a569056c Merge pull request #8327 from loganfsmyth/drop-pattern-matching
Treat string ignore/only/test/include/exclude values as paths with only basic pattern matching
2018-07-16 10:11:23 -07:00
Henry Zhu
7446d06911 also default stage 2 to decoratorsLegacy true [skip ci] 2018-07-16 13:07:17 -04:00
James DiGioia
8817fcf03e Fix stage-0/1 import of pipeline/decorators proposals (#8317)
Just default to pipeline "minimal" and true for decorators for ease of use. We are going to remove the stage presets next so it's fine since it will error when using the plugin individually later.
2018-07-16 13:02:54 -04:00
Logan Smyth
6d177ba4c5 Remove micromatch and use a simple pattern matching utility. 2018-07-16 09:57:14 -07:00
Logan Smyth
935533cff3 Ensure that the wildcard interop is used with re-export + default. (#8316) 2018-07-14 12:49:31 -07:00
Logan Smyth
c4f67bfa57 Leave it to users to clear the require cache if they want to. 2018-07-14 12:48:58 -07:00
Logan Smyth
2854a187be Remove dependency on barely-used package. 2018-07-14 12:41:36 -07:00
rugk
62ee1adc85 Add link to audio version of song (#8320) 2018-07-13 15:34:40 -05:00
Logan Smyth
fd9ebf9e1d Remove option-filtering options from the final options results. (#8315)
| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | Fixes https://github.com/babel/babel-loader/issues/642
| Patch: Bug Fix?          | Y
| Major: Breaking Change?  | N
| Minor: New Feature?      |
| Tests Added + Pass?      | Yes
| Documentation PR Link    | <!-- If only readme change, add `[skip ci]` to your commits -->
| Any Dependency Changes?  |
| License                  | MIT

Since these were getting left in, things that loaded the config, and then passed in back to Babel would get `test` and such _twice_, which could lead to either bad configuration merging, or no configuration at all if the patterns were relative to different directories, as was the case in https://github.com/babel/babel-loader/issues/642.
2018-07-13 07:01:11 -07:00
Daniel Tschinder
dca6125128 Update pirates to 4.0 (#8308) 2018-07-11 16:04:27 -04:00
Henry Zhu
093483c399 remove yearly preset folders [skip ci] 2018-07-11 11:08:33 -04:00
Henry Zhu
b89234b1a2 v7.0.0-beta.53 2018-07-11 09:39:52 -04:00
Ryan Tsao
f2fd9e982e Make env preset build-data scripts reproducible (#8299) 2018-07-10 20:43:45 -05:00
Andy
301db1b921 TypeScript: Support type arguments on JSX opening and self-closing tags (#7799) 2018-07-10 17:19:42 -05:00
James DiGioia
19a1705293 Support pipeline proposal flag in @babel/parser (#8291) 2018-07-09 16:59:56 -04:00
Henry Zhu
10910a10f5 Remove yearly presets from repo, inline in standalone (#8274)
These were already deprecated in v6, just didn't remove the folders?
2018-07-09 14:23:25 -04:00
Henry Zhu
dd6da3b3af rm extra changelog [skip ci] 2018-07-07 18:44:43 -04:00
Henry Zhu
d2d2118a44 Move v4, v5, v6 changelogs to separate files [skip ci] (#8286) 2018-07-07 18:43:34 -04:00
Mateusz Burzyński
21de1581aa Fixed fixture tests after merge (#8287) 2018-07-07 18:40:15 -04:00
Mateusz Burzyński
b5e64cb66e Remove unused bindings when excluding keys with rest in loose mode (#8264) 2018-07-07 19:54:51 +02:00
Alan Pierce
44f738bcbf Upgrade upath to avoid yarn failure on node 10 (#8283) [skip ci]
upath 1.0.4 doesn't support node 10, and this was fixed in later versions
( https://github.com/anodynos/upath/pull/15 )
2018-07-07 10:52:55 -04:00
Henry Zhu
13153ede92 add changelog for 6.23.1-3 [skip ci] 2018-07-07 10:28:01 -04:00
Mateusz Burzyński
c0c13ae30f Introduce objectWithoutPropertiesLoose helper (#8261) 2018-07-06 15:03:44 -04:00
Henry Zhu
cea562c009 Revert micromatch upgrade (regression) [skip ci] (#8281)
Original PR: https://github.com/babel/babel/pull/8038
Ref Issue: https://github.com/babel/babel/issues/8184

Windows paths are broken so wanted to get a fix out since I don't see us fixing it correctly soon enough? I think that's more important than fixing the security warnings that don't apply to us until we can actually handle the change, otherwise need a version of the code that doesn't use the old dep but doesn't change the windows behavior or just remove the matching which will take some time.
2018-07-06 14:28:02 -04:00
James DiGioia
f93fa28c90 Improve error messages around pipeline option (#8279) 2018-07-06 13:01:35 -04:00
Brian Ng
430a105ae7 Compile against beta 52 (#8282) 2018-07-06 12:12:19 -04:00
Tatsuyuki Ishi
3e71108f82 Invoke Jest main file directly (#8187) 2018-07-06 10:09:49 -04:00
Tim Kendrick
e9184ed05e [babel-types] Fix isNodesEquivalent() behavior for TemplateElements (#8165)
Fixes #8163

The `isNodesEquivalent()` algorithm incorrectly assumes that any object properties must themselves be AST nodes, which is not the case here, causing the error.
2018-07-06 08:45:25 -04:00
1211 changed files with 15477 additions and 20953 deletions

View File

@@ -4,8 +4,9 @@
package.json
lerna.json
packages/babel-runtime
!packages/babel-runtime/scripts
!packages/babel-runtime/core-js.js
!packages/babel-plugin-transform-runtime/scripts
!packages/babel-runtime-corejs2/core-js.js
packages/babel-runtime-corejs2
packages/*/node_modules
packages/*/lib
packages/*/dist

View File

@@ -5,6 +5,7 @@
.*/codemods/.*/lib
.*/codemods/.*/test
.*/node_modules/conventional-changelog-core/
.*/node_modules/module-deps/
[include]
packages/*/src

287
.github/CHANGELOG-v4.md vendored Normal file
View File

@@ -0,0 +1,287 @@
# Babel v4 Changelog
## 4.7.16
* **Bug Fix**
* Fix constructor spreading of typed arrays.
* Fix break/continue/return aliasing of non-loops in block scoping transformer.
## 4.7.15
* **Bug Fix**
* Fix constructor spreading of collections.
## 4.7.14
* **Bug Fix**
* Fix constructor spreading of `Promise`.
* **Internal**
* Deprecate remaining playground transformers and abstract references.
## 4.7.13
* **Bug Fix**
* Handle comments on use strict directives.
* Fix assignment patterns with a left side pattern.
* **Polish**
* Special case `this` when doing expression memoisation.
## 4.7.12
* **Bug Fix**
* Deprecate `playground.methodBinding`.
## 4.7.11
* **Bug Fix**
* Fix unicode regexes stripping their unicode flag before being passed on two `regexpu`.
## 4.7.10
* **Internal**
* Deprecate `playground.methodBinding` and `playground.objectGetterMemoization`.
* **Bug Fix**
* Fix `inputSourceMap` option. Thanks [@Rich-Harris](https://github.com/Rich-Harris)!
## 4.7.9
* **Polish**
* Allow `inputSourceMap` to be set to `false` to skip the source map inference.
* Infer computed literal property names.
* **Bug Fix**
* Fix nested labeled for-ofs.
* Fix block scoping `break` colliding with the parent switch case.
* **Internal**
* Upgrade `acorn-babel`.
## 4.7.8
* **Bug Fix**
* Fix computed classes not properly setting symbols.
## 4.7.7
* **Bug Fix**
* Fix `types` API exposure.
## 4.7.6
* **Bug Fix**
* Fix non-Identifier/Literal computed class methods.
* **Polish**
* Add a fallback if `stack` on an error is unconfigurable.
* Hoist `esModule` module declarations to the top of the file to handle circular dependencies better.
## 4.7.5
* **Bug Fix**
* Don't remap` break`s to call the iterator return.
* **Polish**
* Use a different helper for computed classes for much nicer output. Also fixes a bug in symbols being non-enumerable so they wouldn't be set on the class.
## 4.7.4
* **Bug Fix**
* Rewrite named function expressions in optional async function transformers.
* Hoist directives.
* Remove `Number` from the list of valid `runtime` constructors.
* **Internal**
* `spec.typeofSymbol` transformer has been renamed to `es6.symbols`.
## 4.7.2
* **New Feature**
* `"both"` option for `sourceMap`.
* Add output types to external helpers. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)!
* **Bug Fix**
* Fix node duplication sometimes resulting in a recursion error.
* Ignore `break`s within cases inside `for...of`.
* **Polish**
* Split up variable declarations and export declarations to allow easier transformation.
## 4.7.0
* **Bug Fix**
* Add `alternate` to list of `STATEMENT_OR_BLOCK` keys.
* Add support for module specifiers to `t.isReferenced`.
* **New Feature**
* Add `inputSourceMap` option.
* **Polish**
* Throw an error on different `babel` and `babel-runtime` versions.
* Replicate module environment for `babel-node` eval.
* Clean up classes output.
* **Spec Compliancy**
* Make it illegal to use a rest parameter on a setter.
## 4.6.6
* **Bug Fix**
* Fix incorrect method call in `utility.deadCodeElimination` transformer.
* Fix `es6.blockScopingTDZ` transformer duplicating binding nodes.
## 4.6.5
* **Internal**
* `useStrict` transformer has been renamed to `strict`.
## 4.6.4
* **Bug Fix**
* Fix `ForOfStatement` not proplery inheriting labels.
* When in closure mode in block scoping transformer, properly check for variable shadowing.
* **New Feature**
* New `utility.inlineEnvironmentVariables` and `utility.inlineExpression` transformers.
## 4.6.3
* **Bug Fix**
* Fix `arguments` being incorrectly aliased in arrow function rest parameter optimisation.
* Make deoptimisation trigger safer.
* **New Feature**
* Flow types are now retained when blacklisting the `flow` transformer.
## 4.6.1
* **Bug Fix**
* Fix generators in template directory being transformed.
* Fix exposure of `util` for plugins.
## 4.6.0
* **New Feature**
* Desugar sticky regexes to a new constructor expression so it can be handled by a polyfill.
* **Spec Compliancy**
* `for...of` now outputs in a lengthy `try...catch` this is to ensure spec compliancy in regards to iterator returns and abrupt completions. See [google/traceur-compiler#1773](https://github.com/google/traceur-compiler/issues/1773) and [babel/babel/#838](https://github.com/babel/babel/issues/838) for more information.
* **Polish**
* Rest parameters that are only refered to via number properties on member expressions are desugared into a direct `arguments` reference. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)!
* `$ babel` no longer exits on syntax errors.
* **Internal**
* Upgrade `browserify`.
* Upgrade `source-map`.
* Publicly expose more internals.
## 4.5.5
* **Polish**
* Delete old extensions when overriding them in `babel/register`.
## 4.5.3
* **Bug Fix**
* Fix whitelisting logic for helper build script.
## 4.5.2
* **New Feature**
* `returnUsedHelpers` option and add whitelist to `buildHelpers`.
* **Bug Fix**
* Fix function arity on self referencing inferred named functions.
* **Internal**
* Bump `acorn-babel`.
* Start converting source to ES6...
## 4.5.1
**Babel now compiles itself!**
![holy shit](http://gifsec.com/wp-content/uploads/GIF/2014/03/OMG-GIF_2.gif)
## 4.5.0
* **New Feature**
* Add `.babelrc` support.
* **Bug Fix**
* Move use strict directives to the module formatter bodies.
* **Internal**
* Make default `bin/babel` behaviour to ignore non-compilable files and add a `--copy-files` flag to revert to the old behaviour.
## 4.4.6
* **Bug Fix**
* Fix extending a class expression with no methods/only constructor. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)!
* Allow `MemberExpression` as a valid `left` of `ForOfStatement`.
* **Polish**
* Throw an error when people try and transpile code with the `@jsx React.DOM` pragma as it conflicts with the custom jsx constructo method detection.
* Crawl all comments for `@jsx` pragma.
* **Internal**
* Upgrade `chalk`.
* Upgrade `core-js`.
## 4.4.5
* **Internal**
* Remove function self reference optimisation.
## 4.4.4
* **Bug Fix**
* Handle inferred function ids to be reassigned and deopt to a slower but working equivalent.
* Don't unpack array patterns that have more elements than their right hand array expression.
* **Polish**
* Improve syntax highlighting in the code frame. Thanks [@lydell](https://github.com/lydell)!
* **Internal**
* Upgrade `acorn-babel`.
## 4.4.3
* **Bug Fix**
* Fix `for...of` iterator break returns being duplicated.
* Only call `return` on the iterator if it exists.
* **Internal**
* Rename `selfContained` transformer to `runtime`.
## 4.4.2
* **New Feature**
* Add `moduleId` option for specifying a custom module id.
## 4.4.0
* **New Feature**
* `/*** @jsx NAMESPACE **/` comments are now honored by the `react` transformer.
* `getModuleName` option.
* Infer function expression names. Thanks [@RReverser](https://github.com/RReverser)!
* **Bug Fix**
* Add proper control flow for tail recursion optimisation.
* **Internal**
* Remove useless `format` options and move the `format.compact` option to `format`.
* **Polish**
* Newline handling of the code generator has been heavily improved.
* Code generator now deopts whitespace if the input size is >100KB.
## 4.3.0
* **Breaking Change**
* Remove `commonStandard` module formatter and make it the default behaviour of all the strict module formatters.
## 4.2.1
* **Polish**
* Add auxiliary comment to let scoping closure flow control.
## 4.2.0
* **Polish**
* Use an assignment instead of a define for `__esModule` in loose mode.
* **Internal**
* Add error for `eval();` usage and enable strict mode for parsing.
## 4.1.0
* **New Feature**
* Add `BABEL_CACHE_PATH` and `BABEL_DISABLE_CACHE` environment variables.
* **Internal**
* Replace many internal util functions with modules. Thanks [@sindresorhus](https://github.com/sindresorhus)!
## 4.0.2
* **Bug Fix**
* Fix generators not properly propagating their internal declarations.
* **Polish**
* Update setter param length error message.
* Use ranges on dependencies.
## 4.0.0
* 6to5 is now known as Babel.
* Global helpers/runtime has now been given the more descriptive name of "external helpers".

839
.github/CHANGELOG-v5.md vendored Normal file
View File

@@ -0,0 +1,839 @@
# Babel v5 Changelog
## 5.8.26
* **Internal**
* Republish to get fix for runtime `typeof-react-element` helper.
## 5.8.25
* **Internal**
* Rename `define` method to avoid webpack assuming those files are AMD.
## 5.8.24
* **Spec Compliancy**
* Updated `optimisation.react.inlineElements` transformer to React 0.14 output. Thanks [@spicyj](https://github.com/spicyj)!
* **Polish**
* Add support for evaluating more static nodes. Thanks [@hzoo](https://github.com/hzoo)!
## 5.8.23
* **Bug Fix**
* Fix a bug where pushed scope bindings weren't properly being registered.
## 5.8.22
* **Bug Fix**
* Fix bug causing regexes to cause a syntax error after a block.
* **Internal**
* Expose `File`.
## 5.8.21
* **New Feature**
* Add support for Flow export types.
* **Bug Fix**
* Fix flow type annotations on object properties being lost.
* Fix bug effecting nested arrow functions.
* Check valid `export default` `function`/`class` token when parsing export default before converting to a declaration to avoid turning expressions into declarations.
* **Polish**
* Add an exception to non-existent bindings when checking if we need to wrap block scoping blocks in a closure.
* Make comment retainment for multiple replacement nodes more predictable.
* **Internal**
* Remove `operator` property from `AssignmentPattern` nodes.
* Update `es7.asyncFunctions` and `es7.objectRestSpread` to stage 2.
## 5.8.13-5.8.20
**The CHANGELOG was broken for these releases. Git tags were not pushed in the correct order and are therefore incorrect. It's recommended you NOT use any versions within this range.**
* **New Feature**
* Add `es6.spec.modules` transformer.
* **Bug Fix**
* Don't register export declarations as a module binding.
* Register import bindings to the specifier instead of the declaration.
* `export *` should not export `default`.
* Clear `rawValue from JSX attribute values to avoid outputting the raw source verbatim.
* Add support for boolean flow literals.
* Fix bug where files that babel can compile weren't being written when ignored with the `--copy-files` flag.
* Create new raw identifiers instead of cloning the original user one when exploding export specifiers to fix source map issues resulting in incorrect locations.
* Break on hitting a terminator paren triggering character to avoid pushing multiple starting parens.
* Consider comment starting character to be a terminatorless separator to avoid starting comments breaking terminatorless nodes.
* **Internal**
* Use `json5` for parsing `.babelrc` files and `JSON` for `package.json`.
* Update Regenerator dependency to `0.8.35`.
* Remove flow types from being scope tracked.
* **Polish**
* Only register export declarations in scope tracking if they're of a valid type.
* Only output code frame and message on syntax errors in CLI.
* Set decorated initialisers that have no `initialiser` to `undefined`.
* Optimise common `typeof` cases in `es6.spec.symbols` transformer.
## 5.8.12
* **Bug Fix**
* Fix bug in lookahead causing decorators to be cleared.
## 5.8.11
* **Bug Fix**
* Check if module options are nully instead of falsy to allow empty strings as `moduleRoot` etc.
* Fix bug where reassigning the rest parameter wouldn't result in a deoptimisation.
## 5.8.9
* **Bug Fix**
* Fix issue in parser where the flow plugin wasn't using state to refer to whether it as in a type or not causing lookaheads to cause breakages.
## 5.8.8
* **Bug Fix**
* Fix comments not being attached if they're touching the start of their node.
## 5.8.7
* Never published, environment issues, again.
## 5.8.6
* **Bug Fix**
* Remove `rawValue` for JSX inner text.
## 5.8.5
* **Polish**
* Rewrite parentheses insertion for terminatorless nodes such as `BreakStatement` to be much more stable and cleaner.
* Use `Object.setPrototypeOf` and fallback to `__proto__` in `inherits` helper.
## 5.8.2-5.8.4
Issues with publish process.
## 5.8.1
* **Bug Fix**
* Fix regression where async arrow functions couldn't have type annotation parameters.
* Output type annotations of type instantiation parameters.
* **Polish**
* Prepend to highest loop when performing rest parameter allocation optimisation.
* Add comment attachment to parser.
* Add support for retaining inner comments of empty blocks.
## 5.8.0
* Never released due to publish environment issues.
## 5.7.4
* **Bug Fix**
* Fix comments containg `@flow` being completely removed from output rather than just the specific directive.
## 5.7.3
* **Bug Fix**
* Add shim file for broken file path that old versions of the CLI would attempt to use.
## 5.7.2
* **Bug Fix**
* Fix performance issue in code generator when comment columns would attempt to match up in `compact` mode causing large amounts of whitespace.
* Fix single line comments not outputting a newline in `compact` mode.
* **Polish**
* Add support for flow return types for arrow functions.
## 5.7.1
* **Bug Fix**
* Add back mistakenly removed `replaceWithSourceString` method.
## 5.7.0
* **Bug Fix**
* Deopt on spread elements when performing array destructuring unpack optimisation.
* **New Feature**
* Add `shouldPrintComment` option to control comment output.
* Add `.babelignore` file to be consistent with other tools.
* Allow `.babelrc` configs to be specified via `package.json`.
* **Polish**
* Don't ignore comments when using `compact: true` option.
* Add support for Flow `import typeof`.
* Fix incorrect inheritance method position when using loose mode classes and constructor isn't the first item.
* **Internal**
* Completely fork Acorn with `babylon`.
* Rewrite build system to accommodate for multiple packages.
## 5.6.17
* **Bug Fix**
* Fix `CodeGenerator.findCommonStringDelimiter` causing a stack overflow.
## 5.6.16
* **Internal**
* Fix `recast` version to avoid pulling in a newer version.
* **New Feature**
* Add support for functions in `util.shouldIgnore`.
* **Polish**
* Strip flow directives in flow transformer.
* Add a check for out of bounds default parameters, drastically improving performance and removes engine deoptimisations.
* Various performance optimisations by [@samccone](https://github.com/samccone) 💅✨
* Delay `this` assignment when referencing this inside an arrow function pre-bare super in derived class constructors.
* Split up class body pushing if the constructor is in the wrong order.
* **Bug Fix**
* Fix hoisting of `ForInStatement` `init` variables in `system` module formatter.
* `PathHoister`: Don't hoist to the same function as their original paths function parent.
* `PathHoister`: Push each violation paths ancestry to the breakOnScopePaths collection to avoid constant hoisting to nested paths.fix tail call recursion on functions with less arguments than parameters.
* Disallow `super.*` before `super()` in derived class constructors.
* Properly regenerate scope for replaced nodes. Thanks [@loganfsmyth](https://github.com/loganfsmyth)!
* Move up template literal simplification logic to avoid breaking on single elements.
## 5.6.13-5.6.15
* Setting up automatic Travis releases.
## 5.6.12
* **Bug Fix**
* Fix finding parent for top-level shadowed functions.
## 5.6.11
** **Internal**
* Merge `es6.parameters.rest` and `es6.parameters.default` transformers. See commit [c0fd4c1f9e0b18231f585c4fa793e4cb0e01aed1](https://github.com/babel/babel/commit/c0fd4c1f9e0b18231f585c4fa793e4cb0e01aed1) for more info.
## 5.6.10
* **Bug Fix**
* Fix faulty internal require check.
* **Polish**
* Add support for trailing commas in arrow function parameter lists.
## 5.6.8
* **Bug Fix**
* Fix binary expressions colliding with unary expression operators in compact mode.
* Fix node properties being set to `null` when using computed properties.
## 5.6.7
* **Bug Fix**
* Fix hoisting of `ForXStatement` `left` `var`s when inserting a block scoping IIFE.
* **Polish**
* Combine all leading computed property initialisers into the root object in loose mode.
* **Internal**
* Deprecate returning of replacement strings from visitor methods.
## 5.6.6
* **Bug Fix**
* Fix weird parser bug where `void` type annotations were being parsed as keywords causing the tokeniser to lose track of context.
## 5.6.5
* **Bug Fix**
* Fix nested functions causing rest parameter optimisation to not properly detect when it should deopt on a reference.
* **Internal**
* Update Regenerator `0.8.31`.
## 5.6.4
* **Internal**
* Add `ParenthesizedExpression` node type.
## 5.6.3
* **Bug Fix**
* Fix rest parameter array allocation loop being incorrectly aliased.
## 5.6.2
* **Bug Fix**
* Fix method key literals not turning into computed member expression in loose mode.
* Elect rest parameters in spread element position as candidates instead of replacing them in place.
## 5.6.0
* **Bug Fix**
* Fix istanbul interop for register hook when registering for non-existence extension.
* Fix super class constructor call differing for no constructor in derived classes.
* Disable module import receiver when in loose mode.
* Fix duplicate filenames when using `babel` CLI when passing multiple matching patterns.
* Register labels as bindings to fix undeclared variable checks.
* **Polish**
* Remove unnecessary string binary expressions when transforming template literals.
* Support module live bindings in arbitary positions not in Program statement position.
* Throw error when attemping to replace a `Program` root node with another node not of type `Program`.
* Optimise rest parameters in spread element position and allocate rest array at the earliest common ancestor of all references.
* Generate original number representation when value was not changed.
* Check for invalid binding identifiers when generating inferred method names.
* Don't terminate CLI when watching files fail compilation on init.
* **New Feature**
* Add new plugin API.
* **Internal**
* Split react displayName addition into a plugin.
* Add check for `JSXMemberExpression` to `t.isReferenced`.
* Move `validation.undeclaredVariableCheck` transformer up.
* Start great core-to-plugin exodus.
* Add `BindingIdentifier` virtual type.
* Hidden class optimisations.
* Array allocation optimisations.
* Update `regenerator`.
* Update `js-tokens`.
* Sync with upstream Acorn.
## 5.5.8
* **Internal**
* Remove extremely unprofessional and harsh error message for those hotlinking to `resolve-rc`.
## 5.5.7
* **Bug Fix**
* Push newline after decorators when doing code gen.
* Rewriting error handling to normalise options before merging them.
* Remove duplicate keys in `alias-keys.json` causing errors in strict mode.
* Fix `$ babel --help` not showing optional transformers as such.
* **New Feature**
* Add `auxiliaryCommentBefore` and `auxiliaryCommentAfter` options.
## 5.5.6
* **Bug Fix**
* Fix `let` binding collision in loop head not properly replacing `AssignmentExpression`s.
## 5.5.5
* **Bug Fix**
* Fix `file.opts` not being set before `file.log.deprecate` was called causing a `ReferenceError` as it was checking for a property on it.
## 5.5.4
* **Bug Fix**
* Add back missing `shouldIgnore` check.
* Log message on deprecated options rather than throw an error.
* Fix name of `auxiliaryComment` option when attempting Istanbul interop in `babel/register`.
## 5.5.3
* **Bug Fix**
* Fix weird state bug when traversing overa `node` `ClassProperty` instead of `path` in the `es6.classes` transformer.
## 5.5.2
* **Bug Fix**
* Fix `NodePath#isPure` on `Property` nodes.
* Use cwd instead of entry file directory when working out relative directory for `babel/register`.
* **Internal**
* Add scary warning for those few who choose to use the WIP experimental transformers.
## 5.5.1
* **Bug Fix**
* Remove `ClassProperty` nodes always in the `Flow` transformer. This is fine now since class properties aren't supported in any engine that supports classes but the `es7.classProperties` transformer will need to be updated in the future to desugar to ES6 classes instead of relying on the `es6.classes` transformer from being ran.
## 5.5.0
* **Bug Fix**
* Allow pushing declarations to `SwitchStatement`s.
* Fix `minification.removeDebugger` to remove `DebuggerStatement`s rather than `ExpressionStatement`s with an identifier of `debugger`.
* Check LHS in `ForInStatement` and `ForOfStatement` for constant violations.
* Register function `id` as a reference when naming methods to avoid collisions.
* Support key literals when checking for the existence of `displayName` property when attempting to add it for `React.createClass`.
* Remove `ExportDefaultSpecifier` check from `t.isDefaultSpecifier`.
* Don't consider `JSXIdentifier` HTML tag identifiers to be references.
* **Polish**
* Update `minification.deadCodeElimination` transformer to remove all statements after completion statements.
* Update `minification.deadCodeElimination` transformer to not inline single used bindings that exist in different scopes.
* When performing Istanbul interop in `babel/register`, add the auxiliary comment `"istanbul ignore text"` to get more accurate coverage.
* Add `--nolazy` argument to `babel-node`.
* Add support for `cluster` forking.
* Perform scope tracking in a single pass instead of multiple.
* Smarten up type inferrence and resolution to support the whole array of language constructs.
* Optimise module metadata retrieval into a single pass.
* Ignore trailing commas when inferring newlines.
* Rename `minification.inlineExpressions` transformer to `minification.constantFolding`.
* Check path relative to entry file when checking to see if we're inside `node_modules` when using `babel/register`.
* Upgrade `regenerator`.
## 5.4.7
* **Bug Fix**
* Don't consider `JSXAttribute` `names` to be valid `ReferencedIdentifier`s.
## 5.4.6
* **Bug Fix**
* Fix `spec.functionName` transformer incorrectly attempting to rename a binding that doesn't exist as it's a global.
* **Internal**
* Deprecate custom module formatters.
## 5.4.5
* **Bug Fix**
* Add `JSXIdentifier` as a valid `ReferencedIdentifier` visitor virtual type.
* Ignore `CallExpression` `_prettyCall` when the `retainLines` option is enabled.
* Inherit comments to new declaration node when exploding module declarations.
* Fix `es6.tailCall` transformer failing on calls that exceed the max parameters of the function.
## 5.4.4
* **Bug Fix**
* Fix bug where replacing variable declarations in the head of a `for` loop would turn them into `ExpressionStatement`s.
* Fix renaming of assignment expressions that were non-identifiers ie. patterns.
* Force space before `class` `id` to avoid breaking named classes when using `compact` mode.
* Add assignment pattern explosion to avoid initial duplicate nodes.
* Ignore this and arguments when performing TCO on shadowed functions.
* **Polish**
* Rename `sourceMapName` option to `sourceMapTarget`. Thanks [@getify](https://github.com/getify)!
* Better detection of completion records, ignore those in `Function`s.
* Clarified descriptions of the options that are enabled by default.
* Resolve `\`babel-plugin-${name}\`` plugin names **before** just checking the `name`. Thanks [@jquense](https://github.com/jquense)!
* Update AMD module formatter to add import default remapping.
## 5.4.3
* **Bug Fix**
* Fix `module` being incorrectly rewritten when used as in an export declaration.
* When performing single-reference inlining, ensure that the single reference isn't a child of the binding itself.
* Fix a bug in `minification.deadCodeElimination` where a new binding instance was being created for local class bindings instead of just inheriting the parent one.
* Fix bug with paren printing in `compact` and `retainLines` mode where a left paren was already printed before catching up.
* **Internal**
* Handle contexts for paths much better. This will ensure that the path node location info is in sync.
## 5.4.2
* **Polish**
* `ignore` and `only` patterns are now **very** liberal. The pattern can now exist anywhere in the path.
## 5.4.1
* **Bug Fix**
* Add missing `slash` dependency. Thanks [@browncolyn](https://github.com/browncolyn)!
* **Polish**
* Clean up `shouldIgnore` algorithm to work how you'd expect rather than being a hacky piece of shit. It now crawls the entire path, checking each section of it against the input ignore/only patterns. This means that the pattern `foo` will ignore the paths `foo/bar.js`, `bar/foo` etc.
## 5.4.0
* **New Feature**
* Added [function bind syntax](https://github.com/zenparsing/es-function-bind) behind stage 0. Thanks [@RReverser](https://github.com/rreverser)!
* Added `env` option. Especially handy when using the `.babelrc`.
* **Bug Fix**
* Fix files not properly being ignored when `babel.transform` ignores them when using `$ babel`.
* Fix scope tracking registering loop head bindings to their `VariableDeclaration` instead of `VariableDeclarator`.
* **Polish**
* Normalise path separators for souce map paths when using `$ babel`.
* Rework `PathHoister` to ignore global references and to not deopt on reassignments to referenced bindings, instead it tries to hoist to the highest scope.
* Added missing exponential operator inlining. Thanks [@nkt](https://github.com/nkt)!
* Optimise `regenerator` transformer. Thanks [@benjamn](https://github.com/benjamn)!
## 5.3.3
* **Bug Fix**
* Fix `minification.deadCodeElimination` transformer incorrectly trying to inline import declarations.
* Fix `minification.inlineExpression` transformer getting into an infinite loop.
## 5.3.2
* **Bug Fix**
* Fix patterns not being considered when hoisting variables in the `es6.blockScoping` transformer.
## 5.3.1
* **Bug Fix**
* Fix unique export specifiers not being cloned when exploding class and function exports,
* **Polish**
* Turn import remaps to sequence expressions to remove their context and improve performance.
## 5.3.0
**Speeeeeeed**
![gifs lol](https://31.media.tumblr.com/568205a0e37ae15eca510fa639589a59/tumblr_n8kw8kpcSb1sg6cg8o1_500.gif)
* **Spec Compliancy**
* Allow trailing param commas for methods when using the `es7.trailingCommas` transformer.
* **Bug Fix**
* Fix `es6.blockScoping` transformer not properly ignoring `break` in `SwitchCase`.
* Fix lookahead context saving to avoid weird tokenizer state.
* Explode duplicate identifiers in export/import specifiers and property shorthand to create unique objects.
* Skip loose mode for class methods when they have decorators.
* When removing nodes, share their comments with their siblings.
* Properly hoist temp param declarations when doing TCO.
* **Internal**
* Add `--harmony_generators` flag to `$ babel-node`.
* Internal AST traversals have been minimised **drastically**. Transformers have been grouped together which means entire tree traversals are much fewer. Visiting nodes is now also skipped if the traversal context can detect that the handler is a noop. This sames precious cycles as it avoids constructing traversal paths and creating a new traversal context. See issues [#1472](https://github.com/babel/babel/issues/1472) and [#1486](https://github.com/babel/babel/issues/1486) for related discussion.
* **Polish**
* Move many `utility` transformers to `minification`.
## 5.2.17
* **Bug Fix**
* Fix auxiliary comments not properly being attached to function declaration helpers.
* Add `Super` node type to `ast-types` patch.
* Ignore parameter bindings when attempting to inline them in the `minification.deadCodeElimination` transformer.
* Correct `extensions` arguments when using the Babel CLI.
## 5.2.16
* **Bug Fix**
* Fix plugins being disabled when using the whitelist.
* Fix correct function scope being passed to `nameMethod.property` when inferring the function name for class methods.
* Fix incorrect extensions reference causing weird issues when using the Babel CLI.
* Fix destructuring param reference replacements not inheriting from their original param.
* **Spec Compliancy**
* Fix order that method decorators are ran in.
## 5.2.15
* **Bug Fix**
* Fix initializer descriptor add attempt if it doesn't exist.
## 5.2.14
* **Bug Fix**
* Fix bug with initializer decorators where the descriptors weren't being defined if there was no `initializer` property.
* **Internal**
* Expose `retainLines` option to CLI.
* Fix `retainLines` option not being taken into consideration when doing multiple variable declaration declarators generation.
* Expose minified and unminified copies of dist scripts.
## 5.2.13
* **Bug Fix**
* Fix `ExportDeclaration`s being incorrectly removed when using the `utility.deadCodeElimination` transformer.
* Fix position of `utility` transformers.
* **New Feature**
* Add built-in `esquery` support.
* **Internal**
* Consolidate notion of "virtual types".
## 5.2.12
* **Polish**
* Make UID generation based on module declarations **much** nicer.
* **Internal**
* Remove internal check for traversal path replacement of self. This is a pattern that **could** come up in the wild and it could lead to pretty nasty code and may lead to internal regressions as the test coverage isn't 100% :( Instead, just put it in the fast path.
## 5.2.11
* **Internal**
* Rename `getModuleName` option to `getModuleId`, doh.
## 5.2.10
* **Bug Fix**
* Fix numerous issues in `replaceWithSourceString`. Thanks [@pangratz](https://github.com/pangratz)!
* **New Feature**
* Add `getModuleName` option. Thanks [@jayphelps](https://github.com/jayphelps)!
## 5.2.9
* **Bug Fix**
* Fix `_blockHoist` transformer incorrectly sorting nodes on shitty environments that aren't spec compliant in their key order.
* Fix broken `parse` API method reference to an undeclared import.
## 5.2.7
* **Bug Fix**
* Move `utility.deadCodeElimination` transformer up to avoid race conditions.
* Fix shorthand property scope binding renaming.
* **Polish**
* Turn helper variable declarations into function declarations if possible.
* **Internal**
* Removed native inheritance support from classes.
* Added `replaceWithSourceString` path API.
* Split up `es3.propertyLiterals` and `es3.memberExpressionLiterals` transformers to `minfication.propertyLiterals` and `es3.memberExpressionLiterals`.
## 5.2.6
* **Internal**
* Fix transformer aliases being accidently set as deprecated ones.
* Expose `Pipeline` as `TransformerPipeline` instead.
## 5.2.5
* **Bug Fix**
* Fix `parse` API not adding all the correct pipeline transformers.
## 5.2.4
* **Bug Fix**
* Fix race condition with the Node API being loaded awkwardly and not being able to initialise itself when used in the browser.
* **Internal**
* Expose `transform.pipeline`.
## 5.2.3
* **Bug Fix**
* Fix plugin containers being called with an undefined import. Thanks [@timbur](https://github.com/timbur)!
* Allow Flow object separators to be commas. Thanks [@monsanto](https://github.com/monsanto)!
* Add missing `Statement` and `Declaration` node aliases to flow types.
## 5.2.2
* **Internal**
* Allow `util.arrayify` to take arbitrary types and coerce it into an array.
## 5.2.1
* **Bug Fix**
* Fix regression in `node/register` that caused `node_modules` to not be ignored.
## 5.2.0
* **Bug Fix**
* Fix plugin strings splitting arbitrarily on `:` which caused full paths on Windows to fail as they include `:` after the drive letter.
* Call class property `initializer`s with their target instead of their descriptor.
* Fix `ignore` and `only` not properly working on Windows path separators. Thanks [@stagas](https://github.com/stagas)!
* Fix `resolveRc` running on files twice causing issues. Thanks [@lukescott](https://github.com/lukescott)!
* Fix shorthand properties not correctly being target for `isReferenced` checks. Thanks [@monsanto](https://github.com/monsanto)!
* **Polish**
* Allow passing an array of globs to `babel/register` `only` and `ignore` options. Thanks [@Mark-Simulacrum](https://github.com/Mark-Simulacrum)!
* When inferring function names that collide with upper bindings, instead of doing the wrapper, instead rename them.
* Consider constant-like variable declaration functions to always refer to themselves so TOC can be performed.
* Process globs manually when using `$ babel` as some shells such as Windows don't explode them. Thanks [@jden](https://github.com/jden)!
* Add alternative way to execute plugins via a closure that's called with the current Babel instance.
* **Internal**
* Remove multiple internal transformers in favor of directly doing things when we need to. Previously, declarations such as `_ref` that we needed to create in specific scopes were done at the very end via the `_declarations` transformer. Now, they're done and added to the scope **right** when they're needed. This gets rid of the crappy `_declarations` property on scope nodes and fixes the crappy regenerator bug where it was creating a new `BlockStatement` so the declarations were being lost.
* Rework transformer traversal optimisation. Turns out that calling a `check` function for **every single node** in the AST is ridiculously expensive. 300,000 nodes timesed by ~30 transformers meant that it took tens of seconds to perform while it's quicker to just do the unnecessary traversal. Seems obvious in hindsight.
* **New Feature**
* Add `jscript` transformer that turns named function expressions into function declarations to get around [JScript's horribly broken function expression semantics](https://kangax.github.io/nfe/#jscript-bugs). Thanks [@kondi](https://github.com/kondi)!
* Add `@@hasInstance` support to objects when using the `es6.spec.symbols` transformer.
* Add `retainLines` option that retains the line (but not the columns!) of the input code.
## 5.1.13
* **Polish**
* Remove symbol check from `defineProperty` helper.
## 5.1.12
* **Bug Fix**
* Fix `resolveModuleSource` not being ran on `ExportAllDeclaration`s.
* Fix `.babelrc` being resolved multiple times when using the require hook.
* Fix parse error on spread properties in assignment position.
* Fix `externalHelpers` option being incorrectly listed as type `string`.
* **Internal**
* Upgrade `core-js` to `0.9.0`.
* **Spec Compliancy**
* Fix object decorators not using the `initializer` pattern.
* Remove property initializer descriptor reflection.
## 5.1.11
* **Bug Fix**
* Memoise and bind member expression decorators.
* Move JSX children cleaning to opening element visitor. Fixes elements not being cleaned in certain scenarios.
* Consider `SwitchStatement`s to be `Scopable`.
* Fix `bluebirdCoroutines` calling `interopRequireWildcard` before it's defined.
* Add space to `do...while` code generation.
* Validate `super` use before `this` on `super` exit rather than entrance.
* **Polish**
* Add Babel name to logger.
## 5.1.10
* **Bug Fix**
* Remove `makePredicate` from acorn in favor of an `indexOf`.
* Remove statements to expression explosion when inserting a block statement.
* **Internal**
* Remove runtime compatibility check.
## 5.1.9
* **Bug Fix**
* Fix class property initializers with `undefined` values not being correctly writable.
* Fix self inferring generators incorrectly causing a stack error.
* Fix default export specifiers not triggering AMD `module` argument inclusion.
* Fix assignments not having their module references properly remapped.
* **Internal**
* Upgrade to latest `acorn`.
* **Polish**
* Make invalid LHS pattern error messages nicer.
## 5.1.8
* **Bug Fix**
* Only make parenthesized object pattern LHS illegal.
## 5.1.7
* **Internal**
* Add `parse` node API.
## 5.1.6
* **Bug Fix**
* Fix `runtime` built-in catchall not properly checking for local variables.
## 5.1.5
* **Internal**
* Bump `core-js` version.
## 5.1.4
* **Polish**
* Add missing `Reflect` methods to runtime transformer.
## 5.1.3
* **Internal**
* Switch entirely to vanilla regenerator.
* Clean up and make the parsing of decorators stateless.
* **Bug Fix**
* Don't do TCO on generators and async functions.
* Add missing `core-js` runtime definitions.
## 5.1.2
* **Bug Fix**
* Add `getIterator` and `isIterable` to `babel-runtime` build script.
## 5.1.1
* **Bug Fix**
* Add missing runtime symbol definitions.
## 5.1.0
* **Bug Fix**
* Fix super reference when using decorators.
* Don't do array unpack optimisation when member expressions are present.
* Add missing descriptors for undecorated class properties.
* Don't consider `arguments` and `eval` valid function names when doing function name inferrence.
* Fix scope tracking of constants in loop heads.
* Parse `AwaitExpression` as a unary instead of an assignment.
* Fix regex evaluation when attempting static evaluation.
* Don't emit tokens when doing a lookahead.
* Add missing `test` declaration to `utility.deadCodeElimination` transformer.
* **Internal**
* Upgrade `regenerator` to the latest and use my branch with the hope of eventually switching to vanilla regenerator.
* Add support for the replacement of for loop `init`s with statements.
* Upgrade dependencies.
* **Polish**
* When adding the scope IIFE when using default parameters, don't shadow the function expression, just `apply` `this` and `arguments` if necessary.
* Use path basename as non-default import fallback.
* **New Feature**
* Add [trailing function comma proposal](https://github.com/jeffmo/es-trailing-function-commas). Thanks [@AluisioASG](https://github.com/AluisioASG)!
* Add support for object literal decorators.
* Make core-js modular when using the `runtime` transformer.
## 5.0.12
* **Bug Fix**
* Fix incorrect remapping of module references inside of a function id redirection container.
## 5.0.11
* **Bug Fix**
* Fix new `for...of` loops not properly inheriting their original loop.
* **Internal**
* Disable scope instance cache.
* **Polish**
* Allow comments in `.babelrc` JSON.
## 5.0.9
* **Polish**
* Use `moduleId` for UMD global name if available.
* **Bug Fix**
* Fix UMD global `module` variable shadowing the `amd`/`common` `module` variable.
* Fix Flow param type annotation regression.
* Fix function name collision `toString` wrapper. Thanks [@alawatthe](https://github.com/alawatthe)!
## 5.0.8
* **Bug Fix**
* Fix falsy static class properties not being writable.
* Fix block scoping collisions not properly detecting modules and function clashes.
* Skip `this` before `super` for derived constructors on functions.
## 5.0.7
* **New Feature**
* Add `--ignore` and `--only` support to the CLI.
* **Bug Fix**
* Remove `HOMEPATH` environment variable from home resolution in `babel/register` cache.
* **Internal**
* Disable WIP path resolution introducing infinite recursion in some code examples.
* **Polish**
* Add live binding to CommonJS default imports.
## 5.0.6
* **Bug Fix**
* Fix mangling of import references that collide with properties on `Object.prototype`.
* Fix duplicate declarations incorrectly being reported for `var`.
## 5.0.5
* **Internal**
* Upgrade `core-js`.
* **Bug Fix**
* Fix arrays not being supported in `util.list`.
## 5.0.4
* **Polish**
* Check for top level `breakConfig` in `resolveRc`.
## 5.0.3
* **Bug Fix**
* Make relative location absolute before calling `resolveRc`.
* **Internal**
* Switch to global UID registry.
* Add `breakConfig` option to prevent Babel from erroring when hitting that option.
## 5.0.1
* **Bug Fix**
* Fix duplicate declaration regression.
* Fix not being able to call non-writable methods.
## 5.0.0
* **New Feature**
* Decorators based on [@wycat's](https://github.com/wycats) [stage 1 proposal](https://github.com/wycats/javascript-decorators).
* Class property initializers based on [@jeffmo's](https://github.com/jeffmo) [stage 0 proposal](https://gist.github.com/jeffmo/054df782c05639da2adb).
* Export extensions based on [@leebyron's](https://github.com/leebyron) [stage 1 proposal](https://github.com/leebyron/ecmascript-more-export-from).
* UMD module formatter now supports globals.
* Add `es3.runtime`, `optimisation.react.inlineElements` and `optimisation.react.constantElements` transformers.
* Add stage option that replaces the experimental one.
* Allow ES7 transformer to be enabled via `optional` instead of only via `stage`.
* Infer string quotes to use in the code generator.
* Consider `export { foo as default };` to be the same as `export default foo;`.
* Add `nonStandard` option that can be set to `false` to remove parser support for JSX and Flow.
* Add `jsxPragma` option.
* Automatically generate CLI options based on internal API options.
* Add support for `.babelrc` on absolute paths.
* Plugin API!
* **Internal**
* Export `options` in browser API.
* Rewritten parser.
* Don't block hoist when runtime transformer is enabled in system module formatter.
* Rewritten the internal traversal and node replacement API to use "paths" that abstracts out node relationships.
* **Polish**
* JSX output is now more inline with the official JSX transformer.
* Hoist block scoping IIFE - this improves memory usage and performance.
* Better IIFE detection - references are now checked to see if they're referencing the binding we're searching for.
* Check for import reassignments in constants transformer.
* Make method definitions with expression bodies illegal.
* Save register cache on tick instead of `SIGINT`.
* Enable strict mode on babel-node eval flag.
* **Bug Fixes**
* Add support for live bindings. This change also increases the reliablity of export specifier renaming.
* Add support for super update and non equals assignment expressions.
* Rename shadow constructor binding in classes.
* Seed next iteration bindings with previous fresh bindings when reassinging loop block scoped variables.
* Fix new expression spread referencing the wrong constructor.
* Call `resolveModuleSource` on dynamic imports.
* Added `param` to list of duplicate declaration kinds.
* **Breaking Changes**
* The Babel playground has been removed.
* ES7 Abstract References have been removed.
* Experimental option has been removed in favor of a stage option.
* Rename `returnUsedHelpers` to `metadataUsedHelpers`.

4016
.github/CHANGELOG-v6.md vendored Normal file

File diff suppressed because it is too large Load Diff

34
.gitignore vendored
View File

@@ -1,6 +1,9 @@
.DS_Store
/node_modules
/packages/*/node_modules
/packages/*/LICENSE
!/packages/babel-parser/LICENSE
!/packages/babel-plugin-transform-object-assign/LICENSE
*.log
*.cache
/build
@@ -12,24 +15,27 @@ coverage
dist
/.package.json
package-lock.json
/packages/babel-runtime/core-js/**/*.js
!/packages/babel-runtime/core-js/map.js
/packages/babel-runtime/helpers/*.js
!/packages/babel-runtime/helpers/toArray.js
!/packages/babel-runtime/helpers/iterableToArray.js
!/packages/babel-runtime/helpers/temporalRef.js
/packages/babel-runtime/helpers/builtin/*.js
!/packages/babel-runtime/helpers/builtin/toArray.js
!/packages/babel-runtime/helpers/builtin/iterableToArray.js
!/packages/babel-runtime/helpers/builtin/temporalRef.js
/packages/babel-runtime/helpers/builtin/es6/*.js
!/packages/babel-runtime/helpers/builtin/es6/toArray.js
!/packages/babel-runtime/helpers/builtin/es6/iterableToArray.js
!/packages/babel-runtime/helpers/builtin/es6/temporalRef.js
/packages/babel-runtime/helpers/es6/*.js
!/packages/babel-runtime/helpers/es6/toArray.js
!/packages/babel-runtime/helpers/es6/iterableToArray.js
!/packages/babel-runtime/helpers/es6/temporalRef.js
/packages/babel-runtime/helpers/esm/*.js
!/packages/babel-runtime/helpers/esm/toArray.js
!/packages/babel-runtime/helpers/esm/iterableToArray.js
!/packages/babel-runtime/helpers/esm/temporalRef.js
/packages/babel-runtime-corejs2/helpers/*.js
!/packages/babel-runtime-corejs2/helpers/toArray.js
!/packages/babel-runtime-corejs2/helpers/iterableToArray.js
!/packages/babel-runtime-corejs2/helpers/temporalRef.js
/packages/babel-runtime-corejs2/helpers/esm/*.js
!/packages/babel-runtime-corejs2/helpers/esm/toArray.js
!/packages/babel-runtime-corejs2/helpers/esm/iterableToArray.js
!/packages/babel-runtime-corejs2/helpers/esm/temporalRef.js
/packages/babel-runtime-corejs2/core-js/**/*.js
!/packages/babel-runtime-corejs2/core-js/map.js
/packages/babel-register/test/.babel
/packages/babel-cli/test/tmp
/packages/babel-node/test/tmp

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,7 @@
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and

View File

@@ -186,7 +186,7 @@ For example, in [`@babel/plugin-transform-exponentiation-operator/test`](https:/
- If you need to expect an error, you can ignore creating the `output.js` file and pass a new `throws` key to the `options.json` that contains the error string that is created.
- The second and preferred type is a test that actually evaluates the produced code and asserts that certain properties are true or false. We do this by creating an [`exec.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/comprehensive/exec.js) file.
In a fixture test, you simply write out the code you want transformed in `input.js`.
In a fixture test, you simply write out the code you want to transform in `input.js`.
```js
// input.js
@@ -230,7 +230,7 @@ If the test requires a minimum Node version, you can add `minNodeVersion` (must
Writing tests for the babel parser is very
similar to the other packages.
Inside the `packages/babel-parser/tests/fixtures` folder are categories/groupings of test fixtures (es2015, flow,
Inside the `packages/babel-parser/test/fixtures` folder are categories/groupings of test fixtures (es2015, flow,
etc.). To add a test, create a folder under one of these groupings (or create a new one) with a
descriptive name, and add the following:

View File

@@ -1,5 +1,5 @@
MAKEFLAGS = -j1
FLOW_COMMIT = 395e045c18d537fcbbc552a96ef2cdcd70b4ab52
FLOW_COMMIT = bea8b83f50f597454941d2a7ecef6e93a881e576
TEST262_COMMIT = f90a52b39609a620c0854e0bd0b3a906c930fd17
# Fix color output until TravisCI fixes https://github.com/travis-ci/travis-ci/issues/7967
@@ -31,7 +31,7 @@ build-preset-env-standalone:
build-dist: build
cd packages/babel-polyfill; \
scripts/build-dist.sh
cd packages/babel-runtime; \
cd packages/babel-plugin-transform-runtime; \
node scripts/build-dist.js
watch: clean clean-lib
@@ -104,23 +104,33 @@ test-test262-ci: bootstrap test-test262
test-test262-update-whitelist:
node scripts/tests/test262/run_babel_parser_test262.js --update-whitelist
publish:
git pull --rebase
clone-license:
./scripts/clone-license.sh
prepublish-build:
make clean-lib
rm -rf packages/babel-runtime/helpers
rm -rf packages/babel-runtime/core-js
rm -rf packages/babel-runtime-corejs2/helpers
rm -rf packages/babel-runtime-corejs2/core-js
BABEL_ENV=production make build-dist
make clone-license
prepublish:
git pull --rebase
make prepublish-build
make test
publish: prepublish
# not using lerna independent mode atm, so only update packages that have changed since we use ^
# --only-explicit-updates
./node_modules/.bin/lerna publish --force-publish=* --exact --skip-temp-tag
./node_modules/.bin/lerna publish --force-publish=* --temp-tag
make clean
bootstrap: clean-all
yarn --ignore-engines
./node_modules/.bin/lerna bootstrap -- --ignore-engines
make build
cd packages/babel-runtime; \
cd packages/babel-plugin-transform-runtime; \
node scripts/build-dist.js
clean-lib:

View File

@@ -72,6 +72,7 @@ Become a sponsor and get your logo on our README on Github with a link to your s
<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>
<a href="https://issue.sh/?utm_medium=github&utm_campaign=babel" target="_blank"><img src="https://user-images.githubusercontent.com/5557143/43912065-c8cdff78-9c33-11e8-829a-0b4166ccc215.png"></a>
<p><a href="https://twitter.com/mikesherov">Mike Sherov</a></p>
## Intro
@@ -107,7 +108,7 @@ For questions and support please visit join our [Slack Community](https://slack.
### 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!
I'm so glad you asked: [Hallelujah —— In Praise of Babel](SONG.md) by [@angus-c](https://github.com/angus-c), [audio version](https://youtu.be/40abpedBKK8) by [@swyx](https://twitter.com/@swyx). Tweet us your recordings!
### Where are the docs?

View File

@@ -1,5 +1,7 @@
## Hallelujah—In Praise of Babel
➤ [🎶 Audio version here!](https://youtu.be/40abpedBKK8)
I heard there was a clever trick
That rewrote all your JavaScript
But you dont really care for magic, do you

View File

@@ -13,13 +13,18 @@ module.exports = function(api) {
let convertESM = true;
let ignoreLib = true;
let includeRuntime = false;
switch (env) {
// Configs used during bundling builds.
case "babel-parser":
convertESM = false;
ignoreLib = false;
break;
case "standalone":
convertESM = false;
ignoreLib = false;
includeRuntime = true;
break;
case "production":
// Config during builds before publish.
@@ -41,6 +46,10 @@ module.exports = function(api) {
}
const config = {
// Our dependencies are all standard CommonJS, along with all sorts of
// other random files in Babel's codebase, so we use script as the default,
// and then mark actual modules as modules farther down.
sourceType: "script",
comments: false,
ignore: [
// These may not be strictly necessary with the newly-limited scope of
@@ -84,7 +93,29 @@ module.exports = function(api) {
convertESM ? "@babel/transform-modules-commonjs" : null,
].filter(Boolean),
},
],
{
// The vast majority of our src files are modules, but we use
// unambiguous to keep things simple until we get around to renaming
// the modules to be more easily distinguished from CommonJS
test: [
"packages/*/src",
"packages/*/test",
"codemods/*/src",
"codemods/*/test",
],
sourceType: "unambiguous",
},
{
// The runtime transform shouldn't process its own runtime or core-js.
exclude: [
"packages/babel-runtime",
/[\\/]node_modules[\\/](?:@babel\/runtime|babel-runtime|core-js)[\\/]/,
],
plugins: [includeRuntime ? "@babel/transform-runtime" : null].filter(
Boolean
),
},
].filter(Boolean),
};
// we need to do this as long as we do not test everything from source

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-codemod-object-assign-to-object-spread",
"version": "7.0.0-beta.52",
"version": "7.0.0",
"description": "Transforms Object.assign into object spread syntax",
"repository": "https://github.com/babel/babel/tree/master/codemods/babel-plugin-codemod-object-assign-to-object-spread",
"license": "MIT",
@@ -10,14 +10,14 @@
"@babel/plugin"
],
"dependencies": {
"@babel/plugin-syntax-object-rest-spread": "7.0.0-beta.52"
"@babel/plugin-syntax-object-rest-spread": "^7.0.0"
},
"peerDependencies": {
"@babel/core": ">=7.0.0-beta.50 <7.0.0-rc.0"
"@babel/core": "^7.0.0-0"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.52",
"@babel/helper-plugin-test-runner": "7.0.0-beta.52"
"@babel/core": "^7.0.0",
"@babel/helper-plugin-test-runner": "^7.0.0"
},
"publishConfig": {
"access": "public"

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-codemod-optional-catch-binding",
"version": "7.0.0-beta.52",
"version": "7.0.0",
"description": "Remove unused catch bindings",
"repository": "https://github.com/babel/babel/tree/master/codemods/babel-plugin-codemod-remove-unused-catch-binding",
"license": "MIT",
@@ -10,13 +10,13 @@
"@babel/plugin"
],
"dependencies": {
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.52"
"@babel/plugin-syntax-optional-catch-binding": "^7.0.0"
},
"peerDependencies": {
"@babel/core": ">=7.0.0-beta.50 <7.0.0-rc.0"
"@babel/core": "^7.0.0-0"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.52",
"@babel/helper-plugin-test-runner": "7.0.0-beta.52"
"@babel/core": "^7.0.0",
"@babel/helper-plugin-test-runner": "^7.0.0"
}
}

View File

@@ -1,6 +1,6 @@
{
"lerna": "2.11.0",
"version": "7.0.0-beta.52",
"version": "7.0.0",
"changelog": {
"repo": "babel/babel",
"cacheDir": ".changelog",

View File

@@ -32,6 +32,20 @@ declare module "lodash/merge" {
declare export default <T: Object>(T, Object) => T;
}
declare module "semver" {
declare module.exports: {
valid(v: string): boolean;
gt(v1: string, v2: string): boolean;
lt(v1: string, v2: string): boolean;
major(v: string): number;
minor(v: string): number;
patch(v: string): number;
satisfies(v1: string, r1: string): boolean;
intersects(r1: string, r2: string): boolean;
}
}
declare module "source-map" {
declare export type SourceMap = {
version: 3,

View File

@@ -10,29 +10,33 @@
"test": "make test"
},
"devDependencies": {
"@babel/cli": "7.0.0-beta.51",
"@babel/core": "7.0.0-beta.51",
"@babel/plugin-transform-modules-commonjs": "7.0.0-beta.51",
"@babel/preset-env": "7.0.0-beta.51",
"@babel/preset-flow": "7.0.0-beta.51",
"@babel/preset-stage-0": "7.0.0-beta.51",
"@babel/register": "7.0.0-beta.51",
"@babel/cli": "7.0.0-rc.2",
"@babel/core": "7.0.0-rc.2",
"@babel/plugin-transform-runtime": "7.0.0-rc.2",
"@babel/plugin-proposal-class-properties": "7.0.0-rc.2",
"@babel/plugin-proposal-export-namespace-from": "7.0.0-rc.2",
"@babel/plugin-proposal-numeric-separator": "7.0.0-rc.2",
"@babel/plugin-transform-modules-commonjs": "7.0.0-rc.2",
"@babel/preset-env": "7.0.0-rc.2",
"@babel/preset-flow": "7.0.0-rc.2",
"@babel/register": "7.0.0-rc.2",
"@babel/runtime": "7.0.0-rc.2",
"babel-core": "^7.0.0-0",
"babel-eslint": "^8.2.5",
"babel-jest": "^22.4.1",
"babel-loader": "8.0.0-beta.0",
"babel-eslint": "^8.2.6",
"babel-jest": "^23.4.0",
"babel-loader": "8.0.0-beta.4",
"babel-plugin-transform-charcodes": "^0.1.0",
"browserify": "^13.1.1",
"browserify": "^16.2.2",
"bundle-collapser": "^1.2.1",
"chalk": "^2.3.2",
"charcodes": "^0.1.0",
"derequire": "^2.0.2",
"enhanced-resolve": "^3.0.0",
"eslint": "^5.0.1",
"eslint": "^5.3.0",
"eslint-config-babel": "^7.0.2",
"eslint-plugin-flowtype": "^2.49.3",
"eslint-plugin-prettier": "^2.6.1",
"flow-bin": "^0.75.0",
"eslint-plugin-flowtype": "^2.50.0",
"eslint-plugin-prettier": "^2.6.2",
"flow-bin": "^0.79.0",
"graceful-fs": "^4.1.11",
"gulp": "^4.0.0",
"gulp-babel": "^8.0.0-beta.2",
@@ -44,14 +48,14 @@
"gulp-util": "^3.0.7",
"gulp-watch": "^5.0.0",
"husky": "^0.14.3",
"jest": "^22.4.2",
"jest": "^23.4.1",
"lerna": "^2.11.0",
"lerna-changelog": "^0.5.0",
"lint-staged": "^6.0.1",
"lodash": "^4.17.5",
"lodash": "^4.17.10",
"merge-stream": "^1.0.1",
"output-file-sync": "^2.0.0",
"prettier": "1.13.2",
"prettier": "^1.13.7",
"pump": "^1.0.2",
"rimraf": "^2.4.3",
"rollup-plugin-babel": "^4.0.0-beta.0",
@@ -68,7 +72,7 @@
},
"engines": {
"node": ">= 6.9.0 <= 11.0.0-0",
"npm": ">= 2.x <= 5.x",
"npm": ">= 3.x <= 6.x",
"yarn": ">=0.27.5 || >=1.0.0-20170811"
},
"lint-staged": {

View File

@@ -14,7 +14,7 @@ A monorepo, muhahahahahaha. See the [monorepo design doc](/doc/design/monorepo.m
| Package | Version | Dependencies |
|--------|-------|------------|
| [`@babel/core`](/packages/babel-core) | [![npm](https://img.shields.io/npm/v/@babel/core.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/core) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-core)](https://david-dm.org/babel/babel?path=packages/babel-core) |
| [`@babel/parser`](/packages/@babel/parser) | [![npm](https://img.shields.io/npm/v/@babel/parser.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/parser) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-parser)](https://david-dm.org/babel/babel?path=packages/babel-parser) |
| [`@babel/parser`](/packages/babel-parser) | [![npm](https://img.shields.io/npm/v/@babel/parser.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/parser) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-parser)](https://david-dm.org/babel/babel?path=packages/babel-parser) |
| [`@babel/traverse`](/packages/babel-traverse) | [![npm](https://img.shields.io/npm/v/@babel/traverse.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/traverse) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-traverse)](https://david-dm.org/babel/babel?path=packages/babel-traverse) |
| [`@babel/generator`](/packages/babel-generator) | [![npm](https://img.shields.io/npm/v/@babel/generator.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/generator) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-generator)](https://david-dm.org/babel/babel?path=packages/babel-generator) |

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/cli",
"version": "7.0.0-beta.52",
"version": "7.0.0",
"description": "Babel command line.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -18,23 +18,23 @@
"dependencies": {
"commander": "^2.8.1",
"convert-source-map": "^1.1.0",
"fs-readdir-recursive": "^1.0.0",
"fs-readdir-recursive": "^1.1.0",
"glob": "^7.0.0",
"lodash": "^4.17.5",
"lodash": "^4.17.10",
"mkdirp": "^0.5.1",
"output-file-sync": "^2.0.0",
"slash": "^1.0.0",
"slash": "^2.0.0",
"source-map": "^0.5.0"
},
"optionalDependencies": {
"chokidar": "^2.0.3"
},
"peerDependencies": {
"@babel/core": ">=7.0.0-beta.50 <7.0.0-rc.0"
"@babel/core": "^7.0.0-0"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.52",
"@babel/helper-fixtures": "7.0.0-beta.52"
"@babel/core": "^7.0.0",
"@babel/helper-fixtures": "^7.0.0"
},
"bin": {
"babel": "./bin/babel.js",

View File

@@ -89,7 +89,7 @@ export default async function({ cliOptions, babelOptions }) {
const stat = fs.statSync(filenameOrDir);
if (stat.isDirectory(filenameOrDir)) {
if (stat.isDirectory()) {
const dirname = filenameOrDir;
let count = 0;

View File

@@ -15,11 +15,15 @@ export function readdir(
includeDotfiles: boolean,
filter: ReaddirFilter,
) {
return readdirRecursive(
dirname,
filename =>
(includeDotfiles || filename[0] !== ".") && (!filter || filter(filename)),
);
return readdirRecursive(dirname, (filename, _index, currentDirectory) => {
const stat = fs.statSync(path.join(currentDirectory, filename));
if (stat.isDirectory()) return true;
return (
(includeDotfiles || filename[0] !== ".") && (!filter || filter(filename))
);
});
}
export function readdirForCompilable(
@@ -45,9 +49,14 @@ export function addSourceMappingUrl(code, loc) {
return code + "\n//# sourceMappingURL=" + path.basename(loc);
}
const CALLER = {
name: "@babel/cli",
};
export function transform(filename, code, opts) {
opts = {
...opts,
caller: CALLER,
filename,
};
@@ -60,6 +69,11 @@ export function transform(filename, code, opts) {
}
export function compile(filename, opts) {
opts = {
...opts,
caller: CALLER,
};
return new Promise((resolve, reject) => {
babel.transformFile(filename, opts, (err, result) => {
if (err) reject(err);

View File

@@ -1,3 +1 @@
class Test1 {
}
(() => 42)

View File

@@ -1,3 +1 @@
class Test2 {
}
(() => 42)

View File

@@ -1,9 +1,5 @@
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test1 = function Test1() {
_classCallCheck(this, Test1);
};
(function () {
return 42;
});

View File

@@ -1,9 +1,5 @@
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test2 = function Test2() {
_classCallCheck(this, Test2);
};
(function () {
return 42;
});

View File

@@ -1,10 +1,6 @@
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function Test() {
_classCallCheck(this, Test);
};
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXIvYmFyLmpzIl0sIm5hbWVzIjpbIlRlc3QiXSwibWFwcGluZ3MiOiI7Ozs7OztJQUFNQSxJIiwic291cmNlc0NvbnRlbnQiOlsiY2xhc3MgVGVzdCB7XG5cbn0iXX0=
(function () {
return 42;
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXIvYmFyLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsQ0FBQztBQUFBLFNBQU0sRUFBTjtBQUFBLENBQUQiLCJzb3VyY2VzQ29udGVudCI6WyIoKCkgPT4gNDIpIl19

View File

@@ -3,4 +3,4 @@
arr.map(function (x) {
return x * MULTIPLIER;
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9mb28uanMiXSwibmFtZXMiOlsiYXJyIiwibWFwIiwieCIsIk1VTFRJUExJRVIiXSwibWFwcGluZ3MiOiI7O0FBQUFBLElBQUlDLEdBQUosQ0FBUTtBQUFBLFNBQUtDLElBQUlDLFVBQVQ7QUFBQSxDQUFSIiwic291cmNlc0NvbnRlbnQiOlsiYXJyLm1hcCh4ID0+IHggKiBNVUxUSVBMSUVSKTsiXX0=
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9mb28uanMiXSwibmFtZXMiOlsiYXJyIiwibWFwIiwieCIsIk1VTFRJUExJRVIiXSwibWFwcGluZ3MiOiI7O0FBQUFBLEdBQUcsQ0FBQ0MsR0FBSixDQUFRLFVBQUFDLENBQUM7QUFBQSxTQUFJQSxDQUFDLEdBQUdDLFVBQVI7QUFBQSxDQUFUIiwic291cmNlc0NvbnRlbnQiOlsiYXJyLm1hcCh4ID0+IHggKiBNVUxUSVBMSUVSKTsiXX0=

View File

@@ -1,3 +1 @@
class Test {
}
(() => 42)

View File

@@ -1,10 +1,6 @@
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function Test() {
_classCallCheck(this, Test);
};
(function () {
return 42;
});
//# sourceMappingURL=bar.js.map

View File

@@ -1 +1 @@
{"version":3,"sources":["../../src/bar/bar.js"],"names":["Test"],"mappings":";;;;;;IAAMA,I","sourcesContent":["class Test {\n\n}"],"file":"bar.js"}
{"version":3,"sources":["../../src/bar/bar.js"],"names":[],"mappings":";;AAAA,CAAC;AAAA,SAAM,EAAN;AAAA,CAAD","sourcesContent":["(() => 42)"],"file":"bar.js"}

View File

@@ -1 +1 @@
{"version":3,"sources":["../src/foo.js"],"names":["arr","map","x","MULTIPLIER"],"mappings":";;AAAAA,IAAIC,GAAJ,CAAQ;AAAA,SAAKC,IAAIC,UAAT;AAAA,CAAR","sourcesContent":["arr.map(x => x * MULTIPLIER);"],"file":"foo.js"}
{"version":3,"sources":["../src/foo.js"],"names":["arr","map","x","MULTIPLIER"],"mappings":";;AAAAA,GAAG,CAACC,GAAJ,CAAQ,UAAAC,CAAC;AAAA,SAAIA,CAAC,GAAGC,UAAR;AAAA,CAAT","sourcesContent":["arr.map(x => x * MULTIPLIER);"],"file":"foo.js"}

View File

@@ -1,3 +1 @@
class Test {
}
(() => 42)

View File

@@ -1,9 +1,5 @@
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function Test() {
_classCallCheck(this, Test);
};
(function () {
return 42;
});

View File

@@ -1,3 +1 @@
class Test {
}
(() => 42)

View File

@@ -1,9 +1,5 @@
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function Test() {
_classCallCheck(this, Test);
};
(function () {
return 42;
});

View File

@@ -0,0 +1 @@
(() => 42)

View File

@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);

View File

@@ -0,0 +1,3 @@
{
"args": ["src", "--out-file", "test.js"]
}

View File

@@ -0,0 +1,10 @@
"use strict";
(function () {
return 42;
});
"use strict";
arr.map(function (x) {
return x * MULTIPLIER;
});

View File

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

View File

@@ -1,5 +1,3 @@
var foo = function () {
return 4;
};
arr.map(x => x * MULTIPLIER);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm9yaWdpbmFsLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLFVBQVUsWTtTQUFNLEM7Q0FBQyIsInNvdXJjZXNDb250ZW50IjpbInZhciBmb28gPSAoKSA9PiA0OyJdfQ==

View File

@@ -1,7 +1,7 @@
"use strict";
var foo = function foo() {
return 4;
};
arr.map(function (x) {
return x * MULTIPLIER;
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm9yaWdpbmFsLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBQSxNQUFVLFNBQVYsR0FBVSxHO1NBQU0sQztBQUFDLENBQWpCIiwiZmlsZSI6InNjcmlwdDIuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgZm9vID0gKCkgPT4gNDsiXX0=
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm9yaWdpbmFsLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsR0FBQSxDQUFBLEdBQUEsQ0FBQSxVQUFBLENBQUE7QUFBQSxTQUFVLENBQUEsR0FBQSxVQUFWO0FBQUEsQ0FBQSIsImZpbGUiOiJzY3JpcHQyLmpzIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGZvbyA9ICgpID0+IDQ7Il19

View File

@@ -1,16 +1,12 @@
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function Test() {
_classCallCheck(this, Test);
};
(function () {
return 42;
});
"use strict";
arr.map(function (x) {
return x * MULTIPLIER;
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNjcmlwdC5qcyIsInNjcmlwdDIuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7O0lBQU0sSTs7Ozs7QUNBTixJQUFJLEdBQUosQ0FBUTtBQUFBLFNBQUssSUFBSSxVQUFUO0FBQUEsQ0FBUiIsImZpbGUiOiJzY3JpcHQzLmpzIiwic291cmNlc0NvbnRlbnQiOlsiY2xhc3MgVGVzdCB7XG5cbn0iLCJhcnIubWFwKHggPT4geCAqIE1VTFRJUExJRVIpOyJdfQ==
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNjcmlwdC5qcyIsInNjcmlwdDIuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxDQUFDO0FBQUEsU0FBTSxFQUFOO0FBQUEsQ0FBRDs7O0FDQUEsR0FBRyxDQUFDLEdBQUosQ0FBUSxVQUFBLENBQUM7QUFBQSxTQUFJLENBQUMsR0FBRyxVQUFSO0FBQUEsQ0FBVCIsImZpbGUiOiJzY3JpcHQzLmpzIiwic291cmNlc0NvbnRlbnQiOlsiKCgpID0+IDQyKSIsImFyci5tYXAoeCA9PiB4ICogTVVMVElQTElFUik7Il19

View File

@@ -1,3 +1 @@
class Test {
}
(() => 42)

View File

@@ -1,12 +1,8 @@
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function Test() {
_classCallCheck(this, Test);
};
(function () {
return 42;
});
"use strict";
arr.map(function (x) {

View File

@@ -1 +1 @@
{"version":3,"sources":["script.js","script2.js"],"names":[],"mappings":";;;;;;IAAM,I;;;;;ACAN,IAAI,GAAJ,CAAQ;AAAA,SAAK,IAAI,UAAT;AAAA,CAAR","file":"script3.js","sourcesContent":["class Test {\n\n}","arr.map(x => x * MULTIPLIER);"]}
{"version":3,"sources":["script.js","script2.js"],"names":[],"mappings":";;AAAA,CAAC;AAAA,SAAM,EAAN;AAAA,CAAD;;;ACAA,GAAG,CAAC,GAAJ,CAAQ,UAAA,CAAC;AAAA,SAAI,CAAC,GAAG,UAAR;AAAA,CAAT","file":"script3.js","sourcesContent":["(() => 42)","arr.map(x => x * MULTIPLIER);"]}

View File

@@ -1,3 +1 @@
class Test {
}
(() => 42)

View File

@@ -1,12 +1,8 @@
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function Test() {
_classCallCheck(this, Test);
};
(function () {
return 42;
});
"use strict";
arr.map(function (x) {

View File

@@ -14,12 +14,10 @@ const fileFilter = function(x) {
return x !== ".DS_Store";
};
const presetLocs = [
path.join(__dirname, "../../babel-preset-es2015"),
path.join(__dirname, "../../babel-preset-react"),
].join(",");
const presetLocs = [path.join(__dirname, "../../babel-preset-react")];
const pluginLocs = [
path.join(__dirname, "/../../babel-plugin-transform-arrow-functions"),
path.join(__dirname, "/../../babel-plugin-transform-strict-mode"),
path.join(__dirname, "/../../babel-plugin-transform-modules-commonjs"),
].join(",");

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/code-frame",
"version": "7.0.0-beta.52",
"version": "7.0.0",
"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.52"
"@babel/highlight": "^7.0.0"
},
"devDependencies": {
"chalk": "^2.0.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/core",
"version": "7.0.0-beta.52",
"version": "7.0.0",
"description": "Babel compiler core.",
"main": "lib/index.js",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
@@ -30,24 +30,23 @@
"./lib/transform-file.js": "./lib/transform-file-browser.js"
},
"dependencies": {
"@babel/code-frame": "7.0.0-beta.52",
"@babel/generator": "7.0.0-beta.52",
"@babel/helpers": "7.0.0-beta.52",
"@babel/parser": "7.0.0-beta.52",
"@babel/template": "7.0.0-beta.52",
"@babel/traverse": "7.0.0-beta.52",
"@babel/types": "7.0.0-beta.52",
"@babel/code-frame": "^7.0.0",
"@babel/generator": "^7.0.0",
"@babel/helpers": "^7.0.0",
"@babel/parser": "^7.0.0",
"@babel/template": "^7.0.0",
"@babel/traverse": "^7.0.0",
"@babel/types": "^7.0.0",
"convert-source-map": "^1.1.0",
"debug": "^3.1.0",
"json5": "^0.5.0",
"lodash": "^4.17.5",
"micromatch": "^3.1.10",
"lodash": "^4.17.10",
"resolve": "^1.3.2",
"semver": "^5.4.1",
"source-map": "^0.5.0"
},
"devDependencies": {
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.52",
"@babel/register": "7.0.0-beta.52"
"@babel/helper-transform-fixture-test-runner": "^7.0.0",
"@babel/register": "^7.0.0"
}
}

View File

@@ -206,12 +206,29 @@ function makeSimpleConfigurator(
return;
}
return cache.using(val);
return cache.using(() => assertSimpleType(val()));
}
cacheFn.forever = () => cache.forever();
cacheFn.never = () => cache.never();
cacheFn.using = cb => cache.using(() => cb());
cacheFn.invalidate = cb => cache.invalidate(() => cb());
cacheFn.using = cb => cache.using(() => assertSimpleType(cb()));
cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb()));
return (cacheFn: any);
}
// Types are limited here so that in the future these values can be used
// as part of Babel's caching logic.
type SimpleType = string | boolean | number | null | void;
export function assertSimpleType(value: mixed): SimpleType {
if (
value != null &&
typeof value !== "string" &&
typeof value !== "boolean" &&
typeof value !== "number"
) {
throw new Error(
"Cache keys must be either string, boolean, number, null, or undefined.",
);
}
return value;
}

View File

@@ -1,7 +1,6 @@
// @flow
import path from "path";
import micromatch from "micromatch";
import buildDebug from "debug";
import {
validate,
@@ -9,7 +8,9 @@ import {
type IgnoreList,
type ConfigApplicableTest,
type BabelrcSearch,
type CallerMetadata,
} from "./validation/options";
import pathPatternToRegex from "./pattern-to-regex";
const debug = buildDebug("babel:config:config-chain");
@@ -50,17 +51,27 @@ export type ConfigContext = {
cwd: string,
root: string,
envName: string,
};
type ConfigContextNamed = {
...ConfigContext,
filename: string,
caller: CallerMetadata | void,
};
/**
* Build a config chain for a given preset.
*/
export const buildPresetChain: (
export function buildPresetChain(
arg: PresetInstance,
context: *,
): ConfigChain | null {
const chain = buildPresetChainWalker(arg, context);
if (!chain) return null;
return {
plugins: dedupDescriptors(chain.plugins),
presets: dedupDescriptors(chain.presets),
options: chain.options,
};
}
export const buildPresetChainWalker: (
arg: PresetInstance,
context: *,
) => * = makeChainWalker({
@@ -133,9 +144,14 @@ export function buildRootChain(
let configFile;
if (typeof opts.configFile === "string") {
configFile = loadConfig(opts.configFile, context.cwd, context.envName);
configFile = loadConfig(
opts.configFile,
context.cwd,
context.envName,
context.caller,
);
} else if (opts.configFile !== false) {
configFile = findRootConfig(context.root, context.envName);
configFile = findRootConfig(context.root, context.envName, context.caller);
}
let { babelrc, babelrcRoots } = opts;
@@ -217,7 +233,7 @@ function babelrcLoadEnabled(
const absoluteRoot = context.root;
// Fast path to avoid having to load micromatch if the babelrc is just
// Fast path to avoid having to match patterns if the babelrc is just
// loading in the standard root directory.
if (babelrcRoots === undefined) {
return pkgData.directories.indexOf(absoluteRoot) !== -1;
@@ -225,15 +241,23 @@ function babelrcLoadEnabled(
let babelrcPatterns = babelrcRoots;
if (!Array.isArray(babelrcPatterns)) babelrcPatterns = [babelrcPatterns];
babelrcPatterns = babelrcPatterns.map(pat => path.resolve(context.cwd, pat));
babelrcPatterns = babelrcPatterns.map(pat => {
return typeof pat === "string" ? path.resolve(context.cwd, pat) : pat;
});
// Fast path to avoid having to load micromatch if the babelrc is just
// Fast path to avoid having to match patterns 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;
return babelrcPatterns.some(pat => {
if (typeof pat === "string") pat = pathPatternToRegex(pat, context.cwd);
return pkgData.directories.some(directory => {
return matchPattern(pat, context.cwd, directory, context);
});
});
}
const validateConfigFile = makeWeakCache(
@@ -446,7 +470,12 @@ function mergeExtendsChain(
): boolean {
if (opts.extends === undefined) return true;
const file = loadConfig(opts.extends, dirname, context.envName);
const file = loadConfig(
opts.extends,
dirname,
context.envName,
context.caller,
);
if (files.has(file)) {
throw new Error(
@@ -500,11 +529,15 @@ function normalizeOptions(opts: ValidatedOptions): ValidatedOptions {
};
delete options.extends;
delete options.env;
delete options.overrides;
delete options.plugins;
delete options.presets;
delete options.passPerPreset;
delete options.ignore;
delete options.only;
delete options.test;
delete options.include;
delete options.exclude;
// "sourceMap" is just aliased to sourceMap, so copy it over as
// we merge the options together.
@@ -520,7 +553,7 @@ function dedupDescriptors(
): Array<UnloadedDescriptor> {
const map: Map<
Function,
Map<string | void, { value: UnloadedDescriptor | null }>,
Map<string | void, { value: UnloadedDescriptor }>,
> = new Map();
const descriptors = [];
@@ -535,16 +568,12 @@ function dedupDescriptors(
}
let desc = nameMap.get(item.name);
if (!desc) {
desc = { value: null };
desc = { value: item };
descriptors.push(desc);
// Treat passPerPreset presets as unique, skipping them
// in the merge processing steps.
if (!item.ownPass) nameMap.set(item.name, desc);
}
if (item.options === false) {
desc.value = null;
} else {
desc.value = item;
}
@@ -554,7 +583,7 @@ function dedupDescriptors(
}
return descriptors.reduce((acc, desc) => {
if (desc.value) acc.push(desc.value);
acc.push(desc.value);
return acc;
}, []);
}
@@ -579,20 +608,9 @@ function configFieldIsApplicable(
test: ConfigApplicableTest,
dirname: string,
): boolean {
if (typeof context.filename !== "string") {
throw new Error(
`Configuration contains explicit test/include/exclude checks, but no filename was passed to Babel`,
);
}
// $FlowIgnore - Flow refinements aren't quite smart enough for this :(
const ctx: ConfigContextNamed = context;
const patterns = Array.isArray(test) ? test : [test];
// Disabling negation here because it's a bit buggy from
// https://github.com/babel/babel/issues/6907 and it's not clear that it is
// needed since users can use 'exclude' alongside 'test'/'include'.
return matchesPatterns(ctx, patterns, dirname, false /* allowNegation */);
return matchesPatterns(context, patterns, dirname);
}
/**
@@ -604,43 +622,24 @@ function shouldIgnore(
only: ?IgnoreList,
dirname: string,
): boolean {
if (ignore) {
if (typeof context.filename !== "string") {
throw new Error(
`Configuration contains ignore checks, but no filename was passed to Babel`,
);
}
// $FlowIgnore - Flow refinements aren't quite smart enough for this :(
const ctx: ConfigContextNamed = context;
if (matchesPatterns(ctx, ignore, dirname)) {
debug(
"Ignored %o because it matched one of %O from %o",
context.filename,
ignore,
dirname,
);
return true;
}
if (ignore && matchesPatterns(context, ignore, dirname)) {
debug(
"Ignored %o because it matched one of %O from %o",
context.filename,
ignore,
dirname,
);
return true;
}
if (only) {
if (typeof context.filename !== "string") {
throw new Error(
`Configuration contains ignore checks, but no filename was passed to Babel`,
);
}
// $FlowIgnore - Flow refinements aren't quite smart enough for this :(
const ctx: ConfigContextNamed = context;
if (!matchesPatterns(ctx, only, dirname)) {
debug(
"Ignored %o because it failed to match one of %O from %o",
context.filename,
only,
dirname,
);
return true;
}
if (only && !matchesPatterns(context, only, dirname)) {
debug(
"Ignored %o because it failed to match one of %O from %o",
context.filename,
only,
dirname,
);
return true;
}
return false;
@@ -651,64 +650,37 @@ function shouldIgnore(
* Otherwise returns result of matching pattern Regex with filename.
*/
function matchesPatterns(
context: ConfigContextNamed,
context: ConfigContext,
patterns: IgnoreList,
dirname: string,
allowNegation?: boolean = true,
): boolean {
const res = [];
const strings = [];
const fns = [];
patterns.forEach(pattern => {
if (typeof pattern === "string") strings.push(pattern);
else if (typeof pattern === "function") fns.push(pattern);
else res.push(pattern);
});
const filename = context.filename;
if (res.some(re => re.test(context.filename))) return true;
if (fns.some(fn => fn(filename))) return true;
if (strings.length > 0) {
const possibleDirs = getPossibleDirs(context);
const absolutePatterns = strings.map(pattern => {
// Preserve the "!" prefix so that micromatch can use it for negation.
const negate = pattern[0] === "!";
if (negate && !allowNegation) {
throw new Error(`Negation of file paths is not supported.`);
}
if (negate) pattern = pattern.slice(1);
return (negate ? "!" : "") + path.resolve(dirname, pattern);
});
if (
micromatch(possibleDirs, absolutePatterns, {
nocase: true,
nonegate: !allowNegation,
}).length > 0
) {
return true;
}
}
return false;
return patterns.some(pattern =>
matchPattern(pattern, dirname, context.filename, context),
);
}
const getPossibleDirs = makeWeakCache((context: ConfigContextNamed) => {
let current = context.filename;
if (typeof current !== "string") return [];
const possibleDirs = [current];
while (true) {
const previous = current;
current = path.dirname(current);
if (previous === current) break;
possibleDirs.push(current);
function matchPattern(
pattern,
dirname,
pathToTest,
context: ConfigContext,
): boolean {
if (typeof pattern === "function") {
return !!pattern(pathToTest, {
dirname,
envName: context.envName,
caller: context.caller,
});
}
return possibleDirs;
});
if (typeof pathToTest !== "string") {
throw new Error(
`Configuration contains string/RegExp pattern, but no filename was passed to Babel`,
);
}
if (typeof pattern === "string") {
pattern = pathPatternToRegex(pattern, dirname);
}
return pattern.test(pathToTest);
}

View File

@@ -41,6 +41,22 @@ export type UnloadedDescriptor = {
} | void,
};
function isEqualDescriptor(
a: UnloadedDescriptor,
b: UnloadedDescriptor,
): boolean {
return (
a.name === b.name &&
a.value === b.value &&
a.options === b.options &&
a.dirname === b.dirname &&
a.alias === b.alias &&
a.ownPass === b.ownPass &&
(a.file && a.file.request) === (b.file && b.file.request) &&
(a.file && a.file.resolved) === (b.file && b.file.resolved)
);
}
export type ValidatedFile = {
filepath: string,
dirname: string,
@@ -50,7 +66,7 @@ export type ValidatedFile = {
/**
* Create a set of descriptors from a given options object, preserving
* descriptor identity based on the identity of the plugin/preset arrays
* themselves.
* themselves, and potentially on the identity of the plugins/presets + options.
*/
export function createCachedDescriptors(
dirname: string,
@@ -113,26 +129,82 @@ export function createUncachedDescriptors(
};
}
const PRESET_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPresetDescriptors = makeWeakCache(
(items: PluginList, cache: CacheConfigurator<string>) => {
const dirname = cache.using(dir => dir);
return makeStrongCache((alias: string) =>
makeStrongCache((passPerPreset: boolean) =>
createPresetDescriptors(items, dirname, alias, passPerPreset),
createPresetDescriptors(items, dirname, alias, passPerPreset).map(
// Items are cached using the overall preset array identity when
// possibly, but individual descriptors are also cached if a match
// can be found in the previously-used descriptor lists.
desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc),
),
),
);
},
);
const PLUGIN_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPluginDescriptors = makeWeakCache(
(items: PluginList, cache: CacheConfigurator<string>) => {
const dirname = cache.using(dir => dir);
return makeStrongCache((alias: string) =>
createPluginDescriptors(items, dirname, alias),
createPluginDescriptors(items, dirname, alias).map(
// Items are cached using the overall plugin array identity when
// possibly, but individual descriptors are also cached if a match
// can be found in the previously-used descriptor lists.
desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc),
),
);
},
);
/**
* When no options object is given in a descriptor, this object is used
* as a WeakMap key in order to have consistent identity.
*/
const DEFAULT_OPTIONS = {};
/**
* Given the cache and a descriptor, returns a matching descriptor from the
* cache, or else returns the input descriptor and adds it to the cache for
* next time.
*/
function loadCachedDescriptor(
cache: WeakMap<{} | Function, WeakMap<{}, Array<UnloadedDescriptor>>>,
desc: UnloadedDescriptor,
) {
const { value, options = DEFAULT_OPTIONS } = desc;
if (options === false) return desc;
let cacheByOptions = cache.get(value);
if (!cacheByOptions) {
cacheByOptions = new WeakMap();
cache.set(value, cacheByOptions);
}
let possibilities = cacheByOptions.get(options);
if (!possibilities) {
possibilities = [];
cacheByOptions.set(options, possibilities);
}
if (possibilities.indexOf(desc) === -1) {
const matches = possibilities.filter(possibility =>
isEqualDescriptor(possibility, desc),
);
if (matches.length > 0) {
return matches[0];
}
possibilities.push(desc);
}
return desc;
}
function createPresetDescriptors(
items: PluginList,
dirname: string,

View File

@@ -12,7 +12,9 @@ import {
} from "../caching";
import makeAPI from "../helpers/config-api";
import { makeStaticFileCache } from "./utils";
import pathPatternToRegex from "../pattern-to-regex";
import type { FilePackageData, RelativeConfig, ConfigFile } from "./types";
import type { CallerMetadata } from "../validation/options";
const debug = buildDebug("babel:config:loading:files:configuration");
@@ -25,6 +27,7 @@ const BABELIGNORE_FILENAME = ".babelignore";
export function findRelativeConfig(
packageData: FilePackageData,
envName: string,
caller: CallerMetadata | void,
): RelativeConfig {
let config = null;
let ignore = null;
@@ -36,7 +39,7 @@ export function findRelativeConfig(
config = [BABELRC_FILENAME, BABELRC_JS_FILENAME].reduce(
(previousConfig: ConfigFile | null, name) => {
const filepath = path.join(loc, name);
const config = readConfig(filepath, envName);
const config = readConfig(filepath, envName, caller);
if (config && previousConfig) {
throw new Error(
@@ -90,10 +93,11 @@ export function findRelativeConfig(
export function findRootConfig(
dirname: string,
envName: string,
caller: CallerMetadata | void,
): ConfigFile | null {
const filepath = path.resolve(dirname, BABEL_CONFIG_JS_FILENAME);
const conf = readConfig(filepath, envName);
const conf = readConfig(filepath, envName, caller);
if (conf) {
debug("Found root config %o in $o.", BABEL_CONFIG_JS_FILENAME, dirname);
}
@@ -104,10 +108,11 @@ export function loadConfig(
name: string,
dirname: string,
envName: string,
caller: CallerMetadata | void,
): ConfigFile {
const filepath = resolve.sync(name, { basedir: dirname });
const conf = readConfig(filepath, envName);
const conf = readConfig(filepath, envName, caller);
if (!conf) {
throw new Error(`Config file ${filepath} contains no configuration data`);
}
@@ -120,16 +125,22 @@ export function loadConfig(
* Read the given config file, returning the result. Returns null if no config was found, but will
* throw if there are parsing errors while loading a config.
*/
function readConfig(filepath, envName): ConfigFile | null {
function readConfig(filepath, envName, caller): ConfigFile | null {
return path.extname(filepath) === ".js"
? readConfigJS(filepath, { envName })
? readConfigJS(filepath, { envName, caller })
: readConfigJSON5(filepath);
}
const LOADING_CONFIGS = new Set();
const readConfigJS = makeStrongCache(
(filepath, cache: CacheConfigurator<{ envName: string }>) => {
(
filepath,
cache: CacheConfigurator<{
envName: string,
caller: CallerMetadata | void,
}>,
) => {
if (!fs.existsSync(filepath)) {
cache.forever();
return null;
@@ -240,15 +251,24 @@ const readConfigJSON5 = makeStaticFileCache((filepath, content) => {
});
const readIgnoreConfig = makeStaticFileCache((filepath, content) => {
const ignore = content
const ignoreDir = path.dirname(filepath);
const ignorePatterns = content
.split("\n")
.map(line => line.replace(/#(.*?)$/, "").trim())
.filter(line => !!line);
for (const pattern of ignorePatterns) {
if (pattern[0] === "!") {
throw new Error(`Negation of file paths is not supported.`);
}
}
return {
filepath,
dirname: path.dirname(filepath),
ignore,
ignore: ignorePatterns.map(pattern =>
pathPatternToRegex(pattern, ignoreDir),
),
};
});

View File

@@ -7,6 +7,8 @@ import type {
FilePackageData,
} from "./types";
import type { CallerMetadata } from "../validation/options";
export type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData };
export function findPackageData(filepath: string): FilePackageData {
@@ -21,6 +23,7 @@ export function findPackageData(filepath: string): FilePackageData {
export function findRelativeConfig(
pkgData: FilePackageData, // eslint-disable-line no-unused-vars
envName: string, // eslint-disable-line no-unused-vars
caller: CallerMetadata | void, // eslint-disable-line no-unused-vars
): RelativeConfig {
return { pkg: null, config: null, ignore: null };
}
@@ -28,6 +31,7 @@ export function findRelativeConfig(
export function findRootConfig(
dirname: string, // eslint-disable-line no-unused-vars
envName: string, // eslint-disable-line no-unused-vars
caller: CallerMetadata | void, // eslint-disable-line no-unused-vars
): ConfigFile | null {
return null;
}
@@ -36,6 +40,7 @@ export function loadConfig(
name: string,
dirname: string,
envName: string, // eslint-disable-line no-unused-vars
caller: CallerMetadata | void, // eslint-disable-line no-unused-vars
): ConfigFile {
throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);
}

View File

@@ -15,8 +15,8 @@ const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-plugin(?:-|\/|$)|[^/]+\/)/;
const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-preset(?:-|\/|$)|[^/]+\/)/;
const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/;
const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/;
const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
export function resolvePlugin(name: string, dirname: string): string | null {

View File

@@ -9,7 +9,7 @@ export type ConfigFile = {
export type IgnoreFile = {
filepath: string,
dirname: string,
ignore: Array<string>,
ignore: Array<RegExp>,
};
export type RelativeConfig = {

View File

@@ -13,7 +13,7 @@ import {
import type { UnloadedDescriptor } from "./config-descriptors";
import traverse from "@babel/traverse";
import { makeWeakCache, type CacheConfigurator } from "./caching";
import { validate } from "./validation/options";
import { validate, type CallerMetadata } from "./validation/options";
import { validatePluginObject } from "./validation/plugins";
import makeAPI from "./helpers/config-api";
@@ -41,6 +41,7 @@ export type PluginPasses = Array<PluginPassList>;
// process 'ignore'/'only' and other filename-based logic.
type SimpleContext = {
envName: string,
caller: CallerMetadata | void,
};
export default function loadFullConfig(
@@ -68,15 +69,21 @@ export default function loadFullConfig(
},
pass: Array<Plugin>,
) {
const plugins = config.plugins.map(descriptor => {
return loadPluginDescriptor(descriptor, context);
});
const presets = config.presets.map(descriptor => {
return {
preset: loadPresetDescriptor(descriptor, context),
pass: descriptor.ownPass ? [] : pass,
};
});
const plugins = config.plugins.reduce((acc, descriptor) => {
if (descriptor.options !== false) {
acc.push(loadPluginDescriptor(descriptor, context));
}
return acc;
}, []);
const presets = config.presets.reduce((acc, descriptor) => {
if (descriptor.options !== false) {
acc.push({
preset: loadPresetDescriptor(descriptor, context),
pass: descriptor.ownPass ? [] : pass,
});
}
return acc;
}, []);
// resolve presets
if (presets.length > 0) {

View File

@@ -2,7 +2,13 @@
import semver from "semver";
import { version as coreVersion } from "../../";
import type { CacheConfigurator, SimpleCacheConfigurator } from "../caching";
import {
assertSimpleType,
type CacheConfigurator,
type SimpleCacheConfigurator,
} from "../caching";
import type { CallerMetadata } from "../validation/options";
type EnvFunction = {
(): string,
@@ -20,12 +26,14 @@ export type PluginAPI = {
};
export default function makeAPI(
cache: CacheConfigurator<{ envName: string }>,
cache: CacheConfigurator<{ envName: string, caller: CallerMetadata | void }>,
): PluginAPI {
const env: any = value =>
cache.using(data => {
if (typeof value === "undefined") return data.envName;
if (typeof value === "function") return value(data.envName);
if (typeof value === "function") {
return assertSimpleType(value(data.envName));
}
if (!Array.isArray(value)) value = [value];
return value.some(entry => {
@@ -36,12 +44,16 @@ export default function makeAPI(
});
});
const caller: any = cb =>
cache.using(data => assertSimpleType(cb(data.caller)));
return {
version: coreVersion,
cache: cache.simple(),
// Expose ".env()" so people can easily get the same env that we expose using the "env" key.
env,
async: () => false,
caller,
assertVersion,
};
}

View File

@@ -71,9 +71,11 @@ class ConfigItem {
/**
* The options, if any, that were passed to the item.
* Mutating this will lead to undefined behavior. If you need
* Mutating this will lead to undefined behavior.
*
* "false" means that this item has been disabled.
*/
options: {} | void;
options: {} | void | false;
/**
* The directory that the options for this item are relative to.
@@ -103,10 +105,6 @@ class ConfigItem {
this._descriptor = descriptor;
Object.defineProperty(this, "_descriptor", ({ enumerable: false }: any));
if (this._descriptor.options === false) {
throw new Error("Assertion failure - unexpected false options");
}
this.value = this._descriptor.value;
this.options = this._descriptor.options;
this.dirname = this._descriptor.dirname;

View File

@@ -28,7 +28,7 @@ export default function loadPrivatePartialConfig(
const args = inputOpts ? validate("arguments", inputOpts) : {};
const { envName = getEnv(), cwd = ".", root: rootDir = "." } = args;
const { envName = getEnv(), cwd = ".", root: rootDir = ".", caller } = args;
const absoluteCwd = path.resolve(cwd);
const absoluteRootDir = path.resolve(absoluteCwd, rootDir);
@@ -40,6 +40,7 @@ export default function loadPrivatePartialConfig(
cwd: absoluteCwd,
root: absoluteRootDir,
envName,
caller,
};
const configChain = buildRootChain(args, context);

View File

@@ -0,0 +1,51 @@
// @flow
import path from "path";
import escapeRegExp from "lodash/escapeRegExp";
const sep = `\\${path.sep}`;
const endSep = `(?:${sep}|$)`;
const substitution = `[^${sep}]+`;
const starPat = `(?:${substitution}${sep})`;
const starPatLast = `(?:${substitution}${endSep})`;
const starStarPat = `${starPat}*?`;
const starStarPatLast = `${starPat}*?${starPatLast}?`;
/**
* Implement basic pattern matching that will allow users to do the simple
* tests with * and **. If users want full complex pattern matching, then can
* always use regex matching, or function validation.
*/
export default function pathToPattern(
pattern: string,
dirname: string,
): RegExp {
const parts = path.resolve(dirname, pattern).split(path.sep);
return new RegExp(
[
"^",
...parts.map((part, i) => {
const last = i === parts.length - 1;
// ** matches 0 or more path parts.
if (part === "**") return last ? starStarPatLast : starStarPat;
// * matches 1 path part.
if (part === "*") return last ? starPatLast : starPat;
// *.ext matches a wildcard with an extension.
if (part.indexOf("*.") === 0) {
return (
substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep)
);
}
// Otherwise match the pattern text.
return escapeRegExp(part) + (last ? endSep : sep);
}),
].join(""),
);
}

View File

@@ -13,16 +13,55 @@ import type {
SourceTypeOption,
CompactOption,
RootInputSourceMapOption,
NestingPath,
CallerMetadata,
} from "./options";
export type ValidatorSet = {
[string]: Validator<any>,
};
export type Validator<T> = (string, mixed) => T;
export type Validator<T> = (OptionPath, mixed) => T;
export function msg(loc: NestingPath | GeneralPath) {
switch (loc.type) {
case "root":
return ``;
case "env":
return `${msg(loc.parent)}.env["${loc.name}"]`;
case "overrides":
return `${msg(loc.parent)}.overrides[${loc.index}]`;
case "option":
return `${msg(loc.parent)}.${loc.name}`;
case "access":
return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`;
default:
throw new Error(`Assertion failure: Unknown type ${loc.type}`);
}
}
export function access(loc: GeneralPath, name: string | number): AccessPath {
return {
type: "access",
name,
parent: loc,
};
}
export type OptionPath = $ReadOnly<{
type: "option",
name: string,
parent: NestingPath,
}>;
type AccessPath = $ReadOnly<{
type: "access",
name: string | number,
parent: GeneralPath,
}>;
type GeneralPath = OptionPath | AccessPath;
export function assertSourceMaps(
key: string,
loc: OptionPath,
value: mixed,
): SourceMapsOption | void {
if (
@@ -32,21 +71,24 @@ export function assertSourceMaps(
value !== "both"
) {
throw new Error(
`.${key} must be a boolean, "inline", "both", or undefined`,
`${msg(loc)} must be a boolean, "inline", "both", or undefined`,
);
}
return value;
}
export function assertCompact(key: string, value: mixed): CompactOption | void {
export function assertCompact(
loc: OptionPath,
value: mixed,
): CompactOption | void {
if (value !== undefined && typeof value !== "boolean" && value !== "auto") {
throw new Error(`.${key} must be a boolean, "auto", or undefined`);
throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`);
}
return value;
}
export function assertSourceType(
key: string,
loc: OptionPath,
value: mixed,
): SourceTypeOption | void {
if (
@@ -56,14 +98,49 @@ export function assertSourceType(
value !== "unambiguous"
) {
throw new Error(
`.${key} must be "module", "script", "unambiguous", or undefined`,
`${msg(loc)} must be "module", "script", "unambiguous", or undefined`,
);
}
return value;
}
export function assertCallerMetadata(
loc: OptionPath,
value: mixed,
): CallerMetadata | void {
const obj = assertObject(loc, value);
if (obj) {
if (typeof obj[("name": string)] !== "string") {
throw new Error(
`${msg(loc)} set but does not contain "name" property string`,
);
}
for (const prop of Object.keys(obj)) {
const propLoc = access(loc, prop);
const value = obj[prop];
if (
value != null &&
typeof value !== "boolean" &&
typeof value !== "string" &&
typeof value !== "number"
) {
// NOTE(logan): I'm limiting the type here so that we can guarantee that
// the "caller" value will serialize to JSON nicely. We can always
// allow more complex structures later though.
throw new Error(
`${msg(
propLoc,
)} must be null, undefined, a boolean, a string, or a number.`,
);
}
}
}
return (value: any);
}
export function assertInputSourceMap(
key: string,
loc: OptionPath,
value: mixed,
): RootInputSourceMapOption | void {
if (
@@ -71,75 +148,82 @@ export function assertInputSourceMap(
typeof value !== "boolean" &&
(typeof value !== "object" || !value)
) {
throw new Error(".inputSourceMap must be a boolean, object, or undefined");
throw new Error(`${msg(loc)} must be a boolean, object, or undefined`);
}
return value;
}
export function assertString(key: string, value: mixed): string | void {
export function assertString(loc: GeneralPath, value: mixed): string | void {
if (value !== undefined && typeof value !== "string") {
throw new Error(`.${key} must be a string, or undefined`);
throw new Error(`${msg(loc)} must be a string, or undefined`);
}
return value;
}
export function assertFunction(key: string, value: mixed): Function | void {
export function assertFunction(
loc: GeneralPath,
value: mixed,
): Function | void {
if (value !== undefined && typeof value !== "function") {
throw new Error(`.${key} must be a function, or undefined`);
throw new Error(`${msg(loc)} must be a function, or undefined`);
}
return value;
}
export function assertBoolean(key: string, value: mixed): boolean | void {
export function assertBoolean(loc: GeneralPath, value: mixed): boolean | void {
if (value !== undefined && typeof value !== "boolean") {
throw new Error(`.${key} must be a boolean, or undefined`);
throw new Error(`${msg(loc)} must be a boolean, or undefined`);
}
return value;
}
export function assertObject(key: string, value: mixed): {} | void {
export function assertObject(loc: GeneralPath, value: mixed): {} | void {
if (
value !== undefined &&
(typeof value !== "object" || Array.isArray(value) || !value)
) {
throw new Error(`.${key} must be an object, or undefined`);
throw new Error(`${msg(loc)} must be an object, or undefined`);
}
return value;
}
export function assertArray(key: string, value: mixed): ?$ReadOnlyArray<mixed> {
export function assertArray(
loc: GeneralPath,
value: mixed,
): ?$ReadOnlyArray<mixed> {
if (value != null && !Array.isArray(value)) {
throw new Error(`.${key} must be an array, or undefined`);
throw new Error(`${msg(loc)} must be an array, or undefined`);
}
return value;
}
export function assertIgnoreList(key: string, value: mixed): IgnoreList | void {
const arr = assertArray(key, value);
export function assertIgnoreList(
loc: OptionPath,
value: mixed,
): IgnoreList | void {
const arr = assertArray(loc, value);
if (arr) {
arr.forEach((item, i) => assertIgnoreItem(key, i, item));
arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item));
}
return (arr: any);
}
function assertIgnoreItem(
key: string,
index: number,
value: mixed,
): IgnoreItem {
function assertIgnoreItem(loc: GeneralPath, value: mixed): IgnoreItem {
if (
typeof value !== "string" &&
typeof value !== "function" &&
!(value instanceof RegExp)
) {
throw new Error(
`.${key}[${index}] must be an array of string/Funtion/RegExp values, or undefined`,
`${msg(
loc,
)} must be an array of string/Funtion/RegExp values, or undefined`,
);
}
return value;
}
export function assertConfigApplicableTest(
key: string,
loc: OptionPath,
value: mixed,
): ConfigApplicableTest | void {
if (value === undefined) return value;
@@ -147,12 +231,14 @@ export function assertConfigApplicableTest(
if (Array.isArray(value)) {
value.forEach((item, i) => {
if (!checkValidTest(item)) {
throw new Error(`.${key}[${i}] must be a string/Function/RegExp.`);
throw new Error(
`${msg(access(loc, i))} must be a string/Function/RegExp.`,
);
}
});
} else if (!checkValidTest(value)) {
throw new Error(
`.${key} must be a string/Function/RegExp, or an array of those`,
`${msg(loc)} must be a string/Function/RegExp, or an array of those`,
);
}
return (value: any);
@@ -167,7 +253,7 @@ function checkValidTest(value: mixed): boolean {
}
export function assertConfigFileSearch(
key: string,
loc: OptionPath,
value: mixed,
): ConfigFileSearch | void {
if (
@@ -176,7 +262,7 @@ export function assertConfigFileSearch(
typeof value !== "string"
) {
throw new Error(
`.${key} must be a undefined, a boolean, a string, ` +
`${msg(loc)} must be a undefined, a boolean, a string, ` +
`got ${JSON.stringify(value)}`,
);
}
@@ -185,52 +271,51 @@ export function assertConfigFileSearch(
}
export function assertBabelrcSearch(
key: string,
loc: OptionPath,
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.`);
if (!checkValidTest(item)) {
throw new Error(
`${msg(access(loc, i))} must be a string/Function/RegExp.`,
);
}
});
} else if (typeof value !== "string") {
} else if (!checkValidTest(value)) {
throw new Error(
`.${key} must be a undefined, a boolean, a string, ` +
`or an array of strings, got ${JSON.stringify(value)}`,
`${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` +
`or an array of those, got ${JSON.stringify(value)}`,
);
}
return (value: any);
}
export function assertPluginList(key: string, value: mixed): PluginList | void {
const arr = assertArray(key, value);
export function assertPluginList(
loc: OptionPath,
value: mixed,
): PluginList | void {
const arr = assertArray(loc, value);
if (arr) {
// Loop instead of using `.map` in order to preserve object identity
// for plugin array for use during config chain processing.
arr.forEach((item, i) => assertPluginItem(key, i, item));
arr.forEach((item, i) => assertPluginItem(access(loc, i), item));
}
return (arr: any);
}
function assertPluginItem(
key: string,
index: number,
value: mixed,
): PluginItem {
function assertPluginItem(loc: GeneralPath, value: mixed): PluginItem {
if (Array.isArray(value)) {
if (value.length === 0) {
throw new Error(`.${key}[${index}] must include an object`);
throw new Error(`${msg(loc)} must include an object`);
}
if (value.length > 3) {
throw new Error(
`.${key}[${index}] may only be a two-tuple or three-tuple`,
);
throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`);
}
assertPluginTarget(key, index, true, value[0]);
assertPluginTarget(access(loc, 0), value[0]);
if (value.length > 1) {
const opts = value[1];
@@ -240,38 +325,31 @@ function assertPluginItem(
(typeof opts !== "object" || Array.isArray(opts))
) {
throw new Error(
`.${key}[${index}][1] must be an object, false, or undefined`,
`${msg(access(loc, 1))} must be an object, false, or undefined`,
);
}
}
if (value.length === 3) {
const name = value[2];
if (name !== undefined && typeof name !== "string") {
throw new Error(`.${key}[${index}][2] must be a string, or undefined`);
throw new Error(
`${msg(access(loc, 2))} must be a string, or undefined`,
);
}
}
} else {
assertPluginTarget(key, index, false, value);
assertPluginTarget(loc, value);
}
return (value: any);
}
function assertPluginTarget(
key: string,
index: number,
inArray: boolean,
value: mixed,
): PluginTarget {
function assertPluginTarget(loc: GeneralPath, value: mixed): PluginTarget {
if (
(typeof value !== "object" || !value) &&
typeof value !== "string" &&
typeof value !== "function"
) {
throw new Error(
`.${key}[${index}]${
inArray ? `[0]` : ""
} must be a string, object, function`,
);
throw new Error(`${msg(loc)} must be a string, object, function`);
}
return value;
}

View File

@@ -5,10 +5,13 @@ import Plugin from "../plugin";
import removed from "./removed";
import {
msg,
access,
assertString,
assertBoolean,
assertObject,
assertArray,
assertCallerMetadata,
assertInputSourceMap,
assertIgnoreList,
assertPluginList,
@@ -21,6 +24,7 @@ import {
assertSourceType,
type ValidatorSet,
type Validator,
type OptionPath,
} from "./option-assertions";
const ROOT_VALIDATORS: ValidatorSet = {
@@ -30,6 +34,9 @@ const ROOT_VALIDATORS: ValidatorSet = {
$PropertyType<ValidatedOptions, "configFile">,
>),
caller: (assertCallerMetadata: Validator<
$PropertyType<ValidatedOptions, "caller">,
>),
filename: (assertString: Validator<
$PropertyType<ValidatedOptions, "filename">,
>),
@@ -173,6 +180,7 @@ export type ValidatedOptions = {
ast?: boolean,
inputSourceMap?: RootInputSourceMapOption,
envName?: string,
caller?: CallerMetadata,
extends?: string,
env?: EnvSet<ValidatedOptions>,
@@ -222,6 +230,11 @@ export type ValidatedOptions = {
generatorOpts?: {},
};
export type CallerMetadata = {
// If 'caller' is specified, require that the name is given for debugging
// messages.
name: string,
};
export type EnvSet<T> = {
[string]: ?T,
};
@@ -242,30 +255,68 @@ 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 BabelrcSearch = boolean | IgnoreItem | IgnoreList;
export type SourceMapsOption = boolean | "inline" | "both";
export type SourceTypeOption = "module" | "script" | "unambiguous";
export type CompactOption = boolean | "auto";
export type RootInputSourceMapOption = {} | boolean;
export type OptionsType =
export type OptionsSource =
| "arguments"
| "env"
| "preset"
| "override"
| "configfile"
| "babelrcfile"
| "extendsfile";
| "extendsfile"
| "preset";
type RootPath = $ReadOnly<{
type: "root",
source: OptionsSource,
}>;
type OverridesPath = $ReadOnly<{
type: "overrides",
index: number,
parent: RootPath,
}>;
type EnvPath = $ReadOnly<{
type: "env",
name: string,
parent: RootPath | OverridesPath,
}>;
export type NestingPath = RootPath | OverridesPath | EnvPath;
function getSource(loc: NestingPath): OptionsSource {
return loc.type === "root" ? loc.source : getSource(loc.parent);
}
export function validate(type: OptionsSource, opts: {}): ValidatedOptions {
return validateNested(
{
type: "root",
source: type,
},
opts,
);
}
function validateNested(loc: NestingPath, opts: {}) {
const type = getSource(loc);
export function validate(type: OptionsType, opts: {}): ValidatedOptions {
assertNoDuplicateSourcemap(opts);
Object.keys(opts).forEach(key => {
const optLoc = {
type: "option",
name: key,
parent: loc,
};
if (type === "preset" && NONPRESET_VALIDATORS[key]) {
throw new Error(`.${key} is not allowed in preset options`);
throw new Error(`${msg(optLoc)} is not allowed in preset options`);
}
if (type !== "arguments" && ROOT_VALIDATORS[key]) {
throw new Error(`.${key} is only allowed in root programmatic options`);
throw new Error(
`${msg(optLoc)} is only allowed in root programmatic options`,
);
}
if (
type !== "arguments" &&
@@ -274,48 +325,47 @@ export function validate(type: OptionsType, opts: {}): ValidatedOptions {
) {
if (type === "babelrcfile" || type === "extendsfile") {
throw new Error(
`.${key} is not allowed in .babelrc or "extend"ed files, only in root programmatic options, ` +
`${msg(
optLoc,
)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` +
`or babel.config.js/config file options`,
);
}
throw new Error(
`.${key} is only allowed in root programmatic options, or babel.config.js/config file options`,
`${msg(
optLoc,
)} is only allowed in root programmatic options, or babel.config.js/config file options`,
);
}
if (type === "env" && key === "env") {
throw new Error(`.${key} is not allowed inside another env block`);
}
if (type === "env" && key === "overrides") {
throw new Error(`.${key} is not allowed inside an env block`);
}
if (type === "override" && key === "overrides") {
throw new Error(`.${key} is not allowed inside an overrides block`);
}
const validator =
COMMON_VALIDATORS[key] ||
NONPRESET_VALIDATORS[key] ||
BABELRC_VALIDATORS[key] ||
ROOT_VALIDATORS[key];
ROOT_VALIDATORS[key] ||
throwUnknownError;
if (validator) validator(key, opts[key]);
else throw buildUnknownError(key);
validator(optLoc, opts[key]);
});
return (opts: any);
}
function buildUnknownError(key: string) {
function throwUnknownError(loc: OptionPath) {
const key = loc.name;
if (removed[key]) {
const { message, version = 5 } = removed[key];
throw new ReferenceError(
`Using removed Babel ${version} option: .${key} - ${message}`,
`Using removed Babel ${version} option: ${msg(loc)} - ${message}`,
);
} else {
// eslint-disable-next-line max-len
const unknownOptErr = `Unknown option: .${key}. Check out http://babeljs.io/docs/usage/options/ for more information about options.`;
const unknownOptErr = `Unknown option: ${msg(
loc,
)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`;
throw new ReferenceError(unknownOptErr);
}
@@ -331,27 +381,53 @@ function assertNoDuplicateSourcemap(opts: {}): void {
}
}
function assertEnvSet(key: string, value: mixed): EnvSet<ValidatedOptions> {
const obj = assertObject(key, value);
function assertEnvSet(loc: OptionPath, value: mixed): EnvSet<ValidatedOptions> {
if (loc.parent.type === "env") {
throw new Error(`${msg(loc)} is not allowed inside of another .env block`);
}
const parent: RootPath | OverridesPath = loc.parent;
const obj = assertObject(loc, value);
if (obj) {
// Validate but don't copy the .env object in order to preserve
// object identity for use during config chain processing.
for (const key of Object.keys(obj)) {
const env = assertObject(key, obj[key]);
if (env) validate("env", env);
for (const envName of Object.keys(obj)) {
const env = assertObject(access(loc, envName), obj[envName]);
if (!env) continue;
const envLoc = {
type: "env",
name: envName,
parent,
};
validateNested(envLoc, env);
}
}
return (obj: any);
}
function assertOverridesList(key: string, value: mixed): OverridesList {
const arr = assertArray(key, value);
function assertOverridesList(loc: OptionPath, value: mixed): OverridesList {
if (loc.parent.type === "env") {
throw new Error(`${msg(loc)} is not allowed inside an .env block`);
}
if (loc.parent.type === "overrides") {
throw new Error(`${msg(loc)} is not allowed inside an .overrides block`);
}
const parent: RootPath = loc.parent;
const arr = assertArray(loc, value);
if (arr) {
for (const [index, item] of arr.entries()) {
const env = assertObject(`${index}`, item);
if (!env) throw new Error(`.${key}[${index}] must be an object`);
const objLoc = access(loc, index);
const env = assertObject(objLoc, item);
if (!env) throw new Error(`${msg(objLoc)} must be an object`);
validate("override", env);
const overridesLoc = {
type: "overrides",
index,
parent,
};
validateNested(overridesLoc, env);
}
}
return (arr: any);

View File

@@ -24,8 +24,8 @@ type Parse = {
export const parse: Parse = (function parse(code, opts, callback) {
if (typeof opts === "function") {
opts = undefined;
callback = opts;
opts = undefined;
}
// For backward-compat with Babel 7's early betas, we allow sync parsing when

View File

@@ -31,8 +31,8 @@ export const transformFromAst: TransformFromAst = (function transformFromAst(
callback,
) {
if (typeof opts === "function") {
opts = undefined;
callback = opts;
opts = undefined;
}
// For backward-compat with Babel 6, we allow sync transformation when

View File

@@ -18,8 +18,8 @@ type Transform = {
export const transform: Transform = (function transform(code, opts, callback) {
if (typeof opts === "function") {
opts = undefined;
callback = opts;
opts = undefined;
}
// For backward-compat with Babel 6, we allow sync transformation when

View File

@@ -1,10 +1,11 @@
// @flow
import * as helpers from "@babel/helpers";
import { NodePath, Hub, Scope } from "@babel/traverse";
import { NodePath, Scope, type HubInterface } from "@babel/traverse";
import { codeFrameColumns } from "@babel/code-frame";
import traverse from "@babel/traverse";
import * as t from "@babel/types";
import semver from "semver";
import type { NormalizedFile } from "../normalize-file";
@@ -26,10 +27,18 @@ export default class File {
ast: Object = {};
scope: Scope;
metadata: {} = {};
hub: Hub = new Hub(this);
code: string = "";
inputMap: Object | null = null;
hub: HubInterface = {
// keep it for the usage in babel-core, ex: path.hub.file.opts.filename
file: this,
getCode: () => this.code,
getScope: () => this.scope,
addHelper: this.addHelper.bind(this),
buildError: this.buildCodeFrameError.bind(this),
};
constructor(options: {}, { code, ast, inputMap }: NormalizedFile) {
this.opts = options;
this.code = code;
@@ -64,6 +73,16 @@ export default class File {
}
set(key: mixed, val: mixed) {
if (key === "helpersNamespace") {
throw new Error(
"Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." +
"If you are using @babel/plugin-external-helpers you will need to use a newer " +
"version than the one you currently have installed. " +
"If you have your own implementation, you'll want to explore using 'helperGenerator' " +
"alongside 'file.availableHelper()'.",
);
}
this._map.set(key, val);
}
@@ -121,12 +140,6 @@ export default class File {
}
}
// TODO: Remove this before 7.x's official release. Leaving it in for now to
// prevent unnecessary breakage between beta versions.
resolveModuleSource(source: string): string {
return source;
}
addImport() {
throw new Error(
"This API has been removed. If you're looking for this " +
@@ -136,17 +149,38 @@ export default class File {
);
}
/**
* Check if a given helper is available in @babel/core's helper list.
*
* This _also_ allows you to pass a Babel version specifically. If the
* helper exists, but was not available for the full given range, it will be
* considered unavailable.
*/
availableHelper(name: string, versionRange: ?string) {
let minVersion;
try {
minVersion = helpers.minVersion(name);
} catch (err) {
if (err.code !== "BABEL_HELPER_UNKNOWN") throw err;
return false;
}
return (
typeof versionRange !== "string" ||
(!semver.intersects(`<${minVersion}`, versionRange) &&
!semver.intersects(`>=8.0.0`, versionRange))
);
}
addHelper(name: string): Object {
const declar = this.declarations[name];
if (declar) return t.cloneNode(declar);
const generator = this.get("helperGenerator");
const runtime = this.get("helpersNamespace");
if (generator) {
const res = generator(name);
if (res) return res;
} else if (runtime) {
return t.memberExpression(t.cloneNode(runtime), t.identifier(name));
}
const uid = (this.declarations[name] = this.scope.generateUidIdentifier(

View File

@@ -293,7 +293,7 @@ function findInsertionLocation<T>(
// Ensure the value is the start of any set of matches.
let i = left;
if (i < array.length) {
while (i > 0 && callback(array[i]) >= 0) {
while (i >= 0 && callback(array[i]) >= 0) {
i--;
}
return i + 1;

View File

@@ -2,6 +2,7 @@
import path from "path";
import buildDebug from "debug";
import cloneDeep from "lodash/cloneDeep";
import * as t from "@babel/types";
import type { PluginPasses } from "../config";
import convertSourceMap, { typeof Converter } from "convert-source-map";
@@ -75,6 +76,7 @@ export default function normalizeFile(
} else if (ast.type !== "File") {
throw new Error("AST root must be a Program or File node");
}
ast = cloneDeep(ast);
} else {
// The parser's AST types aren't fully compatible with the types generated
// by the logic in babel-types.
@@ -89,14 +91,18 @@ export default function normalizeFile(
});
}
function parser(pluginPasses, options, code) {
function parser(
pluginPasses: PluginPasses,
{ parserOpts, highlightCode = true, filename = "unknown" }: Object,
code: string,
) {
try {
const results = [];
for (const plugins of pluginPasses) {
for (const plugin of plugins) {
const { parserOverride } = plugin;
if (parserOverride) {
const ast = parserOverride(code, options.parserOpts, parse);
const ast = parserOverride(code, parserOpts, parse);
if (ast !== undefined) results.push(ast);
}
@@ -104,7 +110,7 @@ function parser(pluginPasses, options, code) {
}
if (results.length === 0) {
return parse(code, options.parserOpts);
return parse(code, parserOpts);
} else if (results.length === 1) {
if (typeof results[0].then === "function") {
throw new Error(
@@ -134,15 +140,16 @@ function parser(pluginPasses, options, code) {
column: loc.column + 1,
},
},
options,
{
highlightCode,
},
);
if (missingPlugin) {
err.message =
`${options.filename || "unknown"}: ` +
`${filename}: ` +
generateMissingPluginMessage(missingPlugin[0], loc, codeFrame);
} else {
err.message =
`${options.filename || "unknown"}: ${err.message}\n\n` + codeFrame;
err.message = `${filename}: ${err.message}\n\n` + codeFrame;
}
err.code = "BABEL_PARSE_ERROR";
}

View File

@@ -31,6 +31,10 @@ export default class PluginPass {
return this._map.get(key);
}
availableHelper(name: string, versionRange: ?string) {
return this.file.availableHelper(name, versionRange);
}
addHelper(name: string) {
return this.file.addHelper(name);
}

View File

@@ -5,11 +5,18 @@ import Plugin from "../lib/config/plugin";
import generator from "@babel/generator";
function assertIgnored(result) {
expect(result).toBeFalsy();
expect(result).toBeNull();
}
function assertNotIgnored(result) {
expect(result.ignored).toBeFalsy();
expect(result).not.toBeNull();
}
function parse(code, opts) {
return babel.parse(code, {
cwd: __dirname,
...opts,
});
}
function transform(code, opts) {
@@ -36,13 +43,18 @@ function transformFileSync(filename, opts) {
});
}
// shim
function transformAsync(code, opts) {
return {
then: function(resolve) {
resolve(transform(code, opts));
},
};
return babel.transformAsync(code, {
cwd: __dirname,
...opts,
});
}
function transformFromAst(ast, code, opts) {
return babel.transformFromAst(ast, code, {
cwd: __dirname,
...opts,
});
}
describe("parser and generator options", function() {
@@ -170,6 +182,30 @@ describe("api", function() {
expect(options).toEqual({ babelrc: false });
});
it("transformFromAst should not mutate the AST", function() {
const program = "const identifier = 1";
const node = parse(program);
const { code } = transformFromAst(node, program, {
plugins: [
function() {
return {
visitor: {
Identifier: function(path) {
path.node.name = "replaced";
},
},
};
},
],
});
expect(code).toBe("const replaced = 1;");
expect(node.program.body[0].declarations[0].id.name).toBe(
"identifier",
"original ast should not have been mutated",
);
});
it("options throw on falsy true", function() {
return expect(function() {
transform("", {
@@ -180,7 +216,7 @@ describe("api", function() {
it("options merge backwards", function() {
return transformAsync("", {
presets: [__dirname + "/../../babel-preset-es2015"],
presets: [__dirname + "/../../babel-preset-env"],
plugins: [__dirname + "/../../babel-plugin-syntax-jsx"],
}).then(function(result) {
expect(result.options.plugins[0].manipulateOptions.toString()).toEqual(
@@ -259,8 +295,8 @@ describe("api", function() {
};
},
// ES2015 preset
require(__dirname + "/../../babel-preset-es2015"),
// env preset
require(__dirname + "/../../babel-preset-env"),
// Third preset for Flow.
function() {

View File

@@ -899,6 +899,23 @@ describe("buildConfigChain", function() {
expect(opts.comments).toBe(true);
});
it("should remove the overrides and filtering fields from the options", () => {
const opts = loadOptions({
cwd: fixture("nonexistant-fake"),
filename: fixture("nonexistant-fake", "src.js"),
babelrc: false,
overrides: [],
test: /^/,
include: /^/,
exclude: [],
});
expect(opts.overrides).toBeUndefined();
expect(opts.test).toBeUndefined();
expect(opts.include).toBeUndefined();
expect(opts.exclude).toBeUndefined();
});
});
describe("config files", () => {

View File

@@ -1,4 +1,4 @@
import loadConfig from "../lib/config";
import loadConfig, { loadPartialConfig } from "../lib/config";
import path from "path";
describe("@babel/core config loading", () => {
@@ -29,13 +29,53 @@ describe("@babel/core config loading", () => {
filename: FILEPATH,
presets: skipProgrammatic
? null
: [require("./fixtures/config-loading/preset3")],
: [[require("./fixtures/config-loading/preset3"), {}]],
plugins: skipProgrammatic
? null
: [require("./fixtures/config-loading/plugin6")],
: [[require("./fixtures/config-loading/plugin6"), {}]],
};
}
describe("loadPartialConfig", () => {
it("should preserve disabled plugins in the partial config", () => {
const plugin = function() {
return {};
};
const opts = loadPartialConfig({
...makeOpts(true),
babelrc: false,
configFile: false,
plugins: [[plugin, false]],
});
expect(opts.options.plugins.length).toBe(1);
const item = opts.options.plugins[0];
expect(item.value).toBe(plugin);
expect(item.options).toBe(false);
});
it("should preserve disabled presets in the partial config", () => {
const preset = function() {
return {};
};
const opts = loadPartialConfig({
...makeOpts(true),
babelrc: false,
configFile: false,
presets: [[preset, false]],
});
expect(opts.options.presets.length).toBe(1);
const item = opts.options.presets[0];
expect(item.value).toBe(preset);
expect(item.options).toBe(false);
});
});
describe("config file", () => {
it("should load and cache the config with plugins and presets", () => {
const opts = makeOpts();
@@ -173,7 +213,7 @@ describe("@babel/core config loading", () => {
}
});
it("should invalidate the plugins when given a fresh arrays", () => {
it("should not invalidate the plugins when given a fresh arrays", () => {
const opts = makeOpts();
const options1 = loadConfig(opts).options;
@@ -184,6 +224,38 @@ describe("@babel/core config loading", () => {
}).options;
expect(options2.plugins.length).toBe(options1.plugins.length);
for (let i = 0; i < options2.plugins.length; i++) {
expect(options2.plugins[i]).toBe(options1.plugins[i]);
}
});
it("should not invalidate the presets when given a fresh arrays", () => {
const opts = makeOpts();
const options1 = loadConfig(opts).options;
const options2 = loadConfig({
...opts,
presets: opts.presets.slice(),
}).options;
expect(options2.plugins.length).toBe(options1.plugins.length);
for (let i = 0; i < options2.plugins.length; i++) {
expect(options2.plugins[i]).toBe(options1.plugins[i]);
}
});
it("should invalidate the plugins when given a fresh options", () => {
const opts = makeOpts();
const options1 = loadConfig(opts).options;
const options2 = loadConfig({
...opts,
plugins: opts.plugins.map(([plg, opt]) => [plg, { ...opt }]),
}).options;
expect(options2.plugins.length).toBe(options1.plugins.length);
for (let i = 0; i < options2.plugins.length; i++) {
if (i === 2) {
expect(options2.plugins[i]).not.toBe(options1.plugins[i]);
@@ -193,14 +265,14 @@ describe("@babel/core config loading", () => {
}
});
it("should invalidate the presets when given a fresh arrays", () => {
it("should invalidate the presets when given a fresh options", () => {
const opts = makeOpts();
const options1 = loadConfig(opts).options;
const options2 = loadConfig({
...opts,
presets: opts.presets.slice(),
presets: opts.presets.map(([plg, opt]) => [plg, { ...opt }]),
}).options;
expect(options2.plugins.length).toBe(options1.plugins.length);
@@ -251,4 +323,51 @@ describe("@babel/core config loading", () => {
}
});
});
describe("caller metadata", () => {
it("should pass caller data through", () => {
const options1 = loadConfig({
...makeOpts(),
caller: {
name: "babel-test",
someFlag: true,
},
}).options;
expect(options1.caller.name).toBe("babel-test");
expect(options1.caller.someFlag).toBe(true);
});
it("should pass unknown caller data through", () => {
const options1 = loadConfig({
...makeOpts(),
caller: undefined,
}).options;
expect(options1.caller).toBeUndefined();
});
it("should pass caller data to test functions", () => {
const options1 = loadConfig({
...makeOpts(),
caller: {
name: "babel-test",
someFlag: true,
},
overrides: [
{
test: (filename, { caller }) => caller.name === "babel-test",
comments: false,
},
{
test: (filename, { caller }) => caller.name !== "babel-test",
ast: false,
},
],
}).options;
expect(options1.comments).toBe(false);
expect(options1.ast).not.toBe(false);
});
});
});

View File

@@ -1,5 +1,5 @@
{
"plugins": [
["@babel/syntax-decorators", { "legacy": true }]
]
"parserOpts": {
"plugins": ["decorators-legacy"]
}
}

View File

@@ -0,0 +1,3 @@
module.exports = function() {
return {};
};

View File

@@ -0,0 +1,3 @@
module.exports = function() {
return {};
};

View File

@@ -0,0 +1,3 @@
module.exports = function() {
return {};
};

View File

@@ -0,0 +1,3 @@
module.exports = function() {
return {};
};

View File

@@ -1,4 +1,4 @@
{
"plugins": ["transform-async-to-generator"],
"presets": ["es2015"]
"presets": ["env"]
}

View File

@@ -5,13 +5,11 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

View File

@@ -1,7 +1,10 @@
{
"compact": false,
"presets": [
"es2015",
["stage-2", { "decoratorsLegacy": true }]
"env"
],
"plugins": [
"external-helpers",
"proposal-object-rest-spread"
]
}

View File

@@ -1,4 +1,4 @@
{
"plugins": ["transform-async-to-generator"],
"presets": ["es2015"]
"presets": ["env"]
}

View File

@@ -1,7 +1,7 @@
[{
"original": {
"line": 1,
"column": 13
"column": 14
},
"generated": {
"line": 2,

View File

@@ -6,6 +6,6 @@
"map",
"x"
],
"mappings": "AAAAA,IAAIC,GAAJ,CAAQ;AAAA,SAAKC,IAAIA,CAAT;AAAA,CAAR",
"mappings": "AAAAA,GAAG,CAACC,GAAJ,CAAQ,UAAAC,CAAC;AAAA,SAAIA,CAAC,GAAGA,CAAR;AAAA,CAAT",
"sourcesContent": ["arr.map(x => x * x);"]
}

View File

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

View File

@@ -4,7 +4,7 @@
"HelloWorld.vue"
],
"names": [],
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAsFA;AACA,QAAA,YADA;;AAEA,SAAA;AACA,WAAA;AACA,WAAA;AADA,KAAA;AAGA;;AANA,C",
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAsFA;AACA,EAAA,IAAA,EAAA,YADA;;AAEA,EAAA,IAAA,GAAA;AACA,WAAA;AACA,MAAA,GAAA,EAAA;AADA,KAAA;AAGA;;AANA,C",
"sourceRoot": "src/components",
"sourcesContent": [
"<template>\n <div class=\"hello\">\n <h1>{{ msg }}</h1>\n <h2>Essential Links</h2>\n <ul>\n <li>\n <a\n href=\"https://vuejs.org\"\n target=\"_blank\"\n >\n Core Docs\n </a>\n </li>\n <li>\n <a\n href=\"https://forum.vuejs.org\"\n target=\"_blank\"\n >\n Forum\n </a>\n </li>\n <li>\n <a\n href=\"https://chat.vuejs.org\"\n target=\"_blank\"\n >\n Community Chat\n </a>\n </li>\n <li>\n <a\n href=\"https://twitter.com/vuejs\"\n target=\"_blank\"\n >\n Twitter\n </a>\n </li>\n <br>\n <li>\n <a\n href=\"http://vuejs-templates.github.io/webpack/\"\n target=\"_blank\"\n >\n Docs for This Template\n </a>\n </li>\n </ul>\n <h2>Ecosystem</h2>\n <ul>\n <li>\n <a\n href=\"http://router.vuejs.org/\"\n target=\"_blank\"\n >\n vue-router\n </a>\n </li>\n <li>\n <a\n href=\"http://vuex.vuejs.org/\"\n target=\"_blank\"\n >\n vuex\n </a>\n </li>\n <li>\n <a\n href=\"http://vue-loader.vuejs.org/\"\n target=\"_blank\"\n >\n vue-loader\n </a>\n </li>\n <li>\n <a\n href=\"https://github.com/vuejs/awesome-vue\"\n target=\"_blank\"\n >\n awesome-vue\n </a>\n </li>\n </ul>\n </div>\n</template>\n\n<script>\nexport default {\n name: 'HelloWorld',\n data () {\n return {\n msg: 'Welcome to Your Vue.js App'\n }\n }\n}\n</script>\n\n<!-- Add \"scoped\" attribute to limit CSS to this component only -->\n<style scoped>\nh1, h2 {\n font-weight: normal;\n}\nul {\n list-style-type: none;\n padding: 0;\n}\nli {\n display: inline-block;\n margin: 0 10px;\n}\na {\n color: #42b983;\n}\n</style>\n"

View File

@@ -1,5 +1,5 @@
{
"mappings": "AAAA,IAAA,MAAU,Y;SAAM,C;AAAC,CAAjB",
"mappings": "AAAA,IAAA,GAAA,GAAU,Y;SAAM,C;AAAC,CAAjB",
"names": [],
"sources": ["original.js"],
"sourcesContent": ["var foo = () => 4;"],

View File

@@ -1,5 +1,5 @@
{
"mappings": "AAAA;AAEAA,QAAQC,GAAR,CAAY,eAAZ",
"mappings": "AAAA;AAEAA,OAAO,CAACC,GAAR,CAAY,eAAZ",
"names": [
"console",
"log"

View File

@@ -23,7 +23,9 @@ describe("parse", function() {
const output = require(fixture("output.json"));
const result = parse(input, {
parserOpts: { plugins: ["decorators"] },
parserOpts: {
plugins: [["decorators", { decoratorsBeforeExport: false }]],
},
cwd: fixture(),
});
expect(JSON.parse(JSON.stringify(result))).toEqual(output);

View File

@@ -134,6 +134,46 @@ describe("addon resolution", function() {
});
});
it("should find @foo scoped presets with an inner babel-preset", function() {
process.chdir("foo-org-paths");
babel.transform("", {
filename: "filename.js",
babelrc: false,
presets: ["@foo/thing.babel-preset-convert"],
});
});
it("should find @foo scoped plugins with an inner babel-plugin", function() {
process.chdir("foo-org-paths");
babel.transform("", {
filename: "filename.js",
babelrc: false,
plugins: ["@foo/thing.babel-plugin-convert"],
});
});
it("should find @foo scoped presets with an babel-preset suffix", function() {
process.chdir("foo-org-paths");
babel.transform("", {
filename: "filename.js",
babelrc: false,
presets: ["@foo/thing-babel-preset"],
});
});
it("should find @foo scoped plugins with an babel-plugin suffix", function() {
process.chdir("foo-org-paths");
babel.transform("", {
filename: "filename.js",
babelrc: false,
plugins: ["@foo/thing-babel-plugin"],
});
});
it("should find @foo scoped presets with an existing prefix", function() {
process.chdir("foo-org-paths");

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/generator",
"version": "7.0.0-beta.52",
"version": "7.0.0",
"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.52",
"@babel/types": "^7.0.0",
"jsesc": "^2.5.1",
"lodash": "^4.17.5",
"lodash": "^4.17.10",
"source-map": "^0.5.0",
"trim-right": "^1.0.1"
},
"devDependencies": {
"@babel/helper-fixtures": "7.0.0-beta.52",
"@babel/parser": "7.0.0-beta.52"
"@babel/helper-fixtures": "^7.0.0",
"@babel/parser": "^7.0.0"
}
}

View File

@@ -30,6 +30,7 @@ export default class Buffer {
column: null,
filename: null,
};
_disallowedPop: Object | null = null;
/**
* Get the final string output from the buffer, along with the sourcemap if one exists.
@@ -71,8 +72,14 @@ export default class Buffer {
append(str: string): void {
this._flush();
const { line, column, filename, identifierName } = this._sourcePosition;
this._append(str, line, column, identifierName, filename);
const {
line,
column,
filename,
identifierName,
force,
} = this._sourcePosition;
this._append(str, line, column, identifierName, filename, force);
}
/**
@@ -87,8 +94,14 @@ export default class Buffer {
}
}
const { line, column, filename, identifierName } = this._sourcePosition;
this._queue.unshift([str, line, column, identifierName, filename]);
const {
line,
column,
filename,
identifierName,
force,
} = this._sourcePosition;
this._queue.unshift([str, line, column, identifierName, filename, force]);
}
_flush(): void {
@@ -102,6 +115,7 @@ export default class Buffer {
column: number,
identifierName: ?string,
filename: ?string,
force?: boolean,
): void {
// If there the line is ending, adding a new mapping marker is redundant
if (this._map && str[0] !== "\n") {
@@ -112,6 +126,7 @@ export default class Buffer {
column,
identifierName,
filename,
force,
);
}
@@ -169,20 +184,60 @@ export default class Buffer {
return this._queue.length > 0 || !!this._last;
}
/**
* Certain sourcemap usecases expect mappings to be more accurate than
* Babel's generic sourcemap handling allows. For now, we special-case
* identifiers to allow for the primary cases to work.
* The goal of this line is to ensure that the map output from Babel will
* have an exact range on identifiers in the output code. Without this
* line, Babel would potentially include some number of trailing tokens
* that are printed after the identifier, but before another location has
* been assigned.
* This allows tooling like Rollup and Webpack to more accurately perform
* their own transformations. Most importantly, this allows the import/export
* transformations performed by those tools to loose less information when
* applying their own transformations on top of the code and map results
* generated by Babel itself.
*
* The primary example of this is the snippet:
*
* import mod from "mod";
* mod();
*
* With this line, there will be one mapping range over "mod" and another
* over "();", where previously it would have been a single mapping.
*/
exactSource(loc: Object, cb: () => void) {
// In cases where parent expressions start at the same locations as the
// identifier itself, the current active location could already be the
// start of this range. We use 'force' here to explicitly start a new
// mapping range for this new token.
this.source("start", loc, true /* force */);
cb();
// In cases where tokens are printed after this item, we want to
// ensure that they get the location of the _end_ of the identifier.
// To accomplish this, we assign the location and explicitly disable
// the standard Buffer withSource previous-position "reactivation"
// logic. This means that if another item calls '.source()' to set
// the location after the identifier, it is fine, but the position won't
// be automatically replaced with the previous value.
this.source("end", loc);
this._disallowPop("start", loc);
}
/**
* Sets a given position as the current source location so generated code after this call
* will be given this position in the sourcemap.
*/
source(prop: string, loc: Location): void {
source(prop: string, loc: Location, force?: boolean): void {
if (prop && !loc) return;
const pos = loc ? loc[prop] : null;
this._sourcePosition.identifierName = (loc && loc.identifierName) || null;
this._sourcePosition.line = pos ? pos.line : null;
this._sourcePosition.column = pos ? pos.column : null;
this._sourcePosition.filename = (loc && loc.filename) || null;
// Since this is called extremly often, we re-use the same _sourcePosition
// object for the whole lifetime of the buffer.
this._normalizePosition(prop, loc, this._sourcePosition, force);
}
/**
@@ -192,7 +247,9 @@ export default class Buffer {
withSource(prop: string, loc: Location, cb: () => void): void {
if (!this._map) return cb();
// Use the call stack to manage a stack of "source location" data.
// Use the call stack to manage a stack of "source location" data because
// the _sourcePosition object is mutated over the course of code generation,
// and constantly copying it would be slower.
const originalLine = this._sourcePosition.line;
const originalColumn = this._sourcePosition.column;
const originalFilename = this._sourcePosition.filename;
@@ -202,10 +259,79 @@ export default class Buffer {
cb();
this._sourcePosition.line = originalLine;
this._sourcePosition.column = originalColumn;
this._sourcePosition.filename = originalFilename;
this._sourcePosition.identifierName = originalIdentifierName;
if (
// If the current active position is forced, we only want to reactivate
// the old position if it is different from the newest position.
(!this._sourcePosition.force ||
this._sourcePosition.line !== originalLine ||
this._sourcePosition.column !== originalColumn ||
this._sourcePosition.filename !== originalFilename) &&
// Verify if reactivating this specific position has been disallowed.
(!this._disallowedPop ||
this._disallowedPop.line !== originalLine ||
this._disallowedPop.column !== originalColumn ||
this._disallowedPop.filename !== originalFilename)
) {
this._sourcePosition.line = originalLine;
this._sourcePosition.column = originalColumn;
this._sourcePosition.filename = originalFilename;
this._sourcePosition.identifierName = originalIdentifierName;
this._sourcePosition.force = false;
this._disallowedPop = null;
}
}
/**
* Allow printers to disable the default location-reset behavior of the
* sourcemap output, so that certain printers can be sure that the
* "end" location that they set is actually treated as the end position.
*/
_disallowPop(prop: string, loc: Location) {
if (prop && !loc) return;
this._disallowedPop = this._normalizePosition(prop, loc);
}
_normalizePosition(
prop: string,
loc: Object,
targetObj: Object,
force?: boolean,
) {
const pos = loc ? loc[prop] : null;
if (targetObj === undefined) {
// Initialize with fields so that the object doesn't change shape.
targetObj = {
identifierName: null,
line: null,
column: null,
filename: null,
force: false,
};
}
const origLine = targetObj.line;
const origColumn = targetObj.column;
const origFilename = targetObj.filename;
targetObj.identifierName =
(prop === "start" && loc && loc.identifierName) || null;
targetObj.line = pos ? pos.line : null;
targetObj.column = pos ? pos.column : null;
targetObj.filename = (loc && loc.filename) || null;
// We want to skip reassigning `force` if we're re-setting the same position.
if (
force ||
targetObj.line !== origLine ||
targetObj.column !== origColumn ||
targetObj.filename !== origFilename
) {
targetObj.force = force;
}
return targetObj;
}
getCurrentColumn(): number {

View File

@@ -124,6 +124,7 @@ export function ClassPrivateProperty(node: Object) {
this.space();
}
this.print(node.key, node);
this.print(node.typeAnnotation, node);
if (node.value) {
this.space();
this.token("=");

View File

@@ -73,6 +73,7 @@ function spaceSeparator() {
export function JSXOpeningElement(node: Object) {
this.token("<");
this.print(node.name, node);
this.print(node.typeParameters, node); // TS
if (node.attributes.length > 0) {
this.space();
this.printJoin(node.attributes, node, { separator: spaceSeparator });

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