Compare commits

...

173 Commits

Author SHA1 Message Date
Henry Zhu
7d798952d2 v7.0.0-beta.36 2017-12-25 14:04:08 -05:00
Joe Lim
ed2b88830e Remove extraneous console output when running preset-env tests (#6576) 2017-12-25 13:47:19 -05:00
Bogdan Chadkin
d25918aa5d Fix generation flow unnamed computed property (#7095) 2017-12-22 12:55:40 -06:00
Artem Yavorsky
035286a810 [preset-env] Move all defaults to the separate module (#7084)
* preset-env: Move all defaults to the separate module.

* preset-env: Add test cases for defaults.
2017-12-22 10:42:06 -05:00
Logan Smyth
c9a00fbae8 Merge pull request #7090 from loganfsmyth/chain-processing-rewrite
Refactor config processing more
2017-12-21 19:57:07 -08:00
Logan Smyth
758fd0369c Rewrite config chain loading to build chain recursively to keep caching readable. 2017-12-21 19:06:36 -08:00
Logan Smyth
7b861796cf Centralize validation logic in common folder. 2017-12-21 14:45:19 -08:00
Logan Smyth
f9825394a7 Remove unnecessary folder nesting. 2017-12-21 14:45:19 -08:00
Logan Smyth
43e7d1d2cc Use an object instead of a 2-tuple. 2017-12-21 12:31:48 -08:00
Logan Smyth
de63443762 Split babelrc and babelignore searching into two functions. 2017-12-21 12:28:51 -08:00
Andy
6a73f39199 Support parsing export default abstract class {} (#7075) 2017-12-21 16:13:31 +01:00
Azharuddin
2190e10e9a Better error messages when Babel fails to parse import = and export =… (#7079)
* Better error messages when Babel fails to parse import = and export = syntax from typescript when using babel-plugin-transform-typescript

* Fixing Test cases

* Ran make fix and broken looong sentence into smaller

* Slight changes to Messages after review with Nicolo & existentialism

* Removed trailing space
2017-12-21 02:00:36 +02:00
Nicolò Ribaudo
ae3f5b9149 Return the obj in setPrototypeOf fallback (#7080) 2017-12-20 22:48:10 +01:00
Nicolò Ribaudo
0c885b3200 Add support for extending builtins (#7020) 2017-12-20 14:46:00 -05:00
Artem Yavorsky
148fe7d3ff Add proposal-async-generator-functions to babel-standalone (#7073) 2017-12-20 20:37:16 +01:00
Henry Zhu
cabdf3769d Merge pull request #7065 from babel/dotall-preset-env
Add dot-all regex support to preset-env and standalone
2017-12-19 20:45:18 -05:00
Logan Smyth
1178799f07 Remove the LoadedFile class. 2017-12-19 15:36:54 -08:00
Logan Smyth
b2f1d01965 Add type annotations to utility file. 2017-12-19 15:36:19 -08:00
Logan Smyth
4f53496546 Drop the OptionManager class in favor of function. 2017-12-19 14:19:37 -08:00
Logan Smyth
1312a30d54 Perform normalization in the chain building process. 2017-12-19 14:19:37 -08:00
Logan Smyth
4afbc02476 Move descriptor merging into config chain processing. 2017-12-19 14:19:37 -08:00
Brian Ng
080c7f1e2d Clean up logPlugin 2017-12-19 14:57:19 -06:00
Brian Ng
3cea9f412a Add dot-all regex support to preset-env and standalone 2017-12-19 11:39:00 -06:00
Brian Ng
cd10ea03b4 Fix bug with debug output and unreleased versions 2017-12-19 11:38:59 -06:00
Mathias Bynens
5f8a1a2613 Fix unicode-property-regex installation instructions (#7064) 2017-12-19 11:27:26 -06:00
Mathias Bynens
44da8201a5 Import babel-plugin-transform-dotall-regex (#7059)
Original: https://github.com/mathiasbynens/babel-plugin-transform-dotall-regex

Moving it into the official Babel repository makes it easier to maintain the transform.
2017-12-19 11:01:59 -05:00
Brian Ng
2b065350b5 Treat import type * as a parser error (#7061) 2017-12-19 10:54:20 -05:00
Nicolò Ribaudo
68476b6ddd Make .insert{Before,After} work by default when the parent is an eport declaration (#7040) 2017-12-19 00:05:29 +01:00
Maaz Syed Adeeb
17b37b5013 Handling babylon parsing errors in a better way (#6961)
* Handling babylon parsing errors in a better way

* Better error messages + Helpful URLs

* Replaced message from babylon completely

* Add importMeta plugin to the map
2017-12-18 15:49:34 -05:00
Bo Lingen
56638e1370 Add pipeline operator plugins to babel-standalone (#6955) 2017-12-18 10:10:20 -06:00
Francisco Ryan Tolmasky I
f0e46772a6 babel-types lists JSXIdentifier as an Expression (#6960)
Currently, Babel is treating JSXIdentifier, JSXMemberExpression, and JSXEmptyExpression as expressions as well, which means Babel will for example incorrectly allow you to place these anywhere an expression is wanted.

Closes #6851.
2017-12-18 09:27:43 -06:00
Mahmut Surekci
398bc43656 Add MIT license to proposal-unicode-property-regex (#7047) 2017-12-18 13:48:30 +01:00
Logan Smyth
44ea9433c0 Merge pull request #6952 from loganfsmyth/commonjs-lazy
Add a 'lazy' options to modules-commonjs
2017-12-17 19:32:51 -08:00
Logan Smyth
53826aaaa0 Expose a 'lazy' option for the CommonJS transform. 2017-12-17 18:42:35 -08:00
Logan Smyth
b900a3e5c2 Consistently return AST nodes. 2017-12-17 18:33:47 -08:00
dnalborczyk
ed4d90b33d expose import.meta syntax parser option as plugin (#7008) 2017-12-16 15:06:23 -06:00
Anthony Bianco
209a598d51 Fix loose option description in transform-modules-commonjs 2017-12-16 14:41:05 -06:00
Nicolò Ribaudo
9a146d01b0 [decorators] Don't transform every AssignmentExpression (#7032) 2017-12-15 16:17:31 -05:00
Rouven Weßling
f2437583ba Bump globals to version 11.1.0 (#7006) 2017-12-15 13:20:22 -05:00
Sven SAULEAU
a24c9f8ed6 Merge pull request #7028 from sophiebits/getLetReferences-n2
Fix O(n^2) getLetReferences – 40% faster on large flat files
2017-12-15 07:59:57 +01:00
Sophie Alpert
6a7223af29 Fix O(n^2) getLetReferences – 40% faster on large flat files
`this.blockPath.get("body")` constructs an array of paths corresponding to each node in `blocks.body` so takes O(n) time if n is that length. We were re-constructing that array on each iteration, so the entire loop was O(n^2).

On files with many statements in a single block (such as Rollup-generated bundles), this takes a large portion of time. In particular, this makes transforming react-dom.development.js about 40% faster. Not that you should be transforming our bundle with Babel.

Test Plan:
Make an HTML file with these three lines and watch it in the Chrome Performance tab to see timings (on my machine: 2.9s before, 1.6s after):

```
<!DOCTYPE html>
<script src="https://unpkg.com/babel-standalone@7.0.0-beta.3/babel.js"></script>
<script type="text/babel" src="https://unpkg.com/react-dom@16.2.0/umd/react-dom.development.js"></script>
```
2017-12-14 21:55:26 -08:00
Diogo Franco
a66845169f Rename misleading identifier
notRegenerator actually _enabled_ transforming regeneratorRuntime references.
2017-12-15 11:20:15 +09:00
Henry Zhu
8a4124b2ff v7.0.0-beta.35 2017-12-14 16:47:27 -05:00
Nicolò Ribaudo
05b22d2597 Update @babel/helper-wrap-function templates (#6984)
This commit introduces 4 changes:

1) Function declarations are wrapped using function declarations.
   This has two advantages:
    - We can rely on native hoisting, instead of using _blockHoist
    - The function isn't wrapped until it is called. This avoids
      problems where `regeneratorRuntime.wrap` was called before
      that `babel-polyfill` was imported.

   Example:
     function fn() {}
     // becomes
     function fn() { return _fn.apply(this, arguments); }
     function _fn() {
       _fn = _wrapper(/* Original function ... */);
       return _fn.apply(this, arguments);
     }

2) Use a single template for both named and anonymous function
   expressions. They already had the same behavior, but the one
   used for named functions was a bit longer.

3) Use normal functions instead of arrow functions to wrap
   function expressions.

4) Generate a name based on the original one for wrapped
   functions (e.g. `foo` becomes `_foo` instead of `_ref`).
2017-12-13 16:21:58 +01:00
Peri Nikhil
9cc0a26694 Move helpers from 'babel-plugin-proposal-decorators' to 'babel-helpers' (#7017) 2017-12-13 16:08:19 +01:00
Brian Ng
f5ef928586 Add method property to ObjectTypeProperty (#7005) 2017-12-11 09:32:16 -06:00
Brian Ng
42f66782be Improve error message in types assert (#7001) 2017-12-11 09:31:56 -06:00
Daniel Poindexter
12ac1bccd7 Fix type definitions to fully support Typescript (#6939) 2017-12-08 17:03:01 -06:00
Diogo Franco
82357d79a7 Workaround bad #__PURE__ annotation placement on IIFEs (#6999)
Based on a fix suggested by @kzc
2017-12-08 09:51:48 -05:00
Diogo Franco
2958548c2c Fix code generation for async generator methods (#6998)
Fixes generator to write `async *foo() {}` instead of `*async foo() {}`.
2017-12-08 17:38:31 +09:00
Henry Zhu
468aecca21 Add Babel's song: Hallelujah (thanks to Angus) [skip ci] (#6994) 2017-12-07 21:18:17 -05:00
Brian Ng
c7980b2b90 Bump prettier (#6991) 2017-12-07 17:36:49 -05:00
Henry Zhu
d6db5fb1e1 Update to the latest version of regenerator that uses the MIT license (#6992) 2017-12-07 15:32:36 -05:00
K Sashi Kumar
ac745ded0d Fix destructuring assignment spec violation (#6986) 2017-12-07 09:14:03 -06:00
Nicolò Ribaudo
a2aabbd33d Generate better builder names for JSX* and TS* (#6967)
e.g. JSXIdentifier -> jsxIdentifier.
The jSXIdentifier alias isn't removed, so this commit doesn't introduce breaking changes.
2017-12-07 12:17:40 +01:00
Henry Zhu
fcfa987926 publish babylon as next tag since it's not a scoped module yet [skip ci] (#6982) 2017-12-06 15:05:48 -05:00
Nicolò Ribaudo
509dbb7302 this before super() is a runtime error, not a static one. (#6467)
* Check that super.* is after super() at runtime

* "missing super() call in constructor" runtime

* "'this' is not allowed before super()" runtime
2017-12-06 06:46:54 +01:00
Leo Hsieh
e270fbe7f0 Update babylon ast links on CONTRIBUTING.md (#6972) [skip ci] 2017-12-04 23:43:40 +01:00
Andy
aa38c47160 For babylon typescript parser, fix false positive for ! after a line break (#6969)
Closes #6798
2017-12-04 19:57:22 +01:00
Nicolò Ribaudo
62bbee97d7 Better error message for import.meta and import() without plugin (#6962)
The correct error was already thrown when they weren't in statement position.
2017-12-03 17:45:37 +01:00
Daniel Tschinder
ac72bfbd33 Update babylon to use unicode 10 (#6958) 2017-12-03 11:55:50 +01:00
Henry Zhu
a7c9264c79 v7.0.0-beta.34 2017-12-02 09:38:52 -05:00
Raja Sekar
c41eb0d052 Do Expression from Stage 0 to Stage 1 (#6943) 2017-12-02 09:02:31 -05:00
Daniel Tschinder
de5ab72c49 Update flow to 0.59 and fix some flow issues (#6957) 2017-12-02 08:59:46 -05:00
Henry Zhu
607916880d update to beta.33 (#6948)
* update to beta.33

* typeof is excluded by default in loose mode
2017-12-02 08:59:08 -05:00
Daniel Tschinder
8270903ba2 Refactor @babel/types to be 100% ES-module (#6741)
This generates the dynamic functions at buildtime and also
splits the package into smaller files to avoid dependency circles.
2017-12-02 12:20:10 +01:00
Brian Ng
95fe785354 Fix stage refs to exportNamespaceFrom and exportDefaultFrom (#6949) 2017-12-01 12:29:51 -05:00
Henry Zhu
413aa79711 v7.0.0-beta.33 2017-12-01 09:27:57 -05:00
Henry Zhu
1a3a502f97 Remove some built files before publish [skip ci] (#6946) 2017-12-01 09:25:27 -05:00
Henry Zhu
5761eb0bb4 add readme entry for for-of assumeArray, use it (#6942) 2017-11-30 17:40:23 -06:00
Raja Sekar
a992d06c41 Porting babel-plugin-transform-for-of-as-array into transform-for-of as an option (#6914) 2017-11-30 17:48:56 -05:00
Brian Ng
d8bbaaae0a Split exportExtensions into exportDefault and exportNamespace plugins… (#6920)
* Split exportExtensions into two plugins in babylon
* rename proposal-export-default to proposal-export-default-from
* rename proposal-export-namespace to proposal-export-namespace-from
2017-11-30 17:46:36 -05:00
Daniel Tschinder
9d9710c765 Copy getters and setters correctly in interopWildcard (#6850) 2017-11-30 15:50:10 -06:00
Sam Gluck
18b91a8388 [plugin-proposal-class-properties] Fix small loose docs typo (#6941) 2017-11-30 15:09:36 -06:00
Artem Yavorsky
0a2a37c31f Fix export from assignment order for loose mode. (#6863)
* Consider reexports for bindingKindLookup.

* Update test cases according to reexports change

* Fix order for assign reexports.

* void 0 assignation to module keys only for loose mode.

* Create buildReexportsFromMeta helper.

* Update umd/amd fixtures.

* Refactor reexports build.

* Hoist template for reexports.

* Use map as a second argument of Array.from.

* Remove unnecessary export.
2017-11-29 11:58:29 -08:00
Boda
d731acc351 updated Unpkg link (#6929)
...to be the same as the link in the Installation section
2017-11-29 11:41:13 -05:00
Logan Smyth
fba19295b4 Merge pull request #6905 from loganfsmyth/config-options-merge
Merge all config & programmatic plugins/preset rather than duplicating
2017-11-28 13:46:36 -08:00
Logan Smyth
8fc8a1f2ee Use public options API for tests. 2017-11-28 13:25:10 -08:00
Nicolò Ribaudo
18c8d97c3d UpdateExpressions as callees must be parenthesized (#6922) 2017-11-27 23:31:24 +01:00
Henry Zhu
58962c35b5 update regenerator (removed explicit babel-types dep) (#6917) 2017-11-27 23:16:41 +01:00
Brian Ng
881fc14329 Add handling parens for extends clause in generator (#6897) 2017-11-27 12:08:35 -06:00
Daniel Lo Nigro
7d8932b6be Add comment to babel-standalone to dissuade removal of whitelist (#6910)
There was a good discussion on https://github.com/babel/babel/pull/6177. Linking to it in the code to preserve the comments.
2017-11-27 10:08:28 -08:00
Mauro Bringolf
6330a152ce Implement TDZ for ClassFieldDefinitionEvaluation (#6855)
* First implementation sketch and testcase

* Use helper instead of inline IIFE's

* minNodeVersion 6.0.0

* Hoisted visitor for subtraversal and fixed edgest case

* Resolve merge conflicts in helpers

* Remove duplicated helper from messing up Git
2017-11-26 16:56:04 +01:00
Logan Smyth
189c56628a Replace repeated plugins/preset in top-level config instead of running both. 2017-11-25 18:47:13 -08:00
Logan Smyth
8be488652f Allow plugins and presets to have explicit names. 2017-11-25 18:46:00 -08:00
Logan Smyth
cdf420d4d8 Rewrite config chain tests to use public loadOptions API. (#6909) 2017-11-25 18:25:20 -08:00
Nicolas Marien
cf62908bbd Keep user options intact in transformFile (#6890)
* Preserve user options in transformFile

* Improve tests for transformFile user opts handling
2017-11-25 10:13:56 -08:00
Logan Smyth
66ee192a7f Merge pull request #6904 from loganfsmyth/config-merge-prep
Add a 'cwd' option, and misc refactoring and tweaks before simple config merging
2017-11-24 22:54:40 -08:00
Logan Smyth
c635ff9c32 Remove duplicate from plugin list. 2017-11-24 19:45:15 -08:00
Logan Smyth
6cb9d20a0a Tie presets pass metadata to descriptors. 2017-11-24 19:45:15 -08:00
Logan Smyth
b5cb78d33a Move plugin pass initialization logic a bit. 2017-11-24 19:45:15 -08:00
Logan Smyth
1d0a3d6772 Remove duplicated assertion. Covered by validate() 2017-11-24 19:45:14 -08:00
Logan Smyth
18ea5aca51 Expose a 'cwd' option for Babel's root options. 2017-11-24 19:43:25 -08:00
Logan Smyth
db28c18458 Disallow nested '.env' blocks since they are useless. 2017-11-24 17:45:27 -08:00
Logan Smyth
a89171910f Merge pull request #6834 from loganfsmyth/caching-refactor
Expose `envName` as a top-level Babel option to avoid using environmental variables
2017-11-24 17:42:16 -08:00
Mark Shulhin
0056fb1cfb Fixed ignore in readme for babel-register [skip ci] (#6899) 2017-11-24 17:45:49 -05:00
Sven SAULEAU
041dd4a536 Merge pull request #6893 from Arfey/features/updated-gitignore-file
feat: updated .gitignore file
2017-11-24 20:13:37 +01:00
misha.gavela
428e294ded Merge branch 'master' of https://github.com/babel/babel into features/updated-gitignore-file 2017-11-24 19:21:30 +02:00
Brian Ng
0a3c2a0c4c Fix babylon test 2017-11-24 09:15:17 -06:00
misha.gavela
917e3ede31 feat: updated .gitignore file 2017-11-24 15:18:13 +02:00
Martin McKeaveney
6d820a2757 removing expression field from ArrowFunctionExpression (#6836) 2017-11-23 22:12:13 +01:00
Mateusz Burzyński
1ef7e0f48e Allowed hintedNames for namespaced imports, changed some other defaults for more readable ones (#6744) 2017-11-23 21:01:47 +01:00
Daniel Tschinder
9206df964d Use only imports in babel-traverse and remove double exports (#6881) 2017-11-23 20:59:54 +01:00
Brian Ng
c583a04a55 Fix setting deopt properly after evaluating multiple expressions (#6882) 2017-11-22 20:06:57 -05:00
Gidi Meir Morris
edbf5d33dc Fix "Better error messaging for unexpected tokens #6715" (#6875) 2017-11-22 15:31:03 -06:00
Brian Ng
8393a6d089 Add firefox 58 mappings to preset-env data (#6874) 2017-11-22 15:30:07 -06:00
Nicolò Ribaudo
464df13c69 Allow yielding an arrow function withour parens around the param (#6877) 2017-11-22 15:28:37 -06:00
Logan Smyth
80b4b7120b Quick fix for typescript import crash. (#6879) 2017-11-22 13:27:31 -08:00
Brian Ng
ccd7c25174 Regen babel-types docsdocs and interfaces [skip ci] 2017-11-22 08:53:16 -06:00
Sven SAULEAU
4384d38b90 Merge pull request #6862 from maurobringolf/const-violation-helper
Define readOnlyError helper and use in check-constants plugin
2017-11-22 12:18:52 +01:00
Yifeng Wang
3fae022320 Update CONTRIBUTING.md (#6868) 2017-11-22 10:47:06 +01:00
Henry Zhu
70361f1200 Remove the experimental folder 2017-11-21 20:03:16 -05:00
Artem Yavorsky
d72d567d43 Merge pull request #6866 from aaharu/reduce-preset-env-pkg-size
Add `.github` and `.idea` to `.npmignore` for babel-preset-env.
2017-11-21 21:06:52 +02:00
aaharu
4a455639e7 Add .github and .idea to .npmignore 2017-11-22 02:22:55 +09:00
Mauro Bringolf
ba441c5ce4 Define readOnlyError helper and use in check-constants plugin 2017-11-20 16:41:15 +01:00
Daniel Tschinder
7064b298d7 Make SpreadProperty and RestProperty a deprecatedAlias (#6853)
instead of hardcoding backwards compatiblity.
This way we get deprecation warnings and also builders will work.
2017-11-18 21:54:24 +01:00
Daniel Tschinder
f3004d0d4d Fix validation of WithStatement and enable flow in definitions (#6852)
Fixes also flow errors after activating flow
2017-11-18 18:17:31 +01:00
Vincent Chan
037b2025a6 description about building and testing babylon in CONTRIBUTING.md (#6756)
developers maybe confuse about the steps of building and testings in the mono project
2017-11-18 12:57:58 +01:00
Darío Hereñú
7d534dc32c Minor fix (styling) (#6849) [skip ci] 2017-11-18 06:51:44 +01:00
Anatoli Papirovski
2b710d0387 Do not access out of bounds arguments (#6792)
Potentially out of bounds arguments should not just be directly
accessed, instead use a ternary operator to check length.
2017-11-17 21:39:08 +01:00
Kevin Ji
e67cfc5b31 README: Use HTTPS and relative links when possible [skip ci] (#6843) 2017-11-17 10:34:44 -05:00
Sven SAULEAU
4552ee9962 Merge pull request #6844 from nicolo-ribaudo/babyon-watch
Add "make watch-babylon" [skip ci]
2017-11-17 14:16:32 +01:00
Nicolò Ribaudo
3c64554716 Add "make watch-babylon" [skip ci] 2017-11-17 09:50:46 +01:00
Steven Hargrove
cee9ae48e0 [skip ci] removed shorthand usage of official babel scoped presets & plugins from README.md's (#6820) 2017-11-16 22:51:23 -05:00
Logan Smyth
39dae28d5c Add missing argument and remove nonexistent one. (#6842) 2017-11-16 16:32:47 -08:00
Valerii Iatsko
16e898c692 @babel/cli: removed babel-node mention in README.md [skip ci] (#6829)
Follow up to 2374062bbd
2017-11-16 18:04:10 +01:00
Sven SAULEAU
bb89364813 Merge pull request #6727 from babel/feat-use-charcode-constants
[Babylon] Use char codes contants
2017-11-16 10:35:42 +01:00
Sven SAULEAU
57e2c45cbe chore: upgrade charcode 2017-11-16 09:57:20 +01:00
Raja Sekar
63397d0aad Better error message for super when not using an object method (#6754) 2017-11-15 21:29:46 -06:00
Artem Yavorsky
48906604f2 Add safari technology preview for babel-preset-env. (#6791) 2017-11-15 17:14:54 -06:00
Brian Ng
0f2ab2fe20 Fix some reserved type handling and declare class with multiple extends (#6725) 2017-11-15 16:16:15 -06:00
Artem Yavorsky
de3597983a [preset-env] Exclude transform-typeof-symbol with loose option. (#6831) 2017-11-15 14:13:59 -06:00
Logan Smyth
aa2d415507 Expose the envName as a programmatic and CLI option. 2017-11-15 11:24:39 -08:00
Sven SAULEAU
4c584ae341 chore: upgrade and fix charcodes 2017-11-15 19:53:30 +01:00
Logan Smyth
74439889d8 Centralize envName lookup using caching sidechannel. 2017-11-15 10:05:48 -08:00
Logan Smyth
74ea70718e Allow passing an cachable 'sidechannel' object into cache handlers. 2017-11-15 10:05:47 -08:00
Logan Smyth
bbff566024 Use expanded caching API to simplify usage. 2017-11-15 09:51:13 -08:00
Logan Smyth
3942862a2a Expose more caching flexibility for Babel's internal use. 2017-11-15 09:51:12 -08:00
Brian Ng
f3fd2ee3b2 Maintain plugin order with items in the include option (#6663) 2017-11-15 10:45:16 -06:00
Marcio Junior
6a19c2299a docs: [skip-ci] Remove @babel scope from babel-preset-env include/exc… (#6825) 2017-11-15 10:25:21 -06:00
Brian Ng
6371200215 Fix preset-env test 2017-11-15 10:07:04 -06:00
Brian Ng
47d5f0c20c Update dep versions inside preset-env-standalone 2017-11-15 09:54:03 -06:00
Artem Yavorsky
262d7518bd Move babel-preset-env-standalone to the monorepo. (#6438) 2017-11-15 09:50:36 -06:00
Brian Ng
287b485d0e Fix bug in preset-env usage plugin with destructure in for-of (#6662) 2017-11-15 09:45:54 -06:00
Nicolò Ribaudo
9ae23639ad Parse async arrows with flow type parameters (#6802)
Fixes #6712
2017-11-14 16:24:14 +01:00
Brian Ng
3c359698a7 Remove unneeded .eslintrc files (#6815) [skip ci] 2017-11-13 18:12:26 -05:00
Artem Yavorsky
056a995dd8 Fix shadow variables reassignment for block scoping in loops. (#6814) 2017-11-14 00:06:32 +01:00
Henry Zhu
84fe8e4181 use pr instead of tag for changelog/prs [skip ci] (#6819) 2017-11-13 16:08:08 -05:00
Logan Smyth
e44cef3473 Merge pull request #6818 from loganfsmyth/async-warnings
Add some nice warnings if plugins happen to return promises instead of sync values.
2017-11-13 12:42:58 -08:00
Logan Smyth
44c2791849 Expose a function for plugins to check if async plugins are supported by the current compilation. 2017-11-13 11:58:31 -08:00
Logan Smyth
0e88156d0c Add warnings to places where we might allow promises to be returned in later minors. 2017-11-13 11:58:30 -08:00
Henry Zhu
394ad93d22 Update to v7-beta.31 (#6804) 2017-11-13 10:50:29 -05:00
Sven SAULEAU
82a4919c11 Merge pull request #6803 from satya164/async-to-generator-pure
Add /*#__PURE__*/ annotatiotion for babel-plugin-async-to-generator
2017-11-13 16:31:37 +01:00
Sven SAULEAU
186f04a3e9 feat: use charcodes in JSX plugin 2017-11-13 13:15:32 +01:00
Sven SAULEAU
42c740ca0a Merge branch 'master' into async-to-generator-pure 2017-11-13 11:49:16 +01:00
Satyajit Sahoo
7ae6e1e5a0 Add /*#__PURE__*/ annotatiotion for babel-plugin-async-to-generator. Fixes #6572 2017-11-12 18:31:48 +05:30
Sven SAULEAU
097ff40001 feat: more charCodes 2017-11-11 18:08:43 +01:00
Sven SAULEAU
b79e3c0e99 fix: minor changes 2017-11-09 18:07:10 +01:00
Sven SAULEAU
88c1b4ef1c feat: more charcodes 2017-11-09 17:13:36 +01:00
Sven SAULEAU
6b417a8ecb chore: bump charcode plugin 2017-11-08 16:56:25 +01:00
Sven SAULEAU
cd8a869a18 fix: remove unwanted change 2017-11-08 13:20:11 +01:00
Sven SAULEAU
f3f005c67e feat: use charcode AOT transform 2017-11-07 19:16:04 +01:00
Sven SAULEAU
7dfa79f4c8 Merge branch 'master' into feat-use-charcode-constants 2017-11-07 18:09:52 +01:00
Sven SAULEAU
3e34162092 chore: bump charcode 2017-11-07 18:07:38 +01:00
Sven SAULEAU
b93800d3cb fix: use charcode package 2017-11-03 09:52:45 +01:00
Sven SAULEAU
233e60c765 Merge branch 'master' into feat-use-charcode-constants 2017-11-03 08:52:54 +01:00
Sven SAULEAU
72a90cb63d feat: more charcodes 2017-11-03 08:51:48 +01:00
Sven SAULEAU
b51ac5e60a feat: sort by value
Vim 🖤
2017-11-03 08:27:03 +01:00
Sven SAULEAU
8b206b2c3b feat: generate charCodes
Vim 🖤
2017-11-02 20:13:44 +01:00
Sven SAULEAU
a2ed843636 feat: add more charCodes 2017-11-02 18:14:29 +01:00
Sven SAULEAU
b95810f4b4 refactor: switch to individual exports 2017-11-02 17:57:58 +01:00
Sven SAULEAU
abb4850709 refactor: use charCodes 2017-11-02 16:40:08 +01:00
Sven SAULEAU
459e289d63 feat: setup constants 2017-11-02 09:10:26 +01:00
2162 changed files with 19216 additions and 10633 deletions

View File

@@ -2,3 +2,4 @@
packages/*/test/fixtures
packages/*/lib
packages/babel-standalone/babel.js
packages/babel-preset-env-standalone/babel-preset-env.js

View File

@@ -32,7 +32,6 @@ function istanbulHacks() {
let envOpts = {
loose: true,
exclude: ["transform-typeof-symbol"],
};
const config = {
@@ -43,9 +42,9 @@ const config = {
],
plugins: [
["@babel/proposal-class-properties", { loose: true }],
"@babel/proposal-export-namespace",
"@babel/proposal-export-namespace-from",
"@babel/proposal-numeric-separator",
["@babel/proposal-object-rest-spread", { useBuiltIns: true}],
["@babel/proposal-object-rest-spread", { useBuiltIns: true }],
]
};

View File

@@ -9,3 +9,6 @@ end_of_line = lf
[*.{js,json}]
indent_style = space
indent_size = 2
[*.{md,markdown}]
trim_trailing_whitespace = false

View File

@@ -12,12 +12,10 @@ codemods/*/lib
codemods/*/dist
codemods/*/test/fixtures
codemods/*/test/tmp
experimental/*/lib
experimental/*/node_modules
experimental/*/test/fixtures
experimental/*/test/tmp
experimental/babel-preset-env/data
experimental/babel-preset-env/test/debug-fixtures
packages/babel-preset-env/data
packages/babel-preset-env/test/debug-fixtures
packages/babel-preset-env-standalone/babel-preset-env.js
packages/babel-preset-env-standalone/babel-preset-env.min.js
packages/babel-standalone/babel.js
packages/babel-standalone/babel.min.js
packages/babylon/build

View File

@@ -15,7 +15,6 @@
{
"files": [
"packages/*/src/**/*.js",
"experimental/*/src/**/*.js",
"codemods/*/src/**/*.js"
],
"rules": {
@@ -23,7 +22,11 @@
}
},
{
"files": [ "packages/*/test/**/*.js", "test/**/*.js" ],
"files": [
"packages/*/test/**/*.js",
"codemods/*/test/**/*.js",
"test/**/*.js"
],
"env": {
"mocha": true
}

View File

@@ -4,14 +4,11 @@
.*/packages/.*/test
.*/codemods/.*/lib
.*/codemods/.*/test
.*/experimental/.*/lib
.*/experimental/.*/test
.*/node_modules/conventional-changelog-core/
[include]
packages/*/src
codemods/*/src
experimental/*/src
[libs]
lib/file.js
@@ -20,6 +17,7 @@ lib/types.js
lib/third-party-libs.js.flow
[options]
include_warnings=true
suppress_comment= \\(.\\|\n\\)*\\$FlowFixMe
suppress_comment= \\(.\\|\n\\)*\\$FlowIssue
suppress_comment= \\(.\\|\n\\)*\\$FlowIgnore

3
.gitignore vendored
View File

@@ -34,6 +34,9 @@ package-lock.json
/babel.sublime-workspace
packages/babel-standalone/babel.js
packages/babel-standalone/babel.min.js
packages/babel-preset-env-standalone/babel-preset-env.js
packages/babel-preset-env-standalone/babel-preset-env.min.js
/codemods/*/lib
/codemods/*/node_modules
/packages/babylon/build
.idea/

View File

@@ -2,8 +2,6 @@
"trailingComma": "es5",
"overrides": [{
"files": [
"**/experimental/*/src/**/*.js",
"**/experimental/*/test/**/*.js",
"**/codemods/*/src/**/*.js",
"**/codemods/*/test/**/*.js",
"**/packages/*/src/**/*.js",

View File

@@ -24,7 +24,7 @@ contributing, please read the
## Not sure where to start?
- If you aren't just making a documentation change, you'll probably want to learn a bit about a few topics.
- [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (Abstract Syntax Tree): The Babel AST [spec](https://github.com/babel/babel/tree/master/packages/babylon/blob/master/ast/spec.md) is a bit different from [ESTree](https://github.com/estree/estree). The differences are listed [here](https://github.com/babel/babel/tree/master/packages/babylon#output).
- [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (Abstract Syntax Tree): The Babel AST [spec](https://github.com/babel/babel/blob/master/packages/babylon/ast/spec.md) is a bit different from [ESTree](https://github.com/estree/estree). The differences are listed [here](https://github.com/babel/babel/tree/master/packages/babylon#output).
- Check out [`/doc`](https://github.com/babel/babel/tree/master/doc) for information about Babel's internals
- Check out [the Babel Plugin Handbook](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-plugin-handbook) - core plugins are written the same way as any other plugin!
- Check out [AST Explorer](http://astexplorer.net/#/scUfOmVOG5) to learn more about ASTs or make your own plugin in the browser
@@ -115,7 +115,7 @@ $ TEST_ONLY=babel-cli make test
`TEST_ONLY` will also match substrings of the package name:
```sh
# Run tests for the babel-plugin-transform-classes package.
# Run tests for the @babel/plugin-transform-classes package.
$ TEST_ONLY=es2015-class make test
```
@@ -161,16 +161,16 @@ In case you're locally getting errors which are not on the CI, it may be due to
Most packages in [`/packages`](https://github.com/babel/babel/tree/master/packages) have a `test` folder, however some tests might be in other packages or in [`/packages/babel-core`](https://github.com/babel/babel/tree/master/packages/babel-core/test/fixtures).
#### `babel-plugin-x`
#### `@babel/plugin-x`
All the Babel plugins (and other packages) that have a `/test/fixtures` are written in a similar way.
For example, in [`babel-plugin-transform-exponentiation-operator/test`](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-exponentiation-operator/test):
For example, in [`@babel/plugin-transform-exponentiation-operator/test`](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-exponentiation-operator/test):
- There is an `index.js` file. It imports our [test helper](https://github.com/babel/babel/tree/master/packages/babel-helper-plugin-test-runner). (You don't have to worry about this).
- There can be multiple folders under [`/fixtures`](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures)
- There is an [`options.json`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/options.json) file whose function is similar to a `.babelrc` file, allowing you to pass in the plugins and settings you need for your tests.
- For this test, we only need the relevant plugin, so it's just `{ "plugins": ["@babel/transform-exponentiation-operator"] }`.
- For this test, we only need the relevant plugin, so it's just `{ "plugins": ["@babel/plugin-transform-exponentiation-operator"] }`.
- If necessary, you can have an `options.json` with different options in each subfolder.
- In each subfolder, you can organize your directory structure by categories of tests. (Example: these folders can be named after the feature you are testing or can reference the issue number they fix)
@@ -205,8 +205,8 @@ If you need to check for an error that is thrown you can add to the `options.jso
```js
// options.json example
{
"plugins": [["@babel/proposal-object-rest-spread", { "useBuiltIns": "invalidOption" }]],
"throws": "@babel/proposal-object-rest-spread currently only accepts a boolean option for useBuiltIns (defaults to false)"
"plugins": [["@babel/plugin-proposal-object-rest-spread", { "useBuiltIns": "invalidOption" }]],
"throws": "@babel/plugin-proposal-object-rest-spread currently only accepts a boolean option for useBuiltIns (defaults to false)"
}
```
@@ -231,9 +231,21 @@ descriptive name, and add the following:
* Add an `expected.json` file with the expected parser output. For added convenience, if there is no `expected.json` present, the test runner will generate one for you.
After writing tests for babylon, just build it by running:
```sh
$ make build-babylon
```
Then, to run the tests, use:
```sh
$ TEST_ONLY=babylon make test-only
```
#### Bootstrapping expected output
For both `babel-plugin-x` and `babylon`, you can easily generate an `expected.js`/`expected.json` automatically by just providing `actual.js` and running the tests as you usually would.
For both `@babel/plugin-x` and `babylon`, you can easily generate an `expected.js`/`expected.json` automatically by just providing `actual.js` and running the tests as you usually would.
```
// Example
@@ -267,7 +279,7 @@ To include the changes, we have to make sure to build Babel:
$ make build
```
Next, we need to execute `Generator.generate()`, which can be achieved by running a test case in the `babel-generator` package.
Next, we need to execute `Generator.generate()`, which can be achieved by running a test case in the `@babel/generator` package.
For example, we can run the test case that tests the generation of class declarations:
```bash
@@ -275,7 +287,6 @@ $ TEST_DEBUG=true TEST_GREP=ClassDeclaration make test-only
./scripts/test.sh
Debugger listening on port 9229.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/3cdaebd2-be88-4e7b-a94b-432950ab72d0
```
@@ -298,8 +309,8 @@ Note that the code shown in Chrome DevTools is compiled code and therefore diffe
- Start working about the Babel transform itself!
## Internals
- AST spec ([babylon/ast/spec.md](https://github.com/babel/babel/tree/master/packages/babylon/blob/master/ast/spec.md))
- Versioning ([doc/design/versioning.md](https://github.com/babel/babel/blob/master/doc/design/versioning.md)
- AST spec ([babylon/ast/spec.md](https://github.com/babel/babel/blob/master/packages/babylon/ast/spec.md))
- Versioning ([doc/design/versioning.md](https://github.com/babel/babel/blob/master/doc/design/versioning.md))
- Monorepo ([doc/design/monorepo.md](https://github.com/babel/babel/blob/master/doc/design/monorepo.md))
- Compiler environment support ([doc/design/compiler-environment-support.md](https://github.com/babel/babel/blob/master/doc/design/compiler-environment-support.md))
- Compiler assumptions ([doc/design/compiler-assumptions.md](https://github.com/babel/babel/blob/master/doc/design/compiler-assumptions.md))

View File

@@ -3,9 +3,6 @@
const plumber = require("gulp-plumber");
const through = require("through2");
const chalk = require("chalk");
const pump = require("pump");
const uglify = require("gulp-uglify");
const rename = require("gulp-rename");
const newer = require("gulp-newer");
const babel = require("gulp-babel");
const watch = require("gulp-watch");
@@ -13,13 +10,12 @@ const gutil = require("gulp-util");
const filter = require("gulp-filter");
const gulp = require("gulp");
const path = require("path");
const merge = require("merge-stream");
const RootMostResolvePlugin = require("webpack-dependency-suite")
.RootMostResolvePlugin;
const webpack = require("webpack");
const webpackStream = require("webpack-stream");
const merge = require("merge-stream");
const registerStandalonePackageTask = require("./scripts/gulp-tasks")
.registerStandalonePackageTask;
const sources = ["codemods", "packages", "experimental"];
const sources = ["codemods", "packages"];
function swapSrcWithLib(srcPath) {
const parts = srcPath.split(path.sep);
@@ -81,114 +77,40 @@ gulp.task("watch", ["build"], function() {
});
});
gulp.task("build-babel-standalone", cb => {
pump(
[
gulp.src(__dirname + "/packages/babel-standalone/src/index.js"),
webpackBuild(),
gulp.dest(__dirname + "/packages/babel-standalone"),
uglify(),
rename({ extname: ".min.js" }),
gulp.dest(__dirname + "/packages/babel-standalone"),
],
cb
);
});
registerStandalonePackageTask(
gulp,
"babel",
"Babel",
path.join(__dirname, "packages"),
require("./packages/babel-core/package.json").version
);
function webpackBuild() {
let version = require("./packages/babel-core/package.json").version;
const presetEnvWebpackPlugins = [
new webpack.NormalModuleReplacementPlugin(
/\.\/available-plugins/,
require.resolve(
path.join(
__dirname,
"./packages/babel-preset-env-standalone/src/available-plugins"
)
)
),
new webpack.NormalModuleReplacementPlugin(
/caniuse-lite\/data\/regions\/.+/,
require.resolve(
path.join(
__dirname,
"./packages/babel-preset-env-standalone/src/caniuse-lite-regions"
)
)
),
];
// If this build is part of a pull request, include the pull request number in
// the version number.
if (process.env.CIRCLE_PR_NUMBER) {
version += "+pr." + process.env.CIRCLE_PR_NUMBER;
}
const config = {
module: {
rules: [
{
test: /\.js$/,
include: /node_modules/,
loader: "babel-loader",
options: {
// Some of the node_modules may have their own "babel" section in
// their project.json (or a ".babelrc" file). We need to ignore
// those as we're using our own Babel options.
babelrc: false,
presets: [
[
"@babel/env",
{
loose: true,
exclude: ["transform-typeof-symbol"],
},
],
],
},
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
// Some of the node_modules may have their own "babel" section in
// their project.json (or a ".babelrc" file). We need to ignore
// those as we're using our own Babel options.
babelrc: false,
presets: [
[
"@babel/env",
{
loose: true,
exclude: ["transform-typeof-symbol"],
},
],
["@babel/stage-0", { loose: true }],
],
},
},
],
// babylon is already bundled and does not require parsing
noParse: [/babylon\/lib/],
},
node: {
// Mock Node.js modules that Babel require()s but that we don't
// particularly care about.
fs: "empty",
module: "empty",
net: "empty",
},
output: {
filename: "babel.js",
library: "Babel",
libraryTarget: "umd",
},
plugins: [
new webpack.DefinePlugin({
"process.env.NODE_ENV": '"production"',
BABEL_VERSION: JSON.stringify(version),
VERSION: JSON.stringify(version),
}),
/*new webpack.NormalModuleReplacementPlugin(
/..\/..\/package/,
"../../../../src/babel-package-shim"
),*/
new webpack.optimize.ModuleConcatenationPlugin(),
],
resolve: {
plugins: [
// Dedupe packages that are used across multiple plugins.
// This replaces DedupePlugin from Webpack 1.x
new RootMostResolvePlugin(__dirname, true),
],
},
};
return webpackStream(config, webpack);
// To write JSON for debugging:
/*return webpackStream(config, webpack, (err, stats) => {
require('gulp-util').log(stats.toString({colors: true}));
require('fs').writeFileSync('webpack-debug.json', JSON.stringify(stats.toJson()));
});*/
}
registerStandalonePackageTask(
gulp,
"babel-preset-env",
"babelPresetEnv",
path.join(__dirname, "packages"),
require("./packages/babel-preset-env/package.json").version,
presetEnvWebpackPlugins
);

View File

@@ -1,5 +1,5 @@
MAKEFLAGS = -j1
FLOW_COMMIT = 4cc2b9f7fadf2e9e445ee9b7b980c65d69d3fbc0
FLOW_COMMIT = 622bbc4f07acb77eb1109830c70815f827401d90
TEST262_COMMIT = 1282e842febf418ca27df13fa4b32f7e5021b470
export NODE_ENV = test
@@ -7,7 +7,7 @@ export NODE_ENV = test
# Fix color output until TravisCI fixes https://github.com/travis-ci/travis-ci/issues/7967
export FORCE_COLOR = true
SOURCES = packages codemods experimental
SOURCES = packages codemods
.PHONY: build build-dist watch lint fix clean test-clean test-only test test-ci publish bootstrap
@@ -16,8 +16,12 @@ build: clean
# Build babylon before building all other projects
make build-babylon
./node_modules/.bin/gulp build
node ./packages/babel-types/scripts/generateTypeHelpers.js
# call build again as the generated files might need to be compiled again.
./node_modules/.bin/gulp build
ifneq ("$(BABEL_ENV)", "cov")
make build-standalone
make build-preset-env-standalone
endif
build-babylon:
@@ -27,6 +31,9 @@ build-babylon:
build-standalone:
./node_modules/.bin/gulp build-babel-standalone
build-preset-env-standalone:
./node_modules/.bin/gulp build-babel-preset-env-standalone
build-dist: build
cd packages/babel-polyfill; \
scripts/build-dist.sh
@@ -38,6 +45,10 @@ watch: clean
make clean-lib
BABEL_ENV=development ./node_modules/.bin/gulp watch
watch-babylon:
cd packages/babylon; \
./node_modules/.bin/rollup -c -w
flow:
./node_modules/.bin/flow check --strip-root
@@ -50,8 +61,6 @@ fix:
clean: test-clean
rm -rf packages/babel-polyfill/browser*
rm -rf packages/babel-polyfill/dist
# rm -rf packages/babel-runtime/helpers
# rm -rf packages/babel-runtime/core-js
rm -rf coverage
rm -rf packages/*/npm-debug*
@@ -110,6 +119,8 @@ test-test262-update-whitelist:
publish:
git pull --rebase
make clean-lib
rm -rf packages/babel-runtime/helpers
rm -rf packages/babel-runtime/core-js
BABEL_ENV=production make build-dist
make test
# not using lerna independent mode atm, so only update packages that have changed since we use ^

116
README.md
View File

@@ -24,9 +24,9 @@
<a href="https://medium.com/friendship-dot-js/i-peeked-into-my-node-modules-directory-and-you-wont-believe-what-happened-next-b89f63d21558"><img alt="Business Strategy Status" src="https://img.shields.io/badge/business%20model-flavortown-green.svg"></a>
</p>
Babel is community-driven and thus mostly maintained by a group of [volunteers](https://babeljs.io/team). It has a lot of [companies and projects](http://babeljs.io/users) using it but almost no sponsors/people funded to work on it. If you'd like to help maintain the future of the project, please consider:
Babel is community-driven and thus mostly maintained by a group of [volunteers](https://babeljs.io/team). It has a lot of [companies and projects](https://babeljs.io/users) using it but almost no sponsors/people funded to work on it. If you'd like to help maintain the future of the project, please consider:
- Giving developer time on the project. (Message us on [Twitter](https://twitter.com/babeljs) or [Slack](slack.babeljs.io))
- Giving developer time on the project. (Message us on [Twitter](https://twitter.com/babeljs) or [Slack](https://slack.babeljs.io/))
- [Giving funds by becoming a backer/sponsor on OpenCollective](https://opencollective.com/babel)
## Intro
@@ -63,19 +63,23 @@ Mostly a handful of volunteers! Please check out our [team page](https://babeljs
### Looking for support?
For questions and support please visit join our [Slack Community](https://slack.babeljs.io/), ask a question on [Stack Overflow](http://stackoverflow.com/questions/tagged/babeljs), or ping us on [Twitter](https://twitter.com/babeljs/).
For questions and support please visit join our [Slack Community](https://slack.babeljs.io/), ask a question on [Stack Overflow](https://stackoverflow.com/questions/tagged/babeljs), or ping us on [Twitter](https://twitter.com/babeljs).
### Is there a Babel song?
I'm so glad you asked: [Hallelujah —— In Praise of Babel](SONG.md) by [@angus-c](https://github.com/angus-c). Tweet us your recordings!
### Where are the docs?
Check out our website: [babeljs.io](http://babeljs.io/), and report issues/features at [babel/website](https://github.com/babel/website/issues).
Check out our website: [babeljs.io](https://babeljs.io/), and report issues/features at [babel/website](https://github.com/babel/website/issues).
### Want to report a bug or request a feature?
Please read through our [CONTRIBUTING.md](https://github.com/babel/babel/blob/master/CONTRIBUTING.md) and fill out the issue template at [babel/issues](https://github.com/babel/babel/issues)!
Please read through our [CONTRIBUTING.md](CONTRIBUTING.md) and fill out the issue template at [babel/issues](https://github.com/babel/babel/issues)!
### Want to contribute to Babel?
Check out our [CONTRIBUTING.md](https://github.com/babel/babel/blob/master/CONTRIBUTING.md) to get started with setting up the repo.
Check out our [CONTRIBUTING.md](CONTRIBUTING.md) to get started with setting up the repo.
- If you have already joined Slack, join our [#development](https://babeljs.slack.com/messages/development) channel and say hi!
- Check out the issues with the [good first issue](https://github.com/babel/babel/labels/good%20first%20issue) and [help wanted](https://github.com/babel/babel/labels/help%20wanted) label. We suggest also looking at the closed ones to get a sense of the kinds of issues you can tackle.
@@ -84,7 +88,7 @@ Check out our [CONTRIBUTING.md](https://github.com/babel/babel/blob/master/CONTR
### How is the repo structured?
The Babel repo is managed as a [monorepo](https://github.com/babel/babel/blob/master/doc/design/monorepo.md) that is composed of many [npm packages](/packages#readme).
The Babel repo is managed as a [monorepo](doc/design/monorepo.md) that is composed of many [npm packages](packages/README.md).
## Backers
@@ -95,30 +99,30 @@ Support us with a monthly donation and help us continue our activities. [[Become
<a href="https://opencollective.com/babel/backer/2/website" target="_blank"><img src="https://opencollective.com/babel/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/3/website" target="_blank"><img src="https://opencollective.com/babel/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/4/website" target="_blank"><img src="https://opencollective.com/babel/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/5/website" target="_blank"><img src="https://opencollective.com/babel/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/6/website" target="_blank"><img src="https://opencollective.com/babel/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/7/website" target="_blank"><img src="https://opencollective.com/babel/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/8/website" target="_blank"><img src="https://opencollective.com/babel/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/9/website" target="_blank"><img src="https://opencollective.com/babel/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/10/website" target="_blank"><img src="https://opencollective.com/babel/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/11/website" target="_blank"><img src="https://opencollective.com/babel/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/12/website" target="_blank"><img src="https://opencollective.com/babel/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/13/website" target="_blank"><img src="https://opencollective.com/babel/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/14/website" target="_blank"><img src="https://opencollective.com/babel/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/15/website" target="_blank"><img src="https://opencollective.com/babel/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/16/website" target="_blank"><img src="https://opencollective.com/babel/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/17/website" target="_blank"><img src="https://opencollective.com/babel/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/18/website" target="_blank"><img src="https://opencollective.com/babel/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/19/website" target="_blank"><img src="https://opencollective.com/babel/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/20/website" target="_blank"><img src="https://opencollective.com/babel/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/21/website" target="_blank"><img src="https://opencollective.com/babel/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/22/website" target="_blank"><img src="https://opencollective.com/babel/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/23/website" target="_blank"><img src="https://opencollective.com/babel/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/24/website" target="_blank"><img src="https://opencollective.com/babel/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/25/website" target="_blank"><img src="https://opencollective.com/babel/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/26/website" target="_blank"><img src="https://opencollective.com/babel/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/27/website" target="_blank"><img src="https://opencollective.com/babel/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/28/website" target="_blank"><img src="https://opencollective.com/babel/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/5/website" target="_blank"><img src="https://opencollective.com/babel/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/6/website" target="_blank"><img src="https://opencollective.com/babel/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/7/website" target="_blank"><img src="https://opencollective.com/babel/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/8/website" target="_blank"><img src="https://opencollective.com/babel/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/9/website" target="_blank"><img src="https://opencollective.com/babel/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/10/website" target="_blank"><img src="https://opencollective.com/babel/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/11/website" target="_blank"><img src="https://opencollective.com/babel/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/12/website" target="_blank"><img src="https://opencollective.com/babel/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/13/website" target="_blank"><img src="https://opencollective.com/babel/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/14/website" target="_blank"><img src="https://opencollective.com/babel/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/15/website" target="_blank"><img src="https://opencollective.com/babel/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/16/website" target="_blank"><img src="https://opencollective.com/babel/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/17/website" target="_blank"><img src="https://opencollective.com/babel/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/18/website" target="_blank"><img src="https://opencollective.com/babel/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/19/website" target="_blank"><img src="https://opencollective.com/babel/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/20/website" target="_blank"><img src="https://opencollective.com/babel/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/21/website" target="_blank"><img src="https://opencollective.com/babel/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/22/website" target="_blank"><img src="https://opencollective.com/babel/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/23/website" target="_blank"><img src="https://opencollective.com/babel/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/24/website" target="_blank"><img src="https://opencollective.com/babel/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/25/website" target="_blank"><img src="https://opencollective.com/babel/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/26/website" target="_blank"><img src="https://opencollective.com/babel/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/27/website" target="_blank"><img src="https://opencollective.com/babel/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/28/website" target="_blank"><img src="https://opencollective.com/babel/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/babel/backer/29/website" target="_blank"><img src="https://opencollective.com/babel/backer/29/avatar.svg"></a>
## Sponsors
@@ -130,32 +134,32 @@ Become a sponsor and get your logo on our README on Github with a link to your s
<a href="https://opencollective.com/babel/sponsor/2/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/3/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/4/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/5/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/6/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/7/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/8/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/9/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/10/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/11/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/12/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/13/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/14/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/15/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/16/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/17/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/18/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/19/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/20/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/21/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/22/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/23/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/24/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/25/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/26/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/27/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/28/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/5/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/6/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/7/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/8/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/9/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/10/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/11/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/12/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/13/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/14/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/15/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/16/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/17/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/18/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/19/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/20/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/21/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/22/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/23/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/24/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/25/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/26/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/27/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/28/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/babel/sponsor/29/website" target="_blank"><img src="https://opencollective.com/babel/sponsor/29/avatar.svg"></a>
## License
[MIT](https://github.com/babel/babel/blob/master/LICENSE)
[MIT](LICENSE)

67
SONG.md Normal file
View File

@@ -0,0 +1,67 @@
## Hallelujah—In Praise of Babel
I heard there was a clever trick
That rewrote all your JavaScript
But you dont really care for magic, do you
Well it goes like this: the source, the dist
The ES five, the ES six
The sacred script transforming Hallelujah
Hallelujah, Hallelujah
Hallelujah, Hallelujah
So I added all the shiny things
Classes, spreads and template strings
Through syntax sugared code I tried to woo you
Generators, const and let
I used them all without regret
And its a terse and a destructured Hallelujah
Hallelujah etc.
Well my faith was strong but I needed proof
The standard was my source of truth
But TC39 meant nothing to you
So even though you werent impressed
I checked the build against the spec
And its a more-or-less compliant Hallelujah
Hallelujah etc.
Now you say the build steps too complex
And you claim no need for ES Next
Well I used to think that way before I knew you
But your code grows older with each line
Its a joyless dirge on a withered vine
Its a threnody for a bygone Hallelujah
Hallelujah etc.
Yes I learned about the danger signs
How theyd polyfilled a thousand lines
The cost of using Maps and Symbols threw you
Still I disregarded common sense
Now my source is small but the builds immense
And its a slow and unresponsive Hallelujah
Hallelujah etc.
There was a time when they let me know
Whats really going on below
But now theres only source maps there to school you
And debuggings not a progress march
Its a frenzied fumble in the dark
Its a labyrinthine search for Hallelujah
Hallelujah etc.
Well, maybe theres a god up there
But all I ever got from prayers
Was broken builds and errors that would spook you
And that anguished cry you hear at night
Is the plugin I forgot to write
Its a cold and its a broken Hallelujah
Hallelujah etc.
[Angus Croll](https://github.com/angus-c)

View File

@@ -2,6 +2,8 @@ general:
artifacts:
- "packages/babel-standalone/babel.js"
- "packages/babel-standalone/babel.min.js"
- "packages/babel-preset-env-standalone/babel-preset-env.js"
- "packages/babel-preset-env-standalone/babel-preset-env.min.js"
machine:
node:
@@ -25,3 +27,4 @@ test:
# data for a JS file that's several megabytes large is bound to fail. Here,
# we just run the babel-standalone test separately.
- ./node_modules/mocha/bin/_mocha packages/babel-standalone/test/ --opts test/mocha.opts
- ./node_modules/mocha/bin/_mocha packages/babel-preset-env-standalone/test/ --opts test/mocha.opts

View File

@@ -1,6 +0,0 @@
{
"rules": {
"prettier/prettier": ["error", { "trailingComma": "all" }],
"no-undefined-identifier": 2
}
}

View File

@@ -36,21 +36,21 @@ npm install --save-dev @babel/plugin-codemod-optional-catch-binding
```json
{
"plugins": ["@babel/codemod-optional-catch-binding"]
"plugins": ["@babel/plugin-codemod-optional-catch-binding"]
}
```
### Via CLI
```sh
babel --plugins @babel/codemod-optional-catch-binding script.js
babel --plugins @babel/plugin-codemod-optional-catch-binding script.js
```
### Via Node API
```javascript
require("@babel/core").transform("code", {
plugins: ["@babel/codemod-optional-catch-binding"]
plugins: ["@babel/plugin-codemod-optional-catch-binding"]
});
```

View File

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

View File

@@ -1,6 +0,0 @@
{
"rules": {
"prettier/prettier": ["error", { "trailingComma": "all" }],
"no-undefined-identifier": 2
}
}

View File

@@ -1,6 +0,0 @@
/lib
debug-fixtures
fixtures
/data
/flow-typed
test/tmp

View File

@@ -1,63 +0,0 @@
{
"name": "@babel/preset-env",
"version": "7.0.0-beta.32",
"description": "A Babel preset for each environment.",
"author": "Henry Zhu <hi@henryzoo.com>",
"homepage": "https://babeljs.io/",
"license": "MIT",
"repository": "https://github.com/babel/babel/tree/master/experimental/babel-preset-env",
"main": "lib/index.js",
"scripts": {
"build-data": "node ./scripts/build-data.js"
},
"dependencies": {
"@babel/plugin-check-constants": "7.0.0-beta.32",
"@babel/plugin-proposal-async-generator-functions": "7.0.0-beta.32",
"@babel/plugin-proposal-object-rest-spread": "7.0.0-beta.32",
"@babel/plugin-proposal-optional-catch-binding": "7.0.0-beta.32",
"@babel/plugin-proposal-unicode-property-regex": "7.0.0-beta.32",
"@babel/plugin-syntax-async-generators": "7.0.0-beta.32",
"@babel/plugin-syntax-object-rest-spread": "7.0.0-beta.32",
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.32",
"@babel/plugin-transform-arrow-functions": "7.0.0-beta.32",
"@babel/plugin-transform-async-to-generator": "7.0.0-beta.32",
"@babel/plugin-transform-block-scoped-functions": "7.0.0-beta.32",
"@babel/plugin-transform-block-scoping": "7.0.0-beta.32",
"@babel/plugin-transform-classes": "7.0.0-beta.32",
"@babel/plugin-transform-computed-properties": "7.0.0-beta.32",
"@babel/plugin-transform-destructuring": "7.0.0-beta.32",
"@babel/plugin-transform-duplicate-keys": "7.0.0-beta.32",
"@babel/plugin-transform-exponentiation-operator": "7.0.0-beta.32",
"@babel/plugin-transform-for-of": "7.0.0-beta.32",
"@babel/plugin-transform-function-name": "7.0.0-beta.32",
"@babel/plugin-transform-literals": "7.0.0-beta.32",
"@babel/plugin-transform-modules-amd": "7.0.0-beta.32",
"@babel/plugin-transform-modules-commonjs": "7.0.0-beta.32",
"@babel/plugin-transform-modules-systemjs": "7.0.0-beta.32",
"@babel/plugin-transform-modules-umd": "7.0.0-beta.32",
"@babel/plugin-transform-new-target": "7.0.0-beta.32",
"@babel/plugin-transform-object-super": "7.0.0-beta.32",
"@babel/plugin-transform-parameters": "7.0.0-beta.32",
"@babel/plugin-transform-regenerator": "7.0.0-beta.32",
"@babel/plugin-transform-shorthand-properties": "7.0.0-beta.32",
"@babel/plugin-transform-spread": "7.0.0-beta.32",
"@babel/plugin-transform-sticky-regex": "7.0.0-beta.32",
"@babel/plugin-transform-template-literals": "7.0.0-beta.32",
"@babel/plugin-transform-typeof-symbol": "7.0.0-beta.32",
"@babel/plugin-transform-unicode-regex": "7.0.0-beta.32",
"browserslist": "^2.4.0",
"invariant": "^2.2.2",
"semver": "^5.3.0"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.32"
},
"devDependencies": {
"@babel/cli": "7.0.0-beta.32",
"@babel/core": "7.0.0-beta.32",
"@babel/helper-fixtures": "7.0.0-beta.32",
"@babel/helper-plugin-test-runner": "7.0.0-beta.32",
"compat-table": "kangax/compat-table#957f1ff15972e8fb2892a172f985e9af27bf1c75",
"electron-to-chromium": "^1.3.27"
}
}

View File

@@ -1,5 +0,0 @@
{
"rules": {
"prettier/prettier": ["error", { "trailingComma": "es5" }]
}
}

View File

@@ -1,8 +0,0 @@
{
"env": {
"mocha": true
},
"rules": {
"max-len": 0
}
}

View File

@@ -1,5 +0,0 @@
"use strict";
var _a = _interopRequireDefault(require("a"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

View File

@@ -1 +0,0 @@
import a from "a";

View File

@@ -1,16 +1,16 @@
{
"lerna": "2.0.0-rc.4",
"version": "7.0.0-beta.32",
"version": "7.0.0-beta.36",
"changelog": {
"repo": "babel/babel",
"labels": {
"Tag: Spec Compliancy": ":eyeglasses: Spec Compliancy",
"Tag: Breaking Change": ":boom: Breaking Change",
"Tag: New Feature": ":rocket: New Feature",
"Tag: Bug Fix": ":bug: Bug Fix",
"Tag: Polish": ":nail_care: Polish",
"Tag: Docs": ":memo: Documentation",
"Tag: Internal": ":house: Internal"
"PR: Spec Compliancy": ":eyeglasses: Spec Compliancy",
"PR: Breaking Change": ":boom: Breaking Change",
"PR: New Feature": ":rocket: New Feature",
"PR: Bug Fix": ":bug: Bug Fix",
"PR: Polish": ":nail_care: Polish",
"PR: Docs": ":memo: Documentation",
"PR: Internal": ":house: Internal"
}
},
"cacheDir": ".changelog",
@@ -19,15 +19,13 @@
"ignore": [
"*.md",
"test/**",
"codemods/**",
"experimental/**"
"codemods/**"
]
}
},
"packages": [
"packages/*",
"codemods/*",
"experimental/*"
"codemods/*"
],
"npmClient": "yarn",
"npmClientArgs": [

View File

@@ -82,7 +82,7 @@ declare class BabelNodeCallExpression extends BabelNode {
callee: BabelNodeExpression;
arguments: any;
optional?: true | false;
typeParameters?: ?BabelNodeTypeParameterInstantiation;
typeParameters?: ?BabelNodeTypeParameterInstantiation | BabelNodeTSTypeParameterInstantiation;
}
declare class BabelNodeCatchClause extends BabelNode {
@@ -153,7 +153,7 @@ declare class BabelNodeFunctionDeclaration extends BabelNode {
async?: boolean;
declare?: boolean;
returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop;
}
declare class BabelNodeFunctionExpression extends BabelNode {
@@ -164,7 +164,7 @@ declare class BabelNodeFunctionExpression extends BabelNode {
generator?: boolean;
async?: boolean;
returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop;
}
declare class BabelNodeIdentifier extends BabelNode {
@@ -233,7 +233,7 @@ declare class BabelNodeNewExpression extends BabelNode {
callee: BabelNodeExpression;
arguments: any;
optional?: true | false;
typeParameters?: ?BabelNodeTypeParameterInstantiation;
typeParameters?: ?BabelNodeTypeParameterInstantiation | BabelNodeTSTypeParameterInstantiation;
}
declare class BabelNodeProgram extends BabelNode {
@@ -260,7 +260,7 @@ declare class BabelNodeObjectMethod extends BabelNode {
decorators?: any;
generator?: boolean;
returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop;
}
declare class BabelNodeObjectProperty extends BabelNode {
@@ -352,7 +352,7 @@ declare class BabelNodeWhileStatement extends BabelNode {
declare class BabelNodeWithStatement extends BabelNode {
type: "WithStatement";
object: any;
object: BabelNodeExpression;
body: BabelNodeBlockStatement | BabelNodeStatement;
}
@@ -379,7 +379,7 @@ declare class BabelNodeArrowFunctionExpression extends BabelNode {
expression?: boolean;
generator?: boolean;
returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop;
}
declare class BabelNodeClassBody extends BabelNode {
@@ -396,8 +396,8 @@ declare class BabelNodeClassDeclaration extends BabelNode {
abstract?: boolean;
declare?: boolean;
mixins?: any;
superTypeParameters?: ?BabelNodeTypeParameterInstantiation;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop;
superTypeParameters?: ?BabelNodeTypeParameterInstantiation | BabelNodeTSTypeParameterInstantiation;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop;
}
declare class BabelNodeClassExpression extends BabelNode {
@@ -407,8 +407,8 @@ declare class BabelNodeClassExpression extends BabelNode {
body: BabelNodeClassBody;
decorators?: any;
mixins?: any;
superTypeParameters?: ?BabelNodeTypeParameterInstantiation;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop;
superTypeParameters?: ?BabelNodeTypeParameterInstantiation | BabelNodeTSTypeParameterInstantiation;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop;
}
declare class BabelNodeExportAllDeclaration extends BabelNode {
@@ -485,7 +485,7 @@ declare class BabelNodeClassMethod extends BabelNode {
generator?: boolean;
optional?: boolean;
returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop;
}
declare class BabelNodeObjectPattern extends BabelNode {
@@ -800,7 +800,7 @@ declare class BabelNodeVoidTypeAnnotation extends BabelNode {
declare class BabelNodeJSXAttribute extends BabelNode {
type: "JSXAttribute";
name: BabelNodeJSXIdentifier | BabelNodeJSXNamespacedName;
value?: ?BabelNodeJSXElement | BabelNodeStringLiteral | BabelNodeJSXExpressionContainer;
value?: ?BabelNodeJSXElement | BabelNodeJSXFragment | BabelNodeStringLiteral | BabelNodeJSXExpressionContainer;
}
declare class BabelNodeJSXClosingElement extends BabelNode {
@@ -864,6 +864,21 @@ declare class BabelNodeJSXText extends BabelNode {
value: string;
}
declare class BabelNodeJSXFragment extends BabelNode {
type: "JSXFragment";
openingFragment: BabelNodeJSXOpeningFragment;
closingFragment: BabelNodeJSXClosingFragment;
children: any;
}
declare class BabelNodeJSXOpeningFragment extends BabelNode {
type: "JSXOpeningFragment";
}
declare class BabelNodeJSXClosingFragment extends BabelNode {
type: "JSXClosingFragment";
}
declare class BabelNodeNoop extends BabelNode {
type: "Noop";
}
@@ -931,9 +946,9 @@ declare class BabelNodeTSParameterProperty extends BabelNode {
declare class BabelNodeTSDeclareFunction extends BabelNode {
type: "TSDeclareFunction";
id?: ?BabelNodeIdentifier;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop;
typeParameters?: ?BabelNodeTSTypeParameterDeclaration | BabelNodeNoop;
params: any;
returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop;
returnType?: ?BabelNodeTSTypeAnnotation | BabelNodeNoop;
async?: boolean;
declare?: boolean;
generator?: boolean;
@@ -943,9 +958,9 @@ declare class BabelNodeTSDeclareMethod extends BabelNode {
type: "TSDeclareMethod";
decorators?: any;
key: any;
typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop;
typeParameters?: ?BabelNodeTSTypeParameterDeclaration | BabelNodeNoop;
params: any;
returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop;
returnType?: ?BabelNodeTSTypeAnnotation | BabelNodeNoop;
abstract?: boolean;
access?: any;
accessibility?: any;
@@ -964,14 +979,14 @@ declare class BabelNodeTSQualifiedName extends BabelNode {
declare class BabelNodeTSCallSignatureDeclaration extends BabelNode {
type: "TSCallSignatureDeclaration";
typeParameters?: ?BabelNodeTypeParameterDeclaration;
typeParameters?: ?BabelNodeTSTypeParameterDeclaration;
parameters?: any;
typeAnnotation?: ?BabelNodeTSTypeAnnotation;
}
declare class BabelNodeTSConstructSignatureDeclaration extends BabelNode {
type: "TSConstructSignatureDeclaration";
typeParameters?: ?BabelNodeTypeParameterDeclaration;
typeParameters?: ?BabelNodeTSTypeParameterDeclaration;
parameters?: any;
typeAnnotation?: ?BabelNodeTSTypeAnnotation;
}
@@ -989,7 +1004,7 @@ declare class BabelNodeTSPropertySignature extends BabelNode {
declare class BabelNodeTSMethodSignature extends BabelNode {
type: "TSMethodSignature";
key: BabelNodeExpression;
typeParameters?: ?BabelNodeTypeParameterDeclaration;
typeParameters?: ?BabelNodeTSTypeParameterDeclaration;
parameters?: any;
typeAnnotation?: ?BabelNodeTSTypeAnnotation;
computed?: boolean;
@@ -1049,14 +1064,14 @@ declare class BabelNodeTSThisType extends BabelNode {
declare class BabelNodeTSFunctionType extends BabelNode {
type: "TSFunctionType";
typeParameters?: ?BabelNodeTypeParameterDeclaration;
typeParameters?: ?BabelNodeTSTypeParameterDeclaration;
typeAnnotation?: ?BabelNodeTSTypeAnnotation;
parameters?: any;
}
declare class BabelNodeTSConstructorType extends BabelNode {
type: "TSConstructorType";
typeParameters?: ?BabelNodeTypeParameterDeclaration;
typeParameters?: ?BabelNodeTSTypeParameterDeclaration;
typeAnnotation?: ?BabelNodeTSTypeAnnotation;
parameters?: any;
}
@@ -1064,7 +1079,7 @@ declare class BabelNodeTSConstructorType extends BabelNode {
declare class BabelNodeTSTypeReference extends BabelNode {
type: "TSTypeReference";
typeName: BabelNodeTSEntityName;
typeParameters?: ?BabelNodeTypeParameterInstantiation;
typeParameters?: ?BabelNodeTSTypeParameterInstantiation;
}
declare class BabelNodeTSTypePredicate extends BabelNode {
@@ -1122,7 +1137,7 @@ declare class BabelNodeTSIndexedAccessType extends BabelNode {
declare class BabelNodeTSMappedType extends BabelNode {
type: "TSMappedType";
typeParameter: BabelNodeTypeParameter;
typeParameter: BabelNodeTSTypeParameter;
typeAnnotation?: ?BabelNodeTSType;
optional?: boolean;
readonly?: boolean;
@@ -1136,13 +1151,13 @@ declare class BabelNodeTSLiteralType extends BabelNode {
declare class BabelNodeTSExpressionWithTypeArguments extends BabelNode {
type: "TSExpressionWithTypeArguments";
expression: BabelNodeTSEntityName;
typeParameters?: ?BabelNodeTypeParameterInstantiation;
typeParameters?: ?BabelNodeTSTypeParameterInstantiation;
}
declare class BabelNodeTSInterfaceDeclaration extends BabelNode {
type: "TSInterfaceDeclaration";
id: BabelNodeIdentifier;
typeParameters?: ?BabelNodeTypeParameterDeclaration;
typeParameters?: ?BabelNodeTSTypeParameterDeclaration;
body: BabelNodeTSInterfaceBody;
declare?: boolean;
}
@@ -1155,7 +1170,7 @@ declare class BabelNodeTSInterfaceBody extends BabelNode {
declare class BabelNodeTSTypeAliasDeclaration extends BabelNode {
type: "TSTypeAliasDeclaration";
id: BabelNodeIdentifier;
typeParameters?: ?BabelNodeTypeParameterDeclaration;
typeParameters?: ?BabelNodeTSTypeParameterDeclaration;
typeAnnotation: BabelNodeTSType;
declare?: boolean;
}
@@ -1247,7 +1262,7 @@ declare class BabelNodeTSTypeParameter extends BabelNode {
name?: string;
}
type BabelNodeExpression = BabelNodeArrayExpression | BabelNodeAssignmentExpression | BabelNodeBinaryExpression | BabelNodeCallExpression | BabelNodeConditionalExpression | BabelNodeFunctionExpression | BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeNullLiteral | BabelNodeBooleanLiteral | BabelNodeRegExpLiteral | BabelNodeLogicalExpression | BabelNodeMemberExpression | BabelNodeNewExpression | BabelNodeObjectExpression | BabelNodeSequenceExpression | BabelNodeThisExpression | BabelNodeUnaryExpression | BabelNodeUpdateExpression | BabelNodeArrowFunctionExpression | BabelNodeClassExpression | BabelNodeMetaProperty | BabelNodeSuper | BabelNodeTaggedTemplateExpression | BabelNodeTemplateLiteral | BabelNodeYieldExpression | BabelNodeTypeCastExpression | BabelNodeJSXElement | BabelNodeJSXEmptyExpression | BabelNodeJSXIdentifier | BabelNodeJSXMemberExpression | BabelNodeParenthesizedExpression | BabelNodeAwaitExpression | BabelNodeBindExpression | BabelNodeImport | BabelNodeDoExpression | BabelNodeTSAsExpression | BabelNodeTSTypeAssertion | BabelNodeTSNonNullExpression;
type BabelNodeExpression = BabelNodeArrayExpression | BabelNodeAssignmentExpression | BabelNodeBinaryExpression | BabelNodeCallExpression | BabelNodeConditionalExpression | BabelNodeFunctionExpression | BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeNullLiteral | BabelNodeBooleanLiteral | BabelNodeRegExpLiteral | BabelNodeLogicalExpression | BabelNodeMemberExpression | BabelNodeNewExpression | BabelNodeObjectExpression | BabelNodeSequenceExpression | BabelNodeThisExpression | BabelNodeUnaryExpression | BabelNodeUpdateExpression | BabelNodeArrowFunctionExpression | BabelNodeClassExpression | BabelNodeMetaProperty | BabelNodeSuper | BabelNodeTaggedTemplateExpression | BabelNodeTemplateLiteral | BabelNodeYieldExpression | BabelNodeTypeCastExpression | BabelNodeJSXElement | BabelNodeJSXFragment | BabelNodeParenthesizedExpression | BabelNodeAwaitExpression | BabelNodeBindExpression | BabelNodeImport | BabelNodeDoExpression | BabelNodeTSAsExpression | BabelNodeTSTypeAssertion | BabelNodeTSNonNullExpression;
type BabelNodeBinary = BabelNodeBinaryExpression | BabelNodeLogicalExpression;
type BabelNodeScopable = BabelNodeBlockStatement | BabelNodeCatchClause | BabelNodeDoWhileStatement | BabelNodeForInStatement | BabelNodeForStatement | BabelNodeFunctionDeclaration | BabelNodeFunctionExpression | BabelNodeProgram | BabelNodeObjectMethod | BabelNodeSwitchStatement | BabelNodeWhileStatement | BabelNodeArrowFunctionExpression | BabelNodeClassDeclaration | BabelNodeClassExpression | BabelNodeForOfStatement | BabelNodeClassMethod;
type BabelNodeBlockParent = BabelNodeBlockStatement | BabelNodeCatchClause | BabelNodeDoWhileStatement | BabelNodeForInStatement | BabelNodeForStatement | BabelNodeFunctionDeclaration | BabelNodeFunctionExpression | BabelNodeProgram | BabelNodeObjectMethod | BabelNodeSwitchStatement | BabelNodeWhileStatement | BabelNodeArrowFunctionExpression | BabelNodeForOfStatement | BabelNodeClassMethod;
@@ -1269,7 +1284,7 @@ type BabelNodePatternLike = BabelNodeIdentifier | BabelNodeRestElement | BabelNo
type BabelNodeLVal = BabelNodeIdentifier | BabelNodeMemberExpression | BabelNodeRestElement | BabelNodeAssignmentPattern | BabelNodeArrayPattern | BabelNodeObjectPattern | BabelNodeTSParameterProperty;
type BabelNodeTSEntityName = BabelNodeIdentifier | BabelNodeTSQualifiedName;
type BabelNodeLiteral = BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeNullLiteral | BabelNodeBooleanLiteral | BabelNodeRegExpLiteral | BabelNodeTemplateLiteral;
type BabelNodeImmutable = BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeNullLiteral | BabelNodeBooleanLiteral | BabelNodeJSXAttribute | BabelNodeJSXClosingElement | BabelNodeJSXElement | BabelNodeJSXExpressionContainer | BabelNodeJSXSpreadChild | BabelNodeJSXOpeningElement | BabelNodeJSXText;
type BabelNodeImmutable = BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeNullLiteral | BabelNodeBooleanLiteral | BabelNodeJSXAttribute | BabelNodeJSXClosingElement | BabelNodeJSXElement | BabelNodeJSXExpressionContainer | BabelNodeJSXSpreadChild | BabelNodeJSXOpeningElement | BabelNodeJSXText | BabelNodeJSXFragment | BabelNodeJSXOpeningFragment | BabelNodeJSXClosingFragment;
type BabelNodeUserWhitespacable = BabelNodeObjectMethod | BabelNodeObjectProperty | BabelNodeObjectTypeCallProperty | BabelNodeObjectTypeIndexer | BabelNodeObjectTypeProperty | BabelNodeObjectTypeSpreadProperty;
type BabelNodeMethod = BabelNodeObjectMethod | BabelNodeClassMethod;
type BabelNodeObjectMember = BabelNodeObjectMethod | BabelNodeObjectProperty;
@@ -1284,7 +1299,7 @@ type BabelNodeFlow = BabelNodeAnyTypeAnnotation | BabelNodeArrayTypeAnnotation |
type BabelNodeFlowBaseAnnotation = BabelNodeAnyTypeAnnotation | BabelNodeBooleanTypeAnnotation | BabelNodeNullLiteralTypeAnnotation | BabelNodeMixedTypeAnnotation | BabelNodeEmptyTypeAnnotation | BabelNodeNumberTypeAnnotation | BabelNodeStringTypeAnnotation | BabelNodeThisTypeAnnotation | BabelNodeVoidTypeAnnotation;
type BabelNodeFlowDeclaration = BabelNodeDeclareClass | BabelNodeDeclareFunction | BabelNodeDeclareInterface | BabelNodeDeclareModule | BabelNodeDeclareModuleExports | BabelNodeDeclareTypeAlias | BabelNodeDeclareOpaqueType | BabelNodeDeclareVariable | BabelNodeDeclareExportDeclaration | BabelNodeDeclareExportAllDeclaration | BabelNodeInterfaceDeclaration | BabelNodeOpaqueType | BabelNodeTypeAlias;
type BabelNodeFlowPredicate = BabelNodeDeclaredPredicate | BabelNodeInferredPredicate;
type BabelNodeJSX = BabelNodeJSXAttribute | BabelNodeJSXClosingElement | BabelNodeJSXElement | BabelNodeJSXEmptyExpression | BabelNodeJSXExpressionContainer | BabelNodeJSXSpreadChild | BabelNodeJSXIdentifier | BabelNodeJSXMemberExpression | BabelNodeJSXNamespacedName | BabelNodeJSXOpeningElement | BabelNodeJSXSpreadAttribute | BabelNodeJSXText;
type BabelNodeJSX = BabelNodeJSXAttribute | BabelNodeJSXClosingElement | BabelNodeJSXElement | BabelNodeJSXEmptyExpression | BabelNodeJSXExpressionContainer | BabelNodeJSXSpreadChild | BabelNodeJSXIdentifier | BabelNodeJSXMemberExpression | BabelNodeJSXNamespacedName | BabelNodeJSXOpeningElement | BabelNodeJSXSpreadAttribute | BabelNodeJSXText | BabelNodeJSXFragment | BabelNodeJSXOpeningFragment | BabelNodeJSXClosingFragment;
type BabelNodeTSTypeElement = BabelNodeTSCallSignatureDeclaration | BabelNodeTSConstructSignatureDeclaration | BabelNodeTSPropertySignature | BabelNodeTSMethodSignature | BabelNodeTSIndexSignature;
type BabelNodeTSType = BabelNodeTSAnyKeyword | BabelNodeTSNumberKeyword | BabelNodeTSObjectKeyword | BabelNodeTSBooleanKeyword | BabelNodeTSStringKeyword | BabelNodeTSSymbolKeyword | BabelNodeTSVoidKeyword | BabelNodeTSUndefinedKeyword | BabelNodeTSNullKeyword | BabelNodeTSNeverKeyword | BabelNodeTSThisType | BabelNodeTSFunctionType | BabelNodeTSConstructorType | BabelNodeTSTypeReference | BabelNodeTSTypePredicate | BabelNodeTSTypeQuery | BabelNodeTSTypeLiteral | BabelNodeTSArrayType | BabelNodeTSTupleType | BabelNodeTSUnionType | BabelNodeTSIntersectionType | BabelNodeTSParenthesizedType | BabelNodeTSTypeOperator | BabelNodeTSIndexedAccessType | BabelNodeTSMappedType | BabelNodeTSLiteralType | BabelNodeTSExpressionWithTypeArguments;
@@ -1296,7 +1311,7 @@ declare module "@babel/types" {
declare function directiveLiteral(value: string): BabelNodeDirectiveLiteral;
declare function blockStatement(body: any, directives?: any): BabelNodeBlockStatement;
declare function breakStatement(label?: ?BabelNodeIdentifier): BabelNodeBreakStatement;
declare function callExpression(callee: BabelNodeExpression, _arguments: any, optional?: true | false, typeParameters?: ?BabelNodeTypeParameterInstantiation): BabelNodeCallExpression;
declare function callExpression(callee: BabelNodeExpression, _arguments: any, optional?: true | false, typeParameters?: ?BabelNodeTypeParameterInstantiation | BabelNodeTSTypeParameterInstantiation): BabelNodeCallExpression;
declare function catchClause(param?: ?BabelNodeIdentifier, body: BabelNodeBlockStatement): BabelNodeCatchClause;
declare function conditionalExpression(test: BabelNodeExpression, consequent: BabelNodeExpression, alternate: BabelNodeExpression): BabelNodeConditionalExpression;
declare function continueStatement(label?: ?BabelNodeIdentifier): BabelNodeContinueStatement;
@@ -1307,8 +1322,8 @@ declare module "@babel/types" {
declare function file(program: BabelNodeProgram, comments: any, tokens: any): BabelNodeFile;
declare function forInStatement(left: BabelNodeVariableDeclaration | BabelNodeLVal, right: BabelNodeExpression, body: BabelNodeStatement): BabelNodeForInStatement;
declare function forStatement(init?: ?BabelNodeVariableDeclaration | BabelNodeExpression, test?: ?BabelNodeExpression, update?: ?BabelNodeExpression, body: BabelNodeStatement): BabelNodeForStatement;
declare function functionDeclaration(id?: ?BabelNodeIdentifier, params: any, body: BabelNodeBlockStatement, generator?: boolean, async?: boolean, declare?: boolean, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop): BabelNodeFunctionDeclaration;
declare function functionExpression(id?: ?BabelNodeIdentifier, params: any, body: BabelNodeBlockStatement, generator?: boolean, async?: boolean, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop): BabelNodeFunctionExpression;
declare function functionDeclaration(id?: ?BabelNodeIdentifier, params: any, body: BabelNodeBlockStatement, generator?: boolean, async?: boolean, declare?: boolean, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop): BabelNodeFunctionDeclaration;
declare function functionExpression(id?: ?BabelNodeIdentifier, params: any, body: BabelNodeBlockStatement, generator?: boolean, async?: boolean, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop): BabelNodeFunctionExpression;
declare function identifier(name: any, decorators?: any, optional?: boolean, typeAnnotation?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop): BabelNodeIdentifier;
declare function ifStatement(test: BabelNodeExpression, consequent: BabelNodeStatement, alternate?: ?BabelNodeStatement): BabelNodeIfStatement;
declare function labeledStatement(label: BabelNodeIdentifier, body: BabelNodeStatement): BabelNodeLabeledStatement;
@@ -1319,10 +1334,10 @@ declare module "@babel/types" {
declare function regExpLiteral(pattern: string, flags?: string): BabelNodeRegExpLiteral;
declare function logicalExpression(operator: "||" | "&&" | "??", left: BabelNodeExpression, right: BabelNodeExpression): BabelNodeLogicalExpression;
declare function memberExpression(object: BabelNodeExpression, property: any, computed?: boolean, optional?: true | false): BabelNodeMemberExpression;
declare function newExpression(callee: BabelNodeExpression, _arguments: any, optional?: true | false, typeParameters?: ?BabelNodeTypeParameterInstantiation): BabelNodeNewExpression;
declare function newExpression(callee: BabelNodeExpression, _arguments: any, optional?: true | false, typeParameters?: ?BabelNodeTypeParameterInstantiation | BabelNodeTSTypeParameterInstantiation): BabelNodeNewExpression;
declare function program(body: any, directives?: any, sourceType?: "script" | "module", sourceFile?: string): BabelNodeProgram;
declare function objectExpression(properties: any): BabelNodeObjectExpression;
declare function objectMethod(kind?: any, key: any, params: any, body: BabelNodeBlockStatement, computed?: boolean, async?: boolean, decorators?: any, generator?: boolean, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop): BabelNodeObjectMethod;
declare function objectMethod(kind?: any, key: any, params: any, body: BabelNodeBlockStatement, computed?: boolean, async?: boolean, decorators?: any, generator?: boolean, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop): BabelNodeObjectMethod;
declare function objectProperty(key: any, value: BabelNodeExpression | BabelNodePatternLike, computed?: boolean, shorthand?: boolean, decorators?: any): BabelNodeObjectProperty;
declare function restElement(argument: BabelNodeLVal, decorators?: any, typeAnnotation?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop): BabelNodeRestElement;
declare function returnStatement(argument?: ?BabelNodeExpression): BabelNodeReturnStatement;
@@ -1337,13 +1352,13 @@ declare module "@babel/types" {
declare function variableDeclaration(kind: any, declarations: any, declare?: boolean): BabelNodeVariableDeclaration;
declare function variableDeclarator(id: BabelNodeLVal, init?: ?BabelNodeExpression): BabelNodeVariableDeclarator;
declare function whileStatement(test: BabelNodeExpression, body: BabelNodeBlockStatement | BabelNodeStatement): BabelNodeWhileStatement;
declare function withStatement(object: any, body: BabelNodeBlockStatement | BabelNodeStatement): BabelNodeWithStatement;
declare function withStatement(object: BabelNodeExpression, body: BabelNodeBlockStatement | BabelNodeStatement): BabelNodeWithStatement;
declare function assignmentPattern(left: BabelNodeIdentifier | BabelNodeObjectPattern | BabelNodeArrayPattern, right: BabelNodeExpression, decorators?: any, typeAnnotation?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop): BabelNodeAssignmentPattern;
declare function arrayPattern(elements: any, decorators?: any, typeAnnotation?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop): BabelNodeArrayPattern;
declare function arrowFunctionExpression(params: any, body: BabelNodeBlockStatement | BabelNodeExpression, async?: boolean, expression?: boolean, generator?: boolean, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop): BabelNodeArrowFunctionExpression;
declare function arrowFunctionExpression(params: any, body: BabelNodeBlockStatement | BabelNodeExpression, async?: boolean, expression?: boolean, generator?: boolean, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop): BabelNodeArrowFunctionExpression;
declare function classBody(body: any): BabelNodeClassBody;
declare function classDeclaration(id?: ?BabelNodeIdentifier, superClass?: ?BabelNodeExpression, body: BabelNodeClassBody, decorators?: any, abstract?: boolean, declare?: boolean, _implements?: any, mixins?: any, superTypeParameters?: ?BabelNodeTypeParameterInstantiation, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop): BabelNodeClassDeclaration;
declare function classExpression(id?: ?BabelNodeIdentifier, superClass?: ?BabelNodeExpression, body: BabelNodeClassBody, decorators?: any, _implements?: any, mixins?: any, superTypeParameters?: ?BabelNodeTypeParameterInstantiation, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop): BabelNodeClassExpression;
declare function classDeclaration(id?: ?BabelNodeIdentifier, superClass?: ?BabelNodeExpression, body: BabelNodeClassBody, decorators?: any, abstract?: boolean, declare?: boolean, _implements?: any, mixins?: any, superTypeParameters?: ?BabelNodeTypeParameterInstantiation | BabelNodeTSTypeParameterInstantiation, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop): BabelNodeClassDeclaration;
declare function classExpression(id?: ?BabelNodeIdentifier, superClass?: ?BabelNodeExpression, body: BabelNodeClassBody, decorators?: any, _implements?: any, mixins?: any, superTypeParameters?: ?BabelNodeTypeParameterInstantiation | BabelNodeTSTypeParameterInstantiation, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop): BabelNodeClassExpression;
declare function exportAllDeclaration(source: BabelNodeStringLiteral): BabelNodeExportAllDeclaration;
declare function exportDefaultDeclaration(declaration: BabelNodeFunctionDeclaration | BabelNodeTSDeclareFunction | BabelNodeClassDeclaration | BabelNodeExpression): BabelNodeExportDefaultDeclaration;
declare function exportNamedDeclaration(declaration?: ?BabelNodeDeclaration, specifiers: any, source?: ?BabelNodeStringLiteral): BabelNodeExportNamedDeclaration;
@@ -1354,7 +1369,7 @@ declare module "@babel/types" {
declare function importNamespaceSpecifier(local: BabelNodeIdentifier): BabelNodeImportNamespaceSpecifier;
declare function importSpecifier(local: BabelNodeIdentifier, imported: BabelNodeIdentifier, importKind?: null | "type" | "typeof"): BabelNodeImportSpecifier;
declare function metaProperty(meta: BabelNodeIdentifier, property: BabelNodeIdentifier): BabelNodeMetaProperty;
declare function classMethod(kind?: any, key: any, params: any, body: BabelNodeBlockStatement, computed?: boolean, _static?: boolean, abstract?: boolean, access?: any, accessibility?: any, async?: boolean, decorators?: any, generator?: boolean, optional?: boolean, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop): BabelNodeClassMethod;
declare function classMethod(kind?: any, key: any, params: any, body: BabelNodeBlockStatement, computed?: boolean, _static?: boolean, abstract?: boolean, access?: any, accessibility?: any, async?: boolean, decorators?: any, generator?: boolean, optional?: boolean, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeTSTypeParameterDeclaration | BabelNodeNoop): BabelNodeClassMethod;
declare function objectPattern(properties: any, decorators?: any, typeAnnotation?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop): BabelNodeObjectPattern;
declare function spreadElement(argument: BabelNodeExpression): BabelNodeSpreadElement;
declare function taggedTemplateExpression(tag: BabelNodeExpression, quasi: BabelNodeTemplateLiteral): BabelNodeTaggedTemplateExpression;
@@ -1411,7 +1426,7 @@ declare module "@babel/types" {
declare function typeParameterInstantiation(params: any): BabelNodeTypeParameterInstantiation;
declare function unionTypeAnnotation(types: any): BabelNodeUnionTypeAnnotation;
declare function voidTypeAnnotation(): BabelNodeVoidTypeAnnotation;
declare function jSXAttribute(name: BabelNodeJSXIdentifier | BabelNodeJSXNamespacedName, value?: ?BabelNodeJSXElement | BabelNodeStringLiteral | BabelNodeJSXExpressionContainer): BabelNodeJSXAttribute;
declare function jSXAttribute(name: BabelNodeJSXIdentifier | BabelNodeJSXNamespacedName, value?: ?BabelNodeJSXElement | BabelNodeJSXFragment | BabelNodeStringLiteral | BabelNodeJSXExpressionContainer): BabelNodeJSXAttribute;
declare function jSXClosingElement(name: BabelNodeJSXIdentifier | BabelNodeJSXMemberExpression): BabelNodeJSXClosingElement;
declare function jSXElement(openingElement: BabelNodeJSXOpeningElement, closingElement?: ?BabelNodeJSXClosingElement, children: any, selfClosing: any): BabelNodeJSXElement;
declare function jSXEmptyExpression(): BabelNodeJSXEmptyExpression;
@@ -1423,6 +1438,9 @@ declare module "@babel/types" {
declare function jSXOpeningElement(name: BabelNodeJSXIdentifier | BabelNodeJSXMemberExpression, attributes: any, selfClosing?: boolean): BabelNodeJSXOpeningElement;
declare function jSXSpreadAttribute(argument: BabelNodeExpression): BabelNodeJSXSpreadAttribute;
declare function jSXText(value: string): BabelNodeJSXText;
declare function jSXFragment(openingFragment: BabelNodeJSXOpeningFragment, closingFragment: BabelNodeJSXClosingFragment, children: any): BabelNodeJSXFragment;
declare function jSXOpeningFragment(): BabelNodeJSXOpeningFragment;
declare function jSXClosingFragment(): BabelNodeJSXClosingFragment;
declare function noop(): BabelNodeNoop;
declare function parenthesizedExpression(expression: BabelNodeExpression): BabelNodeParenthesizedExpression;
declare function awaitExpression(argument: BabelNodeExpression): BabelNodeAwaitExpression;
@@ -1433,13 +1451,13 @@ declare module "@babel/types" {
declare function exportDefaultSpecifier(exported: BabelNodeIdentifier): BabelNodeExportDefaultSpecifier;
declare function exportNamespaceSpecifier(exported: BabelNodeIdentifier): BabelNodeExportNamespaceSpecifier;
declare function tSParameterProperty(parameter: BabelNodeIdentifier | BabelNodeAssignmentPattern, accessibility?: "public" | "private" | "protected", readonly?: boolean): BabelNodeTSParameterProperty;
declare function tSDeclareFunction(id?: ?BabelNodeIdentifier, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop, params: any, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, async?: boolean, declare?: boolean, generator?: boolean): BabelNodeTSDeclareFunction;
declare function tSDeclareMethod(decorators?: any, key: any, typeParameters?: ?BabelNodeTypeParameterDeclaration | BabelNodeNoop, params: any, returnType?: ?BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, abstract?: boolean, access?: any, accessibility?: any, async?: boolean, computed?: boolean, generator?: boolean, kind?: any, optional?: boolean, _static?: boolean): BabelNodeTSDeclareMethod;
declare function tSDeclareFunction(id?: ?BabelNodeIdentifier, typeParameters?: ?BabelNodeTSTypeParameterDeclaration | BabelNodeNoop, params: any, returnType?: ?BabelNodeTSTypeAnnotation | BabelNodeNoop, async?: boolean, declare?: boolean, generator?: boolean): BabelNodeTSDeclareFunction;
declare function tSDeclareMethod(decorators?: any, key: any, typeParameters?: ?BabelNodeTSTypeParameterDeclaration | BabelNodeNoop, params: any, returnType?: ?BabelNodeTSTypeAnnotation | BabelNodeNoop, abstract?: boolean, access?: any, accessibility?: any, async?: boolean, computed?: boolean, generator?: boolean, kind?: any, optional?: boolean, _static?: boolean): BabelNodeTSDeclareMethod;
declare function tSQualifiedName(left: BabelNodeTSEntityName, right: BabelNodeIdentifier): BabelNodeTSQualifiedName;
declare function tSCallSignatureDeclaration(typeParameters?: ?BabelNodeTypeParameterDeclaration, parameters?: any, typeAnnotation?: ?BabelNodeTSTypeAnnotation): BabelNodeTSCallSignatureDeclaration;
declare function tSConstructSignatureDeclaration(typeParameters?: ?BabelNodeTypeParameterDeclaration, parameters?: any, typeAnnotation?: ?BabelNodeTSTypeAnnotation): BabelNodeTSConstructSignatureDeclaration;
declare function tSCallSignatureDeclaration(typeParameters?: ?BabelNodeTSTypeParameterDeclaration, parameters?: any, typeAnnotation?: ?BabelNodeTSTypeAnnotation): BabelNodeTSCallSignatureDeclaration;
declare function tSConstructSignatureDeclaration(typeParameters?: ?BabelNodeTSTypeParameterDeclaration, parameters?: any, typeAnnotation?: ?BabelNodeTSTypeAnnotation): BabelNodeTSConstructSignatureDeclaration;
declare function tSPropertySignature(key: BabelNodeExpression, typeAnnotation?: ?BabelNodeTSTypeAnnotation, initializer?: ?BabelNodeExpression, computed?: boolean, optional?: boolean, readonly?: boolean): BabelNodeTSPropertySignature;
declare function tSMethodSignature(key: BabelNodeExpression, typeParameters?: ?BabelNodeTypeParameterDeclaration, parameters?: any, typeAnnotation?: ?BabelNodeTSTypeAnnotation, computed?: boolean, optional?: boolean): BabelNodeTSMethodSignature;
declare function tSMethodSignature(key: BabelNodeExpression, typeParameters?: ?BabelNodeTSTypeParameterDeclaration, parameters?: any, typeAnnotation?: ?BabelNodeTSTypeAnnotation, computed?: boolean, optional?: boolean): BabelNodeTSMethodSignature;
declare function tSIndexSignature(parameters: any, typeAnnotation?: ?BabelNodeTSTypeAnnotation, readonly?: boolean): BabelNodeTSIndexSignature;
declare function tSAnyKeyword(): BabelNodeTSAnyKeyword;
declare function tSNumberKeyword(): BabelNodeTSNumberKeyword;
@@ -1452,9 +1470,9 @@ declare module "@babel/types" {
declare function tSNullKeyword(): BabelNodeTSNullKeyword;
declare function tSNeverKeyword(): BabelNodeTSNeverKeyword;
declare function tSThisType(): BabelNodeTSThisType;
declare function tSFunctionType(typeParameters?: ?BabelNodeTypeParameterDeclaration, typeAnnotation?: ?BabelNodeTSTypeAnnotation, parameters?: any): BabelNodeTSFunctionType;
declare function tSConstructorType(typeParameters?: ?BabelNodeTypeParameterDeclaration, typeAnnotation?: ?BabelNodeTSTypeAnnotation, parameters?: any): BabelNodeTSConstructorType;
declare function tSTypeReference(typeName: BabelNodeTSEntityName, typeParameters?: ?BabelNodeTypeParameterInstantiation): BabelNodeTSTypeReference;
declare function tSFunctionType(typeParameters?: ?BabelNodeTSTypeParameterDeclaration, typeAnnotation?: ?BabelNodeTSTypeAnnotation, parameters?: any): BabelNodeTSFunctionType;
declare function tSConstructorType(typeParameters?: ?BabelNodeTSTypeParameterDeclaration, typeAnnotation?: ?BabelNodeTSTypeAnnotation, parameters?: any): BabelNodeTSConstructorType;
declare function tSTypeReference(typeName: BabelNodeTSEntityName, typeParameters?: ?BabelNodeTSTypeParameterInstantiation): BabelNodeTSTypeReference;
declare function tSTypePredicate(parameterName: BabelNodeIdentifier | BabelNodeTSThisType, typeAnnotation: BabelNodeTSTypeAnnotation): BabelNodeTSTypePredicate;
declare function tSTypeQuery(exprName: BabelNodeTSEntityName): BabelNodeTSTypeQuery;
declare function tSTypeLiteral(members: any): BabelNodeTSTypeLiteral;
@@ -1465,12 +1483,12 @@ declare module "@babel/types" {
declare function tSParenthesizedType(typeAnnotation: BabelNodeTSType): BabelNodeTSParenthesizedType;
declare function tSTypeOperator(typeAnnotation: BabelNodeTSType, operator?: string): BabelNodeTSTypeOperator;
declare function tSIndexedAccessType(objectType: BabelNodeTSType, indexType: BabelNodeTSType): BabelNodeTSIndexedAccessType;
declare function tSMappedType(typeParameter: BabelNodeTypeParameter, typeAnnotation?: ?BabelNodeTSType, optional?: boolean, readonly?: boolean): BabelNodeTSMappedType;
declare function tSMappedType(typeParameter: BabelNodeTSTypeParameter, typeAnnotation?: ?BabelNodeTSType, optional?: boolean, readonly?: boolean): BabelNodeTSMappedType;
declare function tSLiteralType(literal: BabelNodeNumericLiteral | BabelNodeStringLiteral | BabelNodeBooleanLiteral): BabelNodeTSLiteralType;
declare function tSExpressionWithTypeArguments(expression: BabelNodeTSEntityName, typeParameters?: ?BabelNodeTypeParameterInstantiation): BabelNodeTSExpressionWithTypeArguments;
declare function tSInterfaceDeclaration(id: BabelNodeIdentifier, typeParameters?: ?BabelNodeTypeParameterDeclaration, _extends?: any, body: BabelNodeTSInterfaceBody, declare?: boolean): BabelNodeTSInterfaceDeclaration;
declare function tSExpressionWithTypeArguments(expression: BabelNodeTSEntityName, typeParameters?: ?BabelNodeTSTypeParameterInstantiation): BabelNodeTSExpressionWithTypeArguments;
declare function tSInterfaceDeclaration(id: BabelNodeIdentifier, typeParameters?: ?BabelNodeTSTypeParameterDeclaration, _extends?: any, body: BabelNodeTSInterfaceBody, declare?: boolean): BabelNodeTSInterfaceDeclaration;
declare function tSInterfaceBody(body: any): BabelNodeTSInterfaceBody;
declare function tSTypeAliasDeclaration(id: BabelNodeIdentifier, typeParameters?: ?BabelNodeTypeParameterDeclaration, typeAnnotation: BabelNodeTSType, declare?: boolean): BabelNodeTSTypeAliasDeclaration;
declare function tSTypeAliasDeclaration(id: BabelNodeIdentifier, typeParameters?: ?BabelNodeTSTypeParameterDeclaration, typeAnnotation: BabelNodeTSType, declare?: boolean): BabelNodeTSTypeAliasDeclaration;
declare function tSAsExpression(expression: BabelNodeExpression, typeAnnotation: BabelNodeTSType): BabelNodeTSAsExpression;
declare function tSTypeAssertion(typeAnnotation: BabelNodeTSType, expression: BabelNodeExpression): BabelNodeTSTypeAssertion;
declare function tSEnumDeclaration(id: BabelNodeIdentifier, members: any, _const?: boolean, declare?: boolean, initializer?: ?BabelNodeExpression): BabelNodeTSEnumDeclaration;
@@ -1621,6 +1639,9 @@ declare module "@babel/types" {
declare function isJSXOpeningElement(node: Object, opts?: ?Object): boolean %checks (node instanceof BabelNodeJSXOpeningElement)
declare function isJSXSpreadAttribute(node: Object, opts?: ?Object): boolean %checks (node instanceof BabelNodeJSXSpreadAttribute)
declare function isJSXText(node: Object, opts?: ?Object): boolean %checks (node instanceof BabelNodeJSXText)
declare function isJSXFragment(node: Object, opts?: ?Object): boolean %checks (node instanceof BabelNodeJSXFragment)
declare function isJSXOpeningFragment(node: Object, opts?: ?Object): boolean %checks (node instanceof BabelNodeJSXOpeningFragment)
declare function isJSXClosingFragment(node: Object, opts?: ?Object): boolean %checks (node instanceof BabelNodeJSXClosingFragment)
declare function isNoop(node: Object, opts?: ?Object): boolean %checks (node instanceof BabelNodeNoop)
declare function isParenthesizedExpression(node: Object, opts?: ?Object): boolean %checks (node instanceof BabelNodeParenthesizedExpression)
declare function isAwaitExpression(node: Object, opts?: ?Object): boolean %checks (node instanceof BabelNodeAwaitExpression)
@@ -1727,6 +1748,8 @@ declare module "@babel/types" {
declare function isTSType(node: Object, opts?: ?Object): boolean
declare function isNumberLiteral(node: Object, opts?: ?Object): boolean
declare function isRegexLiteral(node: Object, opts?: ?Object): boolean
declare function isRestProperty(node: Object, opts?: ?Object): boolean
declare function isSpreadProperty(node: Object, opts?: ?Object): boolean
declare function validate(n: BabelNode, key: string, value: mixed): void;
declare function clone<T>(n: T): T;
declare function cloneDeep<T>(n: T): T;

View File

@@ -10,17 +10,18 @@
"test": "make test"
},
"devDependencies": {
"@babel/cli": "7.0.0-beta.5",
"@babel/core": "7.0.0-beta.5",
"@babel/preset-env": "7.0.0-beta.5",
"@babel/preset-flow": "7.0.0-beta.5",
"@babel/preset-stage-0": "7.0.0-beta.5",
"@babel/register": "7.0.0-beta.5",
"@babel/cli": "7.0.0-beta.33",
"@babel/core": "7.0.0-beta.33",
"@babel/plugin-proposal-export-namespace-from": "7.0.0-beta.33",
"@babel/preset-env": "7.0.0-beta.33",
"@babel/preset-flow": "7.0.0-beta.33",
"@babel/preset-stage-0": "7.0.0-beta.33",
"@babel/register": "7.0.0-beta.33",
"async": "^1.5.0",
"babel-eslint": "^8.0.1",
"babel-loader": "8.0.0-beta.0",
"babel-plugin-istanbul": "^4.1.4",
"babylon": "7.0.0-beta.30",
"babylon": "7.0.0-beta.33",
"browserify": "^13.1.1",
"bundle-collapser": "^1.2.1",
"chai": "^4.1.0",
@@ -30,7 +31,7 @@
"eslint-config-babel": "^7.0.2",
"eslint-plugin-flowtype": "^2.20.0",
"eslint-plugin-prettier": "^2.2.0",
"flow-bin": "^0.57.3",
"flow-bin": "^0.59.0",
"graceful-fs": "^4.1.11",
"gulp": "^3.9.0",
"gulp-babel": "^8.0.0-beta.0",
@@ -50,7 +51,7 @@
"mocha": "^3.0.0",
"nyc": "^11.0.3",
"output-file-sync": "^2.0.0",
"prettier": "1.7.3",
"prettier": "1.9.1",
"pump": "^1.0.2",
"rimraf": "^2.4.3",
"semver": "^5.0.0",
@@ -72,8 +73,7 @@
"scripts/*.js",
"packages/*/test/**",
"packages/babel-standalone/**",
"codemods/*/test/**",
"experimental/*/test/**"
"codemods/*/test/**"
],
"sourceMap": false,
"instrument": false

View File

@@ -45,7 +45,7 @@ Check out the [`babel-handbook`](https://github.com/thejameskyle/babel-handbook/
| [`@babel/helpers`](/packages/babel-helpers) | [![npm](https://img.shields.io/npm/v/babel-helpers.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-helpers) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-helpers)](https://david-dm.org/babel/babel?path=packages/babel-helpers) |
| [`@babel/code-frame`](/packages/babel-code-frame) | [![npm](https://img.shields.io/npm/v/babel-code-frame.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-code-frame) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-code-frame)](https://david-dm.org/babel/babel?path=packages/babel-code-frame) |
- [`@babel/cli`](/packages/babel-cli) is the CLI tool that runs `@babel/core` and helps with outputting to a directory, a file, stdout and more (also includes `babel-node`). Check out the [docs](https://babeljs.io/docs/usage/cli/).
- [`@babel/cli`](/packages/babel-cli) is the CLI tool that runs `@babel/core` and helps with outputting to a directory, a file, stdout and more (also includes `@babel/node` cli). Check out the [docs](https://babeljs.io/docs/usage/cli/).
- [`@babel/types`](/packages/babel-types) is used to validate, build and change AST nodes.
- [`@babel/polyfill`](/packages/babel-polyfill) is [literally a wrapper](https://github.com/babel/babel/blob/master/packages/babel-polyfill/src/index.js) around [`core-js`](https://github.com/zloirock/core-js) and [regenerator-runtime](https://github.com/facebook/regenerator/tree/master/packages/regenerator-runtime). Check out the [docs](https://babeljs.io/docs/usage/polyfill/).
- [`@babel/runtime`](/packages/babel-runtime) is similar to the polyfill except that it doesn't modify the global scope and is to be used with [`@babel/plugin-transform-runtime`](/packages/babel-plugin-transform-runtime) (usually in library/plugin code). Check out the [docs](https://babeljs.io/docs/plugins/transform-runtime/).

View File

@@ -4,7 +4,7 @@
In addition, various entry point scripts live in the top-level package at `@babel/cli/bin`.
There are some shell-executable utility scripts, `babel-external-helpers.js` and `babel-node.js`, and the main Babel cli script, `babel.js`.
There is a shell-executable utility script, `babel-external-helpers.js`, and the main Babel cli script, `babel.js`.
## Install

View File

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

View File

@@ -49,6 +49,11 @@ commander.option(
collect,
);
commander.option("--config-file [path]", "Path a to .babelrc file to use");
commander.option(
"--env-name [name]",
"The name of the 'env' to use when loading configs and plugins. " +
"Defaults to the value of BABEL_ENV, or else NODE_ENV, or else 'development'.",
);
// Basic file input configuration.
commander.option("--source-type [script|module]", "");

View File

@@ -1 +1 @@
SyntaxError: test.js: Unexpected token, expected ; (2:10)
SyntaxError: test.js: Unexpected token, expected ";" (2:10)

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/code-frame",
"version": "7.0.0-beta.32",
"version": "7.0.0-beta.36",
"description": "Generate errors that contain a code frame that point to source locations.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",

View File

@@ -144,10 +144,11 @@ Following is a table of the options you can use:
| `auxiliaryCommentAfter` | `null` | Attach a comment after all non-user injected code |
| `auxiliaryCommentBefore` | `null` | Attach a comment before all non-user injected code |
| `babelrc` | `true` | Specify whether or not to use .babelrc and .babelignore files. Not available when using the CLI, [use `--no-babelrc` instead](https://babeljs.io/docs/usage/cli/#babel-ignoring-babelrc) |
| `envName` | env vars | Defaults to environment variable `BABEL_ENV` if set, or else `NODE_ENV` if set, or else it defaults to `"development"` |
| `code` | `true` | Enable code generation |
| `comments` | `true` | Output comments in generated output |
| `compact` | `"auto"` | Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB |
| `env` | `{}` | This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { /* specific options */ } } }` which will use those options when the environment variable `BABEL_ENV` is set to `"production"`. If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"` |
| `env` | `{}` | This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { /* specific options */ } } }` which will use those options when the `envName` is `production` |
| `extends` | `null` | A path to a `.babelrc` file to extend |
| `filename` | `"unknown"` | Filename for use in errors etc |
| `filenameRelative` | `(filename)` | Filename relative to `sourceRoot` |

View File

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

View File

@@ -1,419 +0,0 @@
// @flow
import { getEnv } from "./helpers/environment";
import path from "path";
import micromatch from "micromatch";
import buildDebug from "debug";
import {
validate,
type ValidatedOptions,
type PluginList,
type IgnoreList,
} from "./options";
const debug = buildDebug("babel:config:config-chain");
import { findConfigs, loadConfig, type ConfigFile } from "./loading/files";
import { makeWeakCache, makeStrongCache } from "./caching";
export type ConfigItem = {
type: "arguments" | "env" | "file",
options: ValidatedOptions,
alias: string,
dirname: string,
};
type ConfigPart =
| {
part: "config",
config: ConfigItem,
ignore: ?IgnoreList,
only: ?IgnoreList,
activeEnv: string | null,
}
| {
part: "extends",
path: string,
dirname: string,
activeEnv: string | null,
};
export default function buildConfigChain(
opts: ValidatedOptions,
): Array<ConfigItem> | null {
const filename = opts.filename ? path.resolve(opts.filename) : null;
const builder = new ConfigChainBuilder(
filename ? new LoadedFile(filename) : null,
);
const envKey = getEnv();
try {
builder.mergeConfigArguments(opts, process.cwd(), envKey);
// resolve all .babelrc files
if (opts.babelrc !== false && filename) {
findConfigs(path.dirname(filename)).forEach(configFile =>
builder.mergeConfigFile(configFile, envKey),
);
}
} catch (e) {
if (e.code !== "BABEL_IGNORED_FILE") throw e;
return null;
}
return builder.configs.reverse();
}
class ConfigChainBuilder {
file: LoadedFile | null;
configs: Array<ConfigItem> = [];
seenFiles: Set<ConfigFile> = new Set();
constructor(file: LoadedFile | null) {
this.file = file;
}
mergeConfigArguments(
opts: ValidatedOptions,
dirname: string,
envKey: string,
) {
flattenArgumentsOptionsParts(opts, dirname, envKey).forEach(part =>
this._processConfigPart(part, envKey),
);
}
mergeConfigFile(file: ConfigFile, envKey: string) {
if (this.seenFiles.has(file)) {
throw new Error(
`Cycle detected in Babel configuration file through "${file.filepath}".`,
);
}
const parts = flattenFileOptionsParts(file)(envKey);
this.seenFiles.add(file);
parts.forEach(part => this._processConfigPart(part, envKey));
this.seenFiles.delete(file);
}
_processConfigPart(part: ConfigPart, envKey: string) {
if (part.part === "config") {
const { ignore, only } = part;
// Bail out ASAP if this file is ignored so that we run as little logic as possible on ignored files.
if (
this.file &&
this.file.shouldIgnore(ignore, only, part.config.dirname)
) {
// TODO(logan): This is a really gross way to bail out. Avoid this in rewrite.
throw Object.assign((new Error("This file has been ignored."): any), {
code: "BABEL_IGNORED_FILE",
});
}
this.configs.push(part.config);
} else {
this.mergeConfigFile(loadConfig(part.path, part.dirname), envKey);
}
}
}
/**
* Given the root config object passed to Babel, split it into the separate
* config parts. The resulting config objects in the 'ConfigPart' have their
* object identity preserved between calls so that they can be used for caching.
*/
function flattenArgumentsOptionsParts(
opts: ValidatedOptions,
dirname: string,
envKey: string,
): Array<ConfigPart> {
const {
env,
plugins,
presets,
passPerPreset,
extends: extendsPath,
...options
} = opts;
const raw = [];
if (env) {
raw.push(...flattenArgumentsEnvOptionsParts(env)(dirname)(envKey));
}
if (Object.keys(options).length > 0) {
raw.push(...flattenOptionsParts(buildArgumentsItem(options, dirname)));
}
if (plugins) {
raw.push(...flattenArgumentsPluginsOptionsParts(plugins)(dirname));
}
if (presets) {
raw.push(
...flattenArgumentsPresetsOptionsParts(presets)(!!passPerPreset)(dirname),
);
}
if (extendsPath != null) {
raw.push(
...flattenOptionsParts(
buildArgumentsItem({ extends: extendsPath }, dirname),
),
);
}
return raw;
}
/**
* For the top-level 'options' object, we cache the env list based on
* the object identity of the 'env' object.
*/
const flattenArgumentsEnvOptionsParts = makeWeakCache((env: {}) => {
const options: ValidatedOptions = { env };
return makeStrongCache((dirname: string) =>
flattenOptionsPartsLookup(buildArgumentsItem(options, dirname)),
);
});
/**
* For the top-level 'options' object, we cache the plugin list based on
* the object identity of the 'plugins' object.
*/
const flattenArgumentsPluginsOptionsParts = makeWeakCache(
(plugins: PluginList) => {
const options: ValidatedOptions = { plugins };
return makeStrongCache((dirname: string) =>
flattenOptionsParts(buildArgumentsItem(options, dirname)),
);
},
);
/**
* For the top-level 'options' object, we cache the preset list based on
* the object identity of the 'presets' object.
*/
const flattenArgumentsPresetsOptionsParts = makeWeakCache(
(presets: PluginList) =>
makeStrongCache((passPerPreset: boolean) => {
// The concept of passPerPreset is integrally tied to the preset list
// so unfortunately we need to copy both values here, adding an extra
// layer of caching functions.
const options = { presets, passPerPreset };
return makeStrongCache((dirname: string) =>
flattenOptionsParts(buildArgumentsItem(options, dirname)),
);
}),
);
function buildArgumentsItem(
options: ValidatedOptions,
dirname: string,
): ConfigItem {
return {
type: "arguments",
options,
alias: "base",
dirname,
};
}
/**
* Given a config from a specific file, return a list of ConfigPart objects
* with object identity preserved for all 'config' part objects for use
* with caching later in config processing.
*/
const flattenFileOptionsParts = makeWeakCache((file: ConfigFile) => {
return flattenOptionsPartsLookup({
type: "file",
options: validate("file", file.options),
alias: file.filepath,
dirname: file.dirname,
});
});
/**
* Given a config, create a function that will return the config parts for
* the environment passed as the first argument.
*/
function flattenOptionsPartsLookup(
config: ConfigItem,
): (string | null) => Array<ConfigPart> {
const parts = flattenOptionsParts(config);
const def = parts.filter(part => part.activeEnv === null);
const lookup = new Map();
parts.forEach(part => {
if (part.activeEnv !== null) lookup.set(part.activeEnv, []);
});
for (const [activeEnv, values] of lookup) {
parts.forEach(part => {
if (part.activeEnv === null || part.activeEnv === activeEnv) {
values.push(part);
}
});
}
return envKey => lookup.get(envKey) || def;
}
/**
* Given a generic config object, flatten it into its various parts so that
* then can be cached and processed later.
*/
function flattenOptionsParts(
config: ConfigItem,
activeEnv: string | null = null,
): Array<ConfigPart> {
const { options: rawOpts, alias, dirname } = config;
const parts = [];
if (rawOpts.env) {
for (const envKey of Object.keys(rawOpts.env)) {
if (rawOpts.env[envKey]) {
parts.push(
...flattenOptionsParts(
{
type: "env",
options: rawOpts.env[envKey],
alias: alias + `.env.${envKey}`,
dirname,
},
envKey,
),
);
}
}
}
parts.push({
part: "config",
config,
ignore: rawOpts.ignore,
only: rawOpts.only,
activeEnv,
});
if (rawOpts.extends != null) {
parts.push({
part: "extends",
path: rawOpts.extends,
dirname,
activeEnv,
});
}
return parts;
}
/**
* Track a given file and expose function to check if it should be ignored.
*/
class LoadedFile {
filename: string;
possibleDirs: null | Array<string> = null;
constructor(filename) {
this.filename = filename;
}
/**
* Tests if a filename should be ignored based on "ignore" and "only" options.
*/
shouldIgnore(
ignore: ?IgnoreList,
only: ?IgnoreList,
dirname: string,
): boolean {
if (ignore) {
if (this._matchesPatterns(ignore, dirname)) {
debug(
"Ignored %o because it matched one of %O from %o",
this.filename,
ignore,
dirname,
);
return true;
}
}
if (only) {
if (!this._matchesPatterns(only, dirname)) {
debug(
"Ignored %o because it failed to match one of %O from %o",
this.filename,
only,
dirname,
);
return true;
}
}
return false;
}
/**
* Returns result of calling function with filename if pattern is a function.
* Otherwise returns result of matching pattern Regex with filename.
*/
_matchesPatterns(patterns: IgnoreList, dirname: string): 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 = this.filename;
if (res.some(re => re.test(filename))) return true;
if (fns.some(fn => fn(filename))) return true;
if (strings.length > 0) {
let possibleDirs = this.possibleDirs;
// Lazy-init so we don't initialize this for files that have no glob patterns.
if (!possibleDirs) {
possibleDirs = this.possibleDirs = [];
possibleDirs.push(filename);
let current = filename;
while (true) {
const previous = current;
current = path.dirname(current);
if (previous === current) break;
possibleDirs.push(current);
}
}
const absolutePatterns = strings.map(pattern => {
// Preserve the "!" prefix so that micromatch can use it for negation.
const negate = pattern[0] === "!";
if (negate) pattern = pattern.slice(1);
return (negate ? "!" : "") + path.resolve(dirname, pattern);
});
if (
micromatch(possibleDirs, absolutePatterns, { nocase: true }).length > 0
) {
return true;
}
}
return false;
}
}

View File

@@ -1,29 +1,34 @@
// @flow
type CacheConfigurator = CacheConfiguratorFn & CacheConfiguratorObj;
type SimpleCacheConfigurator = SimpleCacheConfiguratorFn &
SimpleCacheConfiguratorObj;
type CacheConfiguratorFn = {
type SimpleCacheConfiguratorFn = {
(boolean): void,
<T>(handler: () => T): T,
};
type CacheConfiguratorObj = {
type SimpleCacheConfiguratorObj = {
forever: () => void,
never: () => void,
using: <T>(handler: () => T) => T,
invalidate: <T>(handler: () => T) => T,
};
type CacheEntry<ResultT> = Array<[ResultT, () => boolean]>;
type CacheEntry<ResultT, SideChannel> = Array<{
value: ResultT,
valid: SideChannel => boolean,
}>;
export type { CacheConfigurator };
/**
* Given a function with a single argument, cache its results based on its argument and how it
* configures its caching behavior. Cached values are stored strongly.
*/
export function makeStrongCache<ArgT, ResultT>(
handler: (ArgT, CacheConfigurator) => ResultT,
autoPermacache?: boolean,
): ArgT => ResultT {
return makeCachedFunction(new Map(), handler, autoPermacache);
export function makeStrongCache<ArgT, ResultT, SideChannel>(
handler: (ArgT, CacheConfigurator<SideChannel>) => ResultT,
): (ArgT, SideChannel) => ResultT {
return makeCachedFunction(new Map(), handler);
}
/**
@@ -31,190 +36,182 @@ export function makeStrongCache<ArgT, ResultT>(
* configures its caching behavior. Cached values are stored weakly and the function argument must be
* an object type.
*/
export function makeWeakCache<ArgT: {} | Array<*> | $ReadOnlyArray<*>, ResultT>(
handler: (ArgT, CacheConfigurator) => ResultT,
autoPermacache?: boolean,
): ArgT => ResultT {
return makeCachedFunction(new WeakMap(), handler, autoPermacache);
export function makeWeakCache<
ArgT: {} | Array<*> | $ReadOnlyArray<*>,
ResultT,
SideChannel,
>(
handler: (ArgT, CacheConfigurator<SideChannel>) => ResultT,
): (ArgT, SideChannel) => ResultT {
return makeCachedFunction(new WeakMap(), handler);
}
type CacheMap<ArgT, ResultT> =
| Map<ArgT, CacheEntry<ResultT>>
| WeakMap<ArgT, CacheEntry<ResultT>>;
type CacheMap<ArgT, ResultT, SideChannel> =
| Map<ArgT, CacheEntry<ResultT, SideChannel>>
| WeakMap<ArgT, CacheEntry<ResultT, SideChannel>>;
function makeCachedFunction<ArgT, ResultT, Cache: CacheMap<ArgT, ResultT>>(
function makeCachedFunction<
ArgT,
ResultT,
SideChannel,
Cache: CacheMap<ArgT, ResultT, SideChannel>,
>(
callCache: Cache,
handler: (ArgT, CacheConfigurator) => ResultT,
autoPermacache: boolean = true,
): ArgT => ResultT {
return function cachedFunction(arg) {
let cachedValue: CacheEntry<ResultT> | void = callCache.get(arg);
handler: (ArgT, CacheConfigurator<SideChannel>) => ResultT,
): (ArgT, SideChannel) => ResultT {
return function cachedFunction(arg, data) {
let cachedValue: CacheEntry<ResultT, SideChannel> | void = callCache.get(
arg,
);
if (cachedValue) {
for (const [value, valid] of cachedValue) {
if (valid()) return value;
for (const { value, valid } of cachedValue) {
if (valid(data)) return value;
}
}
const { cache, result, deactivate } = makeCacheConfig();
const cache = new CacheConfigurator(data);
const value = handler(arg, cache);
if (autoPermacache && !result.configured) cache.forever();
if (!cache.configured()) cache.forever();
deactivate();
cache.deactivate();
if (!result.configured) {
// eslint-disable-next-line max-len
throw new Error(
[
"Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured",
"for various types of caching, using the first param of their handler functions:",
"",
"module.exports = function(api) {",
" // The API exposes the following:",
"",
" // Cache the returned value forever and don't call this function again.",
" api.cache(true);",
"",
" // Don't cache at all. Not recommended because it will be very slow.",
" api.cache(false);",
"",
" // Cached based on the value of some function. If this function returns a value different from",
" // a previously-encountered value, the plugins will re-evaluate.",
" var env = api.cache(() => process.env.NODE_ENV);",
"",
" // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for",
" // any possible NODE_ENV value that might come up during plugin execution.",
' var isProd = api.cache(() => process.env.NODE_ENV === "production");',
"",
" // .cache(fn) will perform a linear search though instances to find the matching plugin based",
" // based on previous instantiated plugins. If you want to recreate the plugin and discard the",
" // previous instance whenever something changes, you may use:",
' var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production");',
"",
" // Note, we also expose the following more-verbose versions of the above examples:",
" api.cache.forever(); // api.cache(true)",
" api.cache.never(); // api.cache(false)",
" api.cache.using(fn); // api.cache(fn)",
"",
" // Return the value that will be cached.",
" return { };",
"};",
].join("\n"),
);
}
if (!result.never) {
if (result.forever) {
cachedValue = [[value, () => true]];
} else if (result.invalidate) {
cachedValue = [[value, result.valid]];
} else {
cachedValue = cachedValue || [];
cachedValue.push([value, result.valid]);
}
callCache.set(arg, cachedValue);
switch (cache.mode()) {
case "forever":
cachedValue = [{ value, valid: () => true }];
callCache.set(arg, cachedValue);
break;
case "invalidate":
cachedValue = [{ value, valid: cache.validator() }];
callCache.set(arg, cachedValue);
break;
case "valid":
if (cachedValue) {
cachedValue.push({ value, valid: cache.validator() });
} else {
cachedValue = [{ value, valid: cache.validator() }];
callCache.set(arg, cachedValue);
}
}
return value;
};
}
function makeCacheConfig(): {
cache: CacheConfigurator,
result: *,
deactivate: () => void,
} {
const pairs = [];
class CacheConfigurator<SideChannel = void> {
_active: boolean = true;
_never: boolean = false;
_forever: boolean = false;
_invalidate: boolean = false;
const result = {
configured: false,
never: false,
forever: false,
invalidate: false,
valid: () => pairs.every(([key, fn]) => key === fn()),
};
_configured: boolean = false;
let active = true;
const deactivate = () => {
active = false;
};
_pairs: Array<[mixed, (SideChannel) => mixed]> = [];
const cache: CacheConfigurator = Object.assign(
(function cacheFn(val) {
if (typeof val === "boolean") {
if (val) cache.forever();
else cache.never();
return;
}
_data: SideChannel;
return cache.using(val);
}: any),
({
forever() {
if (!active) {
throw new Error(
"Cannot change caching after evaluation has completed.",
);
}
if (result.never) {
throw new Error("Caching has already been configured with .never()");
}
result.forever = true;
result.configured = true;
},
never() {
if (!active) {
throw new Error(
"Cannot change caching after evaluation has completed.",
);
}
if (result.forever) {
throw new Error(
"Caching has already been configured with .forever()",
);
}
result.never = true;
result.configured = true;
},
using<T>(handler: () => T): T {
if (!active) {
throw new Error(
"Cannot change caching after evaluation has completed.",
);
}
if (result.never || result.forever) {
throw new Error(
"Caching has already been configured with .never or .forever()",
);
}
result.configured = true;
constructor(data: SideChannel) {
this._data = data;
}
const key = handler();
pairs.push([key, handler]);
return key;
},
invalidate<T>(handler: () => T): T {
if (!active) {
throw new Error(
"Cannot change caching after evaluation has completed.",
);
}
if (result.never || result.forever) {
throw new Error(
"Caching has already been configured with .never or .forever()",
);
}
result.invalidate = true;
result.configured = true;
simple() {
return makeSimpleConfigurator(this);
}
const key = handler();
pairs.push([key, handler]);
return key;
},
}: CacheConfiguratorObj),
);
mode() {
if (this._never) return "never";
if (this._forever) return "forever";
if (this._invalidate) return "invalidate";
return "valid";
}
return { cache, result, deactivate };
forever() {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._never) {
throw new Error("Caching has already been configured with .never()");
}
this._forever = true;
this._configured = true;
}
never() {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._forever) {
throw new Error("Caching has already been configured with .forever()");
}
this._never = true;
this._configured = true;
}
using<T>(handler: SideChannel => T): T {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._never || this._forever) {
throw new Error(
"Caching has already been configured with .never or .forever()",
);
}
this._configured = true;
const key = handler(this._data);
this._pairs.push([key, handler]);
return key;
}
invalidate<T>(handler: SideChannel => T): T {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._never || this._forever) {
throw new Error(
"Caching has already been configured with .never or .forever()",
);
}
this._invalidate = true;
this._configured = true;
const key = handler(this._data);
this._pairs.push([key, handler]);
return key;
}
validator(): SideChannel => boolean {
const pairs = this._pairs;
return (data: SideChannel) => pairs.every(([key, fn]) => key === fn(data));
}
deactivate() {
this._active = false;
}
configured() {
return this._configured;
}
}
function makeSimpleConfigurator(
cache: CacheConfigurator<any>,
): SimpleCacheConfigurator {
function cacheFn(val) {
if (typeof val === "boolean") {
if (val) cache.forever();
else cache.never();
return;
}
return cache.using(val);
}
cacheFn.forever = () => cache.forever();
cacheFn.never = () => cache.never();
cacheFn.using = cb => cache.using(() => cb());
cacheFn.invalidate = cb => cache.invalidate(() => cb());
return (cacheFn: any);
}

View File

@@ -0,0 +1,452 @@
// @flow
import path from "path";
import micromatch from "micromatch";
import buildDebug from "debug";
import {
validate,
type ValidatedOptions,
type IgnoreList,
} from "./validation/options";
const debug = buildDebug("babel:config:config-chain");
import {
findBabelrc,
findBabelignore,
loadConfig,
type ConfigFile,
} from "./files";
import { makeWeakCache, makeStrongCache } from "./caching";
import {
createCachedDescriptors,
createUncachedDescriptors,
type UnloadedDescriptor,
type OptionsAndDescriptors,
type ValidatedFile,
} from "./config-descriptors";
export type ConfigChain = {
plugins: Array<UnloadedDescriptor>,
presets: Array<UnloadedDescriptor>,
options: Array<ValidatedOptions>,
};
export type PresetInstance = {
options: ValidatedOptions,
alias: string,
dirname: string,
};
type ConfigContext = {
filename: string | null,
cwd: string,
envName: string,
};
type ConfigContextNamed = {
...ConfigContext,
filename: string,
};
/**
* Build a config chain for a given preset.
*/
export const buildPresetChain = makeWeakCache(
({ dirname, options, alias }: PresetInstance): ConfigChain => {
const result = createUncachedDescriptors(dirname, options, alias);
const { plugins, presets } = result;
return {
plugins: plugins(),
presets: presets(),
options: [normalizeOptions(result.options)],
};
},
);
/**
* Build a config chain for Babel's full root configuration.
*/
export function buildRootChain(
cwd: string,
opts: ValidatedOptions,
envName: string,
): ConfigChain | null {
const context = {
filename: opts.filename ? path.resolve(cwd, opts.filename) : null,
cwd,
envName,
};
const programmaticChain = loadProgrammaticChain(
{
options: opts,
dirname: context.cwd,
},
context,
);
if (!programmaticChain) return null;
const fileChain = emptyChain();
// resolve all .babelrc files
if (opts.babelrc !== false && context.filename !== null) {
const filename = context.filename;
const babelrcFile = findBabelrc(filename, context.envName);
if (babelrcFile) {
const result = loadFileChain(babelrcFile, context);
if (!result) return null;
mergeChain(fileChain, result);
}
const babelignoreFile = findBabelignore(filename);
if (
babelignoreFile &&
shouldIgnore(
context,
babelignoreFile.ignore,
null,
babelignoreFile.dirname,
)
) {
return null;
}
}
// Insert file chain in front so programmatic options have priority
// over configuration file chain items.
const chain = mergeChain(
mergeChain(emptyChain(), fileChain),
programmaticChain,
);
return {
plugins: dedupDescriptors(chain.plugins),
presets: dedupDescriptors(chain.presets),
options: chain.options.map(o => normalizeOptions(o)),
};
}
/**
* Build a config chain for just the programmatic options passed into Babel.
*/
const loadProgrammaticChain = makeChainWalker({
init: arg => arg,
root: input => buildRootDescriptors(input, "base", createCachedDescriptors),
env: (input, envName) =>
buildEnvDescriptors(input, "base", createCachedDescriptors, envName),
});
/**
* Build a config chain for a given file.
*/
const loadFileChain = makeChainWalker({
init: input => validateFile(input),
root: file => loadFileDescriptors(file),
env: (file, envName) => loadFileEnvDescriptors(file)(envName),
});
const validateFile = makeWeakCache((file: ConfigFile): ValidatedFile => ({
filepath: file.filepath,
dirname: file.dirname,
options: validate("file", file.options),
}));
const loadFileDescriptors = makeWeakCache((file: ValidatedFile) =>
buildRootDescriptors(file, file.filepath, createUncachedDescriptors),
);
const loadFileEnvDescriptors = makeWeakCache((file: ValidatedFile) =>
makeStrongCache((envName: string) =>
buildEnvDescriptors(
file,
file.filepath,
createUncachedDescriptors,
envName,
),
),
);
function buildRootDescriptors({ dirname, options }, alias, descriptors) {
return descriptors(dirname, options, alias);
}
function buildEnvDescriptors(
{ dirname, options },
alias,
descriptors,
envName,
) {
const opts = options.env && options.env[envName];
return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null;
}
function makeChainWalker<
ArgT,
InnerT: { options: ValidatedOptions, dirname: string },
>({
init,
root,
env,
}: {
init: ArgT => InnerT,
root: InnerT => OptionsAndDescriptors,
env: (InnerT, string) => OptionsAndDescriptors | null,
}): (ArgT, ConfigContext, Set<ConfigFile> | void) => ConfigChain | null {
return (arg, context, files = new Set()) => {
const input = init(arg);
const { dirname } = input;
const flattenedConfigs = [];
const rootOpts = root(input);
flattenedConfigs.push(rootOpts);
const envOpts = env(input, context.envName);
if (envOpts) {
flattenedConfigs.push(envOpts);
}
// Process 'ignore' and 'only' before 'extends' items are processed so
// that we don't do extra work loading extended configs if a file is
// ignored.
if (
flattenedConfigs.some(({ options: { ignore, only } }) =>
shouldIgnore(context, ignore, only, dirname),
)
) {
return null;
}
const chain = emptyChain();
for (const op of flattenedConfigs) {
if (!mergeExtendsChain(chain, op.options, dirname, context, files)) {
return null;
}
mergeChainOpts(chain, op);
}
return chain;
};
}
function mergeExtendsChain(
chain: ConfigChain,
opts: ValidatedOptions,
dirname: string,
context: ConfigContext,
files: Set<ConfigFile>,
): boolean {
if (opts.extends === undefined) return true;
const file = loadConfig(opts.extends, dirname, context.envName);
if (files.has(file)) {
throw new Error(
`Configuration cycle detected loading ${file.filepath}.\n` +
`File already loaded following the config chain:\n` +
Array.from(files, file => ` - ${file.filepath}`).join("\n"),
);
}
files.add(file);
const fileChain = loadFileChain(file, context, files);
files.delete(file);
if (!fileChain) return false;
mergeChain(chain, fileChain);
return true;
}
function mergeChain(target: ConfigChain, source: ConfigChain): ConfigChain {
target.options.push(...source.options);
target.plugins.push(...source.plugins);
target.presets.push(...source.presets);
return target;
}
function mergeChainOpts(
target: ConfigChain,
{ options, plugins, presets }: OptionsAndDescriptors,
): ConfigChain {
target.options.push(options);
target.plugins.push(...plugins());
target.presets.push(...presets());
return target;
}
function emptyChain(): ConfigChain {
return {
options: [],
presets: [],
plugins: [],
};
}
function normalizeOptions(opts: ValidatedOptions): ValidatedOptions {
const options = Object.assign({}, opts);
delete options.extends;
delete options.env;
delete options.plugins;
delete options.presets;
delete options.passPerPreset;
delete options.ignore;
delete options.only;
// "sourceMap" is just aliased to sourceMap, so copy it over as
// we merge the options together.
if (options.sourceMap) {
options.sourceMaps = options.sourceMap;
delete options.sourceMap;
}
return options;
}
function dedupDescriptors(
items: Array<UnloadedDescriptor>,
): Array<UnloadedDescriptor> {
const map: Map<
Function,
Map<string | void, { value: UnloadedDescriptor | null }>,
> = new Map();
const descriptors = [];
for (const item of items) {
if (typeof item.value === "function") {
const fnKey = item.value;
let nameMap = map.get(fnKey);
if (!nameMap) {
nameMap = new Map();
map.set(fnKey, nameMap);
}
let desc = nameMap.get(item.name);
if (!desc) {
desc = { value: null };
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;
}
} else {
descriptors.push({ value: item });
}
}
return descriptors.reduce((acc, desc) => {
if (desc.value) acc.push(desc.value);
return acc;
}, []);
}
/**
* Tests if a filename should be ignored based on "ignore" and "only" options.
*/
function shouldIgnore(
context: ConfigContext,
ignore: ?IgnoreList,
only: ?IgnoreList,
dirname: string,
): boolean {
if (context.filename === null) return false;
// $FlowIgnore - Flow refinements aren't quite smart enough for this :(
const ctx: ConfigContextNamed = context;
if (ignore) {
if (matchesPatterns(ctx, ignore, dirname)) {
debug(
"Ignored %o because it matched one of %O from %o",
context.filename,
ignore,
dirname,
);
return true;
}
}
if (only) {
if (!matchesPatterns(ctx, only, dirname)) {
debug(
"Ignored %o because it failed to match one of %O from %o",
context.filename,
only,
dirname,
);
return true;
}
}
return false;
}
/**
* Returns result of calling function with filename if pattern is a function.
* Otherwise returns result of matching pattern Regex with filename.
*/
function matchesPatterns(
context: ConfigContextNamed,
patterns: IgnoreList,
dirname: string,
): 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) pattern = pattern.slice(1);
return (negate ? "!" : "") + path.resolve(dirname, pattern);
});
if (
micromatch(possibleDirs, absolutePatterns, { nocase: true }).length > 0
) {
return true;
}
}
return false;
}
const getPossibleDirs = makeWeakCache((context: ConfigContextNamed) => {
let current = context.filename;
if (current === null) return [];
const possibleDirs = [current];
while (true) {
const previous = current;
current = path.dirname(current);
if (previous === current) break;
possibleDirs.push(current);
}
return possibleDirs;
});

View File

@@ -0,0 +1,272 @@
// @flow
import { loadPlugin, loadPreset } from "./files";
import {
makeWeakCache,
makeStrongCache,
type CacheConfigurator,
} from "./caching";
import type {
ValidatedOptions,
PluginList,
PluginItem,
} from "./validation/options";
// Represents a config object and functions to lazily load the descriptors
// for the plugins and presets so we don't load the plugins/presets unless
// the options object actually ends up being applicable.
export type OptionsAndDescriptors = {
options: ValidatedOptions,
plugins: () => Array<UnloadedDescriptor>,
presets: () => Array<UnloadedDescriptor>,
};
// Represents a plugin or presets at a given location in a config object.
// At this point these have been resolved to a specific object or function,
// but have not yet been executed to call functions with options.
export type UnloadedDescriptor = {
name: string | void,
value: {} | Function,
options: {} | void | false,
dirname: string,
alias: string,
ownPass?: boolean,
};
export type ValidatedFile = {
filepath: string,
dirname: string,
options: ValidatedOptions,
};
/**
* Create a set of descriptors from a given options object, preserving
* descriptor identity based on the identity of the plugin/preset arrays
* themselves.
*/
export function createCachedDescriptors(
dirname: string,
options: ValidatedOptions,
alias: string,
): OptionsAndDescriptors {
const { plugins, presets, passPerPreset } = options;
return {
options,
plugins: plugins
? () => createCachedPluginDescriptors(plugins, dirname)(alias)
: () => [],
presets: presets
? () =>
createCachedPresetDescriptors(presets, dirname)(alias)(
!!passPerPreset,
)
: () => [],
};
}
/**
* Create a set of descriptors from a given options object, with consistent
* identity for the descriptors, but not caching based on any specific identity.
*/
export function createUncachedDescriptors(
dirname: string,
options: ValidatedOptions,
alias: string,
): OptionsAndDescriptors {
// The returned result here is cached to represent a config object in
// memory, so we build and memoize the descriptors to ensure the same
// values are returned consistently.
let plugins;
let presets;
return {
options,
plugins: () => {
if (!plugins) {
plugins = createPluginDescriptors(
options.plugins || [],
dirname,
alias,
);
}
return plugins;
},
presets: () => {
if (!presets) {
presets = createPresetDescriptors(
options.presets || [],
dirname,
alias,
!!options.passPerPreset,
);
}
return presets;
},
};
}
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),
),
);
},
);
const createCachedPluginDescriptors = makeWeakCache(
(items: PluginList, cache: CacheConfigurator<string>) => {
const dirname = cache.using(dir => dir);
return makeStrongCache((alias: string) =>
createPluginDescriptors(items, dirname, alias),
);
},
);
function createPresetDescriptors(
items: PluginList,
dirname: string,
alias: string,
passPerPreset: boolean,
): Array<UnloadedDescriptor> {
return createDescriptors("preset", items, dirname, alias, passPerPreset);
}
function createPluginDescriptors(
items: PluginList,
dirname: string,
alias: string,
): Array<UnloadedDescriptor> {
return createDescriptors("plugin", items, dirname, alias);
}
function createDescriptors(
type: "plugin" | "preset",
items: PluginList,
dirname: string,
alias: string,
ownPass?: boolean,
): Array<UnloadedDescriptor> {
const descriptors = items.map((item, index) =>
createDescriptor(
item,
type === "plugin" ? loadPlugin : loadPreset,
dirname,
{
index,
alias,
ownPass: !!ownPass,
},
),
);
assertNoDuplicates(descriptors);
return descriptors;
}
/**
* Given a plugin/preset item, resolve it into a standard format.
*/
function createDescriptor(
pair: PluginItem,
resolver,
dirname,
{
index,
alias,
ownPass,
}: {
index: number,
alias: string,
ownPass?: boolean,
},
): UnloadedDescriptor {
let name;
let options;
let value = pair;
if (Array.isArray(value)) {
if (value.length === 3) {
// $FlowIgnore - Flow doesn't like the multiple tuple types.
[value, options, name] = value;
} else {
[value, options] = value;
}
}
let filepath = null;
if (typeof value === "string") {
({ filepath, value } = resolver(value, dirname));
}
if (!value) {
throw new Error(`Unexpected falsy value: ${String(value)}`);
}
if (typeof value === "object" && value.__esModule) {
if (value.default) {
value = value.default;
} else {
throw new Error("Must export a default export when using ES6 modules.");
}
}
if (typeof value !== "object" && typeof value !== "function") {
throw new Error(
`Unsupported format: ${typeof value}. Expected an object or a function.`,
);
}
if (filepath !== null && typeof value === "object" && value) {
// We allow object values for plugins/presets nested directly within a
// config object, because it can be useful to define them in nested
// configuration contexts.
throw new Error(
"Plugin/Preset files are not allowed to export objects, only functions.",
);
}
return {
name,
alias: filepath || `${alias}$${index}`,
value,
options,
dirname,
ownPass,
};
}
function assertNoDuplicates(items: Array<UnloadedDescriptor>): void {
const map = new Map();
for (const item of items) {
if (typeof item.value !== "function") continue;
let nameMap = map.get(item.value);
if (!nameMap) {
nameMap = new Set();
map.set(item.value, nameMap);
}
if (nameMap.has(item.name)) {
throw new Error(
[
`Duplicate plugin/preset detected.`,
`If you'd like to use two separate instances of a plugin,`,
`they neen separate names, e.g.`,
``,
` plugins: [`,
` ['some-plugin', {}],`,
` ['some-plugin', {}, 'some unique name'],`,
` ]`,
].join("\n"),
);
}
nameMap.add(item.name);
}
}

View File

@@ -0,0 +1,294 @@
// @flow
import buildDebug from "debug";
import path from "path";
import fs from "fs";
import json5 from "json5";
import resolve from "resolve";
import { makeStrongCache, type CacheConfigurator } from "../caching";
const debug = buildDebug("babel:config:loading:files:configuration");
export type ConfigFile = {
filepath: string,
dirname: string,
options: {},
};
export type IgnoreFile = {
filepath: string,
dirname: string,
ignore: Array<string>,
};
const BABELRC_FILENAME = ".babelrc";
const BABELRC_JS_FILENAME = ".babelrc.js";
const PACKAGE_FILENAME = "package.json";
const BABELIGNORE_FILENAME = ".babelignore";
export function findBabelrc(
filepath: string,
envName: string,
): ConfigFile | null {
const dirname = path.dirname(filepath);
let loc = dirname;
while (true) {
const conf = [
BABELRC_FILENAME,
BABELRC_JS_FILENAME,
PACKAGE_FILENAME,
].reduce((previousConfig: ConfigFile | null, name) => {
const filepath = path.join(loc, name);
const config = readConfig(filepath, envName);
if (config && previousConfig) {
throw new Error(
`Multiple configuration files found. Please remove one:\n` +
` - ${path.basename(previousConfig.filepath)}\n` +
` - ${name}\n` +
`from ${loc}`,
);
}
return config || previousConfig;
}, null);
if (conf) {
debug("Found configuration %o from %o.", conf.filepath, dirname);
return conf;
}
const nextLoc = path.dirname(loc);
if (loc === nextLoc) break;
loc = nextLoc;
}
return null;
}
export function findBabelignore(filepath: string): IgnoreFile | null {
const dirname = path.dirname(filepath);
let loc = dirname;
while (true) {
const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
const ignore = readIgnoreConfig(ignoreLoc);
if (ignore) {
debug("Found ignore %o from %o.", ignore.filepath, dirname);
return ignore;
}
const nextLoc = path.dirname(loc);
if (loc === nextLoc) break;
loc = nextLoc;
}
return null;
}
export function loadConfig(
name: string,
dirname: string,
envName: string,
): ConfigFile {
const filepath = resolve.sync(name, { basedir: dirname });
const conf = readConfig(filepath, envName);
if (!conf) {
throw new Error(`Config file ${filepath} contains no configuration data`);
}
debug("Loaded config %o from $o.", name, dirname);
return conf;
}
/**
* 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) {
return path.extname(filepath) === ".js"
? readConfigJS(filepath, { envName })
: readConfigFile(filepath);
}
const LOADING_CONFIGS = new Set();
const readConfigJS = makeStrongCache(
(filepath, cache: CacheConfigurator<{ envName: string }>) => {
if (!fs.existsSync(filepath)) {
cache.forever();
return null;
}
// The `require()` call below can make this code reentrant if a require hook like @babel/register has been
// loaded into the system. That would cause Babel to attempt to compile the `.babelrc.js` file as it loads
// below. To cover this case, we auto-ignore re-entrant config processing.
if (LOADING_CONFIGS.has(filepath)) {
cache.never();
debug("Auto-ignoring usage of config %o.", filepath);
return {
filepath,
dirname: path.dirname(filepath),
options: {},
};
}
let options;
try {
LOADING_CONFIGS.add(filepath);
// $FlowIssue
const configModule = (require(filepath): mixed);
options =
configModule && configModule.__esModule
? configModule.default || undefined
: configModule;
} catch (err) {
err.message = `${filepath}: Error while loading config - ${err.message}`;
throw err;
} finally {
LOADING_CONFIGS.delete(filepath);
}
if (typeof options === "function") {
options = options({
cache: cache.simple(),
// Expose ".env()" so people can easily get the same env that we expose using the "env" key.
env: () => cache.using(data => data.envName),
async: () => false,
});
if (!cache.configured()) throwConfigError();
}
if (!options || typeof options !== "object" || Array.isArray(options)) {
throw new Error(
`${filepath}: Configuration should be an exported JavaScript object.`,
);
}
if (typeof options.then === "function") {
throw new Error(
`You appear to be using an async configuration, ` +
`which your current version of Babel does not support. ` +
`We may add support for this in the future, ` +
`but if you're on the most recent version of @babel/core and still ` +
`seeing this error, then you'll need to synchronously return your config.`,
);
}
return {
filepath,
dirname: path.dirname(filepath),
options,
};
},
);
const readConfigFile = makeStaticFileCache((filepath, content) => {
let options;
if (path.basename(filepath) === PACKAGE_FILENAME) {
try {
options = JSON.parse(content).babel;
} catch (err) {
err.message = `${filepath}: Error while parsing JSON - ${err.message}`;
throw err;
}
if (!options) return null;
} else {
try {
options = json5.parse(content);
} catch (err) {
err.message = `${filepath}: Error while parsing config - ${err.message}`;
throw err;
}
if (!options) throw new Error(`${filepath}: No config detected`);
}
if (typeof options !== "object") {
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
}
if (Array.isArray(options)) {
throw new Error(`${filepath}: Expected config object but found array`);
}
return {
filepath,
dirname: path.dirname(filepath),
options,
};
});
const readIgnoreConfig = makeStaticFileCache((filepath, content) => {
const ignore = content
.split("\n")
.map(line => line.replace(/#(.*?)$/, "").trim())
.filter(line => !!line);
return {
filepath,
dirname: path.dirname(filepath),
ignore,
};
});
function makeStaticFileCache<T>(fn: (string, string) => T): string => T | null {
return makeStrongCache((filepath, cache) => {
if (cache.invalidate(() => fileMtime(filepath)) === null) {
cache.forever();
return null;
}
return fn(filepath, fs.readFileSync(filepath, "utf8"));
});
}
function fileMtime(filepath: string): number | null {
try {
return +fs.statSync(filepath).mtime;
} catch (e) {
if (e.code !== "ENOENT") throw e;
}
return null;
}
function throwConfigError() {
throw new Error(`\
Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured
for various types of caching, using the first param of their handler functions:
module.exports = function(api) {
// The API exposes the following:
// Cache the returned value forever and don't call this function again.
api.cache(true);
// Don't cache at all. Not recommended because it will be very slow.
api.cache(false);
// Cached based on the value of some function. If this function returns a value different from
// a previously-encountered value, the plugins will re-evaluate.
var env = api.cache(() => process.env.NODE_ENV);
// If testing for a specific env, we recommend specifics to avoid instantiating a plugin for
// any possible NODE_ENV value that might come up during plugin execution.
var isProd = api.cache(() => process.env.NODE_ENV === "production");
// .cache(fn) will perform a linear search though instances to find the matching plugin based
// based on previous instantiated plugins. If you want to recreate the plugin and discard the
// previous instance whenever something changes, you may use:
var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production");
// Note, we also expose the following more-verbose versions of the above examples:
api.cache.forever(); // api.cache(true)
api.cache.never(); // api.cache(false)
api.cache.using(fn); // api.cache(fn)
// Return the value that will be cached.
return { };
};`);
}

View File

@@ -6,9 +6,22 @@ export type ConfigFile = {
options: {},
};
export type IgnoreFile = {
filepath: string,
dirname: string,
ignore: Array<string>,
};
export function findBabelrc(
filepath: string,
envName: string, // eslint-disable-line no-unused-vars
): ConfigFile | null {
return null;
}
// eslint-disable-next-line no-unused-vars
export function findConfigs(dirname: string): Array<ConfigFile> {
return [];
export function findBabelignore(filepath: string): IgnoreFile | null {
return null;
}
export function loadConfig(name: string, dirname: string): ConfigFile {

View File

@@ -1,9 +1,31 @@
// @flow
import type Plugin from "./plugin";
import manageOptions from "./option-manager";
import path from "path";
import * as context from "../index";
import Plugin from "./plugin";
import merge from "lodash/merge";
import {
buildRootChain,
buildPresetChain,
type ConfigChain,
type PresetInstance,
} from "./config-chain";
import type { UnloadedDescriptor } from "./config-descriptors";
import traverse from "@babel/traverse";
import clone from "lodash/clone";
import { makeWeakCache, type CacheConfigurator } from "./caching";
import { getEnv } from "./helpers/environment";
import { validate } from "./validation/options";
import { validatePluginObject } from "./validation/plugins";
export type { InputOptions } from "./options";
type LoadedDescriptor = {
value: {},
options: {},
dirname: string,
alias: string,
};
export type { InputOptions } from "./validation/options";
export type ResolvedConfig = {
options: Object,
@@ -14,13 +36,257 @@ export type { Plugin };
export type PluginPassList = Array<Plugin>;
export type PluginPasses = Array<PluginPassList>;
/**
* Standard API for loading Babel configuration data. Not for public consumption.
*/
export default function loadConfig(opts: mixed): ResolvedConfig | null {
if (opts != null && (typeof opts !== "object" || Array.isArray(opts))) {
export default function loadConfig(inputOpts: mixed): ResolvedConfig | null {
if (
inputOpts != null &&
(typeof inputOpts !== "object" || Array.isArray(inputOpts))
) {
throw new Error("Babel options must be an object, null, or undefined");
}
return manageOptions(opts || {});
const args = inputOpts ? validate("arguments", inputOpts) : {};
const { envName = getEnv(), cwd = "." } = args;
const absoluteCwd = path.resolve(cwd);
const configChain = buildRootChain(absoluteCwd, args, envName);
if (!configChain) return null;
const optionDefaults = {};
const options = {};
const passes = [[]];
try {
(function recurseDescriptors(
config: {
plugins: Array<UnloadedDescriptor>,
presets: Array<UnloadedDescriptor>,
},
pass: Array<Plugin>,
envName: string,
) {
const plugins = config.plugins.map(descriptor =>
loadPluginDescriptor(descriptor, envName),
);
const presets = config.presets.map(descriptor => {
return {
preset: loadPresetDescriptor(descriptor, envName),
pass: descriptor.ownPass ? [] : pass,
};
});
// resolve presets
if (presets.length > 0) {
// The passes are created in the same order as the preset list, but are inserted before any
// existing additional passes.
passes.splice(
1,
0,
...presets.map(o => o.pass).filter(p => p !== pass),
);
for (const { preset, pass } of presets) {
recurseDescriptors(
{
plugins: preset.plugins,
presets: preset.presets,
},
pass,
envName,
);
preset.options.forEach(opts => {
merge(optionDefaults, opts);
});
}
}
// resolve plugins
if (plugins.length > 0) {
pass.unshift(...plugins);
}
})(
{
plugins: configChain.plugins,
presets: configChain.presets,
},
passes[0],
envName,
);
configChain.options.forEach(opts => {
merge(options, opts);
});
} catch (e) {
// There are a few case where thrown errors will try to annotate themselves multiple times, so
// to keep things simple we just bail out if re-wrapping the message.
if (!/^\[BABEL\]/.test(e.message)) {
e.message = `[BABEL] ${args.filename || "unknown"}: ${e.message}`;
}
throw e;
}
const opts: Object = merge(optionDefaults, options);
// Tack the passes onto the object itself so that, if this object is passed back to Babel a second time,
// it will be in the right structure to not change behavior.
opts.babelrc = false;
opts.plugins = passes[0];
opts.presets = passes
.slice(1)
.filter(plugins => plugins.length > 0)
.map(plugins => ({ plugins }));
opts.passPerPreset = opts.presets.length > 0;
opts.envName = envName;
opts.cwd = absoluteCwd;
return {
options: opts,
passes: passes,
};
}
/**
* Load a generic plugin/preset from the given descriptor loaded from the config object.
*/
const loadDescriptor = makeWeakCache(
(
{ value, options, dirname, alias }: UnloadedDescriptor,
cache: CacheConfigurator<{ envName: string }>,
): LoadedDescriptor => {
// Disabled presets should already have been filtered out
if (options === false) throw new Error("Assertion failure");
options = options || {};
let item = value;
if (typeof value === "function") {
const api = Object.assign(Object.create(context), {
cache: cache.simple(),
env: () => cache.using(data => data.envName),
async: () => false,
});
try {
item = value(api, options, dirname);
} catch (e) {
if (alias) {
e.message += ` (While processing: ${JSON.stringify(alias)})`;
}
throw e;
}
}
if (!item || typeof item !== "object") {
throw new Error("Plugin/Preset did not return an object.");
}
if (typeof item.then === "function") {
throw new Error(
`You appear to be using an async plugin, ` +
`which your current version of Babel does not support.` +
`If you're using a published plugin, ` +
`you may need to upgrade your @babel/core version.`,
);
}
return { value: item, options, dirname, alias };
},
);
/**
* Instantiate a plugin for the given descriptor, returning the plugin/options pair.
*/
function loadPluginDescriptor(
descriptor: UnloadedDescriptor,
envName: string,
): Plugin {
if (descriptor.value instanceof Plugin) {
if (descriptor.options) {
throw new Error(
"Passed options to an existing Plugin instance will not work.",
);
}
return descriptor.value;
}
return instantiatePlugin(loadDescriptor(descriptor, { envName }), {
envName,
});
}
const instantiatePlugin = makeWeakCache(
(
{ value, options, dirname, alias }: LoadedDescriptor,
cache: CacheConfigurator<{ envName: string }>,
): Plugin => {
const pluginObj = validatePluginObject(value);
const plugin = Object.assign({}, pluginObj);
if (plugin.visitor) {
plugin.visitor = traverse.explode(clone(plugin.visitor));
}
if (plugin.inherits) {
const inheritsDescriptor = {
name: undefined,
alias: `${alias}$inherits`,
value: plugin.inherits,
options,
dirname,
};
// If the inherited plugin changes, reinstantiate this plugin.
const inherits = cache.invalidate(data =>
loadPluginDescriptor(inheritsDescriptor, data.envName),
);
plugin.pre = chain(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post);
plugin.manipulateOptions = chain(
inherits.manipulateOptions,
plugin.manipulateOptions,
);
plugin.visitor = traverse.visitors.merge([
inherits.visitor || {},
plugin.visitor || {},
]);
}
return new Plugin(plugin, options, alias);
},
);
/**
* Generate a config object that will act as the root of a new nested config.
*/
const loadPresetDescriptor = (
descriptor: UnloadedDescriptor,
envName: string,
): ConfigChain => {
return buildPresetChain(
instantiatePreset(loadDescriptor(descriptor, { envName })),
);
};
const instantiatePreset = makeWeakCache(
({ value, dirname, alias }: LoadedDescriptor): PresetInstance => {
return {
options: validate("preset", value),
alias,
dirname,
};
},
);
function chain(a, b) {
const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0];
return function(...args) {
for (const fn of fns) {
fn.apply(this, args);
}
};
}

View File

@@ -1,230 +0,0 @@
// @flow
import buildDebug from "debug";
import path from "path";
import fs from "fs";
import json5 from "json5";
import resolve from "resolve";
import { getEnv } from "../../helpers/environment";
import { makeStrongCache } from "../../caching";
const debug = buildDebug("babel:config:loading:files:configuration");
export type ConfigFile = {
filepath: string,
dirname: string,
options: {},
};
const BABELRC_FILENAME = ".babelrc";
const BABELRC_JS_FILENAME = ".babelrc.js";
const PACKAGE_FILENAME = "package.json";
const BABELIGNORE_FILENAME = ".babelignore";
export function findConfigs(dirname: string): Array<ConfigFile> {
let foundConfig = false;
let foundIgnore = false;
const confs = [];
let loc = dirname;
while (true) {
if (!foundIgnore) {
const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
const ignore = readIgnoreConfig(ignoreLoc);
if (ignore) {
debug("Found ignore %o from %o.", ignore.filepath, dirname);
confs.push(ignore);
foundIgnore = true;
}
}
if (!foundConfig) {
const conf = [
BABELRC_FILENAME,
BABELRC_JS_FILENAME,
PACKAGE_FILENAME,
].reduce((previousConfig: ConfigFile | null, name) => {
const filepath = path.join(loc, name);
const config = readConfig(filepath);
if (config && previousConfig) {
throw new Error(
`Multiple configuration files found. Please remove one:\n- ${path.basename(
previousConfig.filepath,
)}\n- ${name}\nfrom ${loc}`,
);
}
return config || previousConfig;
}, null);
if (conf) {
debug("Found configuration %o from %o.", conf.filepath, dirname);
confs.push(conf);
foundConfig = true;
}
}
if (foundIgnore && foundConfig) break;
if (loc === path.dirname(loc)) break;
loc = path.dirname(loc);
}
return confs;
}
export function loadConfig(name: string, dirname: string): ConfigFile {
const filepath = resolve.sync(name, { basedir: dirname });
const conf = readConfig(filepath);
if (!conf) {
throw new Error(`Config file ${filepath} contains no configuration data`);
}
debug("Loaded config %o from $o.", name, dirname);
return conf;
}
/**
* 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) {
return path.extname(filepath) === ".js"
? readConfigJS(filepath)
: readConfigFile(filepath);
}
const LOADING_CONFIGS = new Set();
const readConfigJS = makeStrongCache((filepath, cache) => {
if (!fs.existsSync(filepath)) {
cache.forever();
return null;
}
// The `require()` call below can make this code reentrant if a require hook like @babel/register has been
// loaded into the system. That would cause Babel to attempt to compile the `.babelrc.js` file as it loads
// below. To cover this case, we auto-ignore re-entrant config processing.
if (LOADING_CONFIGS.has(filepath)) {
cache.never();
debug("Auto-ignoring usage of config %o.", filepath);
return {
filepath,
dirname: path.dirname(filepath),
options: {},
};
}
let options;
try {
LOADING_CONFIGS.add(filepath);
// $FlowIssue
const configModule = (require(filepath): mixed);
options =
configModule && configModule.__esModule
? configModule.default || undefined
: configModule;
} catch (err) {
err.message = `${filepath}: Error while loading config - ${err.message}`;
throw err;
} finally {
LOADING_CONFIGS.delete(filepath);
}
if (typeof options === "function") {
options = options({
cache,
// Expose ".env()" so people can easily get the same env that we expose using the "env" key.
env: () => cache.using(() => getEnv()),
});
} else {
cache.forever();
}
if (!options || typeof options !== "object" || Array.isArray(options)) {
throw new Error(
`${filepath}: Configuration should be an exported JavaScript object.`,
);
}
return {
filepath,
dirname: path.dirname(filepath),
options,
};
}, false /* autoPermacache */);
const readConfigFile = makeStaticFileCache((filepath, content) => {
let options;
if (path.basename(filepath) === PACKAGE_FILENAME) {
try {
options = JSON.parse(content).babel;
} catch (err) {
err.message = `${filepath}: Error while parsing JSON - ${err.message}`;
throw err;
}
if (!options) return null;
} else {
try {
options = json5.parse(content);
} catch (err) {
err.message = `${filepath}: Error while parsing config - ${err.message}`;
throw err;
}
if (!options) throw new Error(`${filepath}: No config detected`);
}
if (typeof options !== "object") {
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
}
if (Array.isArray(options)) {
throw new Error(`${filepath}: Expected config object but found array`);
}
return {
filepath,
dirname: path.dirname(filepath),
options,
};
});
const readIgnoreConfig = makeStaticFileCache((filepath, content) => {
const ignore = content
.split("\n")
.map(line => line.replace(/#(.*?)$/, "").trim())
.filter(line => !!line);
return {
filepath,
dirname: path.dirname(filepath),
options: { ignore },
};
});
function makeStaticFileCache<T>(fn: (string, string) => T): string => T | null {
return makeStrongCache((filepath, cache) => {
if (cache.invalidate(() => fileMtime(filepath)) === null) {
cache.forever();
return null;
}
return fn(filepath, fs.readFileSync(filepath, "utf8"));
});
}
function fileMtime(filepath: string): number | null {
try {
return +fs.statSync(filepath).mtime;
} catch (e) {
if (e.code !== "ENOENT") throw e;
}
return null;
}

View File

@@ -1,362 +0,0 @@
// @flow
import * as context from "../index";
import Plugin, { validatePluginObject } from "./plugin";
import merge from "lodash/merge";
import buildConfigChain, { type ConfigItem } from "./build-config-chain";
import traverse from "@babel/traverse";
import clone from "lodash/clone";
import { makeWeakCache } from "./caching";
import { getEnv } from "./helpers/environment";
import { validate, type ValidatedOptions, type PluginItem } from "./options";
import { loadPlugin, loadPreset } from "./loading/files";
type MergeOptions =
| ConfigItem
| {
type: "preset",
options: ValidatedOptions,
alias: string,
dirname: string,
};
export default function manageOptions(opts: {}): {
options: Object,
passes: Array<Array<Plugin>>,
} | null {
return new OptionManager().init(opts);
}
class OptionManager {
constructor() {
this.options = {};
this.passes = [[]];
}
options: ValidatedOptions;
passes: Array<Array<Plugin>>;
/**
* This is called when we want to merge the input `opts` into the
* base options.
*
* - `alias` is used to output pretty traces back to the original source.
* - `loc` is used to point to the original config.
* - `dirname` is used to resolve plugins relative to it.
*/
mergeOptions(config: MergeOptions, pass?: Array<Plugin>) {
const result = loadConfig(config);
const plugins = result.plugins.map(descriptor =>
loadPluginDescriptor(descriptor),
);
const presets = result.presets.map(descriptor =>
loadPresetDescriptor(descriptor),
);
const passPerPreset = config.options.passPerPreset;
pass = pass || this.passes[0];
// resolve presets
if (presets.length > 0) {
let presetPasses = null;
if (passPerPreset) {
presetPasses = presets.map(() => []);
// The passes are created in the same order as the preset list, but are inserted before any
// existing additional passes.
this.passes.splice(1, 0, ...presetPasses);
}
presets.forEach((presetConfig, i) => {
this.mergeOptions(presetConfig, presetPasses ? presetPasses[i] : pass);
});
}
// resolve plugins
if (plugins.length > 0) {
pass.unshift(...plugins);
}
const options = Object.assign({}, result.options);
delete options.extends;
delete options.env;
delete options.plugins;
delete options.presets;
delete options.passPerPreset;
// "sourceMap" is just aliased to sourceMap, so copy it over as
// we merge the options together.
if (options.sourceMap) {
options.sourceMaps = options.sourceMap;
delete options.sourceMap;
}
merge(this.options, options);
}
init(inputOpts: {}) {
const args = validate("arguments", inputOpts);
const configChain = buildConfigChain(args);
if (!configChain) return null;
try {
for (const config of configChain) {
this.mergeOptions(config);
}
} catch (e) {
// There are a few case where thrown errors will try to annotate themselves multiple times, so
// to keep things simple we just bail out if re-wrapping the message.
if (!/^\[BABEL\]/.test(e.message)) {
e.message = `[BABEL] ${args.filename || "unknown"}: ${e.message}`;
}
throw e;
}
const opts: Object = this.options;
// Tack the passes onto the object itself so that, if this object is passed back to Babel a second time,
// it will be in the right structure to not change behavior.
opts.babelrc = false;
opts.plugins = this.passes[0];
opts.presets = this.passes
.slice(1)
.filter(plugins => plugins.length > 0)
.map(plugins => ({ plugins }));
opts.passPerPreset = opts.presets.length > 0;
return {
options: opts,
passes: this.passes,
};
}
}
type BasicDescriptor = {
value: {} | Function,
options: {} | void,
dirname: string,
alias: string,
};
type LoadedDescriptor = {
value: {},
options: {},
dirname: string,
alias: string,
};
/**
* Load and validate the given config into a set of options, plugins, and presets.
*/
const loadConfig = makeWeakCache((config: MergeOptions): {
options: {},
plugins: Array<BasicDescriptor>,
presets: Array<BasicDescriptor>,
} => {
const options = config.options;
const plugins = (config.options.plugins || []).map((plugin, index) =>
createDescriptor(plugin, loadPlugin, config.dirname, {
index,
alias: config.alias,
}),
);
const presets = (config.options.presets || []).map((preset, index) =>
createDescriptor(preset, loadPreset, config.dirname, {
index,
alias: config.alias,
}),
);
return { options, plugins, presets };
});
/**
* Load a generic plugin/preset from the given descriptor loaded from the config object.
*/
const loadDescriptor = makeWeakCache(
(
{ value, options = {}, dirname, alias }: BasicDescriptor,
cache,
): LoadedDescriptor => {
let item = value;
if (typeof value === "function") {
const api = Object.assign(Object.create(context), {
cache,
env: () => cache.using(() => getEnv()),
});
try {
item = value(api, options, dirname);
} catch (e) {
if (alias) {
e.message += ` (While processing: ${JSON.stringify(alias)})`;
}
throw e;
}
}
if (!item || typeof item !== "object") {
throw new Error("Plugin/Preset did not return an object.");
}
return { value: item, options, dirname, alias };
},
);
/**
* Instantiate a plugin for the given descriptor, returning the plugin/options pair.
*/
function loadPluginDescriptor(descriptor: BasicDescriptor): Plugin {
if (descriptor.value instanceof Plugin) {
if (descriptor.options) {
throw new Error(
"Passed options to an existing Plugin instance will not work.",
);
}
return descriptor.value;
}
return instantiatePlugin(loadDescriptor(descriptor));
}
const instantiatePlugin = makeWeakCache(
({ value, options, dirname, alias }: LoadedDescriptor, cache): Plugin => {
const pluginObj = validatePluginObject(value);
const plugin = Object.assign({}, pluginObj);
if (plugin.visitor) {
plugin.visitor = traverse.explode(clone(plugin.visitor));
}
if (plugin.inherits) {
const inheritsDescriptor = {
alias: `${alias}$inherits`,
value: plugin.inherits,
options,
dirname,
};
// If the inherited plugin changes, reinstantiate this plugin.
const inherits = cache.invalidate(() =>
loadPluginDescriptor(inheritsDescriptor),
);
plugin.pre = chain(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post);
plugin.manipulateOptions = chain(
inherits.manipulateOptions,
plugin.manipulateOptions,
);
plugin.visitor = traverse.visitors.merge([
inherits.visitor || {},
plugin.visitor || {},
]);
}
return new Plugin(plugin, options, alias);
},
);
/**
* Generate a config object that will act as the root of a new nested config.
*/
const loadPresetDescriptor = (descriptor: BasicDescriptor): MergeOptions => {
return instantiatePreset(loadDescriptor(descriptor));
};
const instantiatePreset = makeWeakCache(
({ value, dirname, alias }: LoadedDescriptor): MergeOptions => {
return {
type: "preset",
options: validate("preset", value),
alias,
dirname,
};
},
);
/**
* Given a plugin/preset item, resolve it into a standard format.
*/
function createDescriptor(
pair: PluginItem,
resolver,
dirname,
{
index,
alias,
}: {
index: number,
alias: string,
},
): BasicDescriptor {
let options;
let value = pair;
if (Array.isArray(value)) {
[value, options] = value;
}
let filepath = null;
if (typeof value === "string") {
({ filepath, value } = resolver(value, dirname));
}
if (!value) {
throw new Error(`Unexpected falsy value: ${String(value)}`);
}
if (typeof value === "object" && value.__esModule) {
if (value.default) {
value = value.default;
} else {
throw new Error("Must export a default export when using ES6 modules.");
}
}
if (typeof value !== "object" && typeof value !== "function") {
throw new Error(
`Unsupported format: ${typeof value}. Expected an object or a function.`,
);
}
if (filepath !== null && typeof value === "object" && value) {
// We allow object values for plugins/presets nested directly within a
// config object, because it can be useful to define them in nested
// configuration contexts.
throw new Error(
"Plugin/Preset files are not allowed to export objects, only functions.",
);
}
if (options != null && typeof options !== "object") {
throw new Error(
"Plugin/Preset options must be an object, null, or undefined",
);
}
options = options || undefined;
return {
alias: filepath || `${alias}$${index}`,
value,
options,
dirname,
};
}
function chain(a, b) {
const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0];
return function(...args) {
for (const fn of fns) {
fn.apply(this, args);
}
};
}

View File

@@ -1,100 +1,6 @@
// @flow
import {
assertString,
assertFunction,
assertObject,
type ValidatorSet,
type Validator,
} from "./option-assertions";
// Note: The casts here are just meant to be static assertions to make sure
// that the assertion functions actually assert that the value's type matches
// the declared types.
const VALIDATORS: ValidatorSet = {
name: (assertString: Validator<$PropertyType<PluginObject, "name">>),
manipulateOptions: (assertFunction: Validator<
$PropertyType<PluginObject, "manipulateOptions">,
>),
pre: (assertFunction: Validator<$PropertyType<PluginObject, "pre">>),
post: (assertFunction: Validator<$PropertyType<PluginObject, "post">>),
inherits: (assertFunction: Validator<
$PropertyType<PluginObject, "inherits">,
>),
visitor: (assertVisitorMap: Validator<
$PropertyType<PluginObject, "visitor">,
>),
parserOverride: (assertFunction: Validator<
$PropertyType<PluginObject, "parserOverride">,
>),
generatorOverride: (assertFunction: Validator<
$PropertyType<PluginObject, "generatorOverride">,
>),
};
function assertVisitorMap(key: string, value: mixed): VisitorMap {
const obj = assertObject(key, value);
if (obj) {
Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop]));
if (obj.enter || obj.exit) {
throw new Error(
`.${key} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`,
);
}
}
return (obj: any);
}
function assertVisitorHandler(
key: string,
value: mixed,
): VisitorHandler | void {
if (value && typeof value === "object") {
Object.keys(value).forEach(handler => {
if (handler !== "enter" && handler !== "exit") {
throw new Error(
`.visitor["${key}"] may only have .enter and/or .exit handlers.`,
);
}
});
} else if (typeof value !== "function") {
throw new Error(`.visitor["${key}"] must be a function`);
}
return (value: any);
}
type VisitorHandler = Function | { enter?: Function, exit?: Function };
export type VisitorMap = {
[string]: VisitorHandler,
};
export type PluginObject = {
name?: string,
manipulateOptions?: Function,
pre?: Function,
post?: Function,
inherits?: Function,
visitor?: VisitorMap,
parserOverride?: Function,
generatorOverride?: Function,
};
export function validatePluginObject(obj: {}): PluginObject {
Object.keys(obj).forEach(key => {
const validator = VALIDATORS[key];
if (validator) validator(key, obj[key]);
else throw new Error(`.${key} is not a valid Plugin property`);
});
return (obj: any);
}
import type { PluginObject } from "./validation/plugins";
export default class Plugin {
key: ?string;

View File

@@ -146,16 +146,31 @@ function assertPluginItem(
if (value.length === 0) {
throw new Error(`.${key}[${index}] must include an object`);
}
if (value.length > 2) {
throw new Error(`.${key}[${index}] may only be a two-tuple`);
if (value.length > 3) {
throw new Error(
`.${key}[${index}] may only be a two-tuple or three-tuple`,
);
}
assertPluginTarget(key, index, true, value[0]);
if (value.length === 2) {
if (value.length > 1) {
const opts = value[1];
if (opts != null && (typeof opts !== "object" || Array.isArray(opts))) {
throw new Error(`.${key}[${index}][1] must be an object, or undefined`);
if (
opts !== undefined &&
opts !== false &&
(typeof opts !== "object" || Array.isArray(opts))
) {
throw new Error(
`.${key}[${index}][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`);
}
}
} else {
@@ -176,9 +191,9 @@ function assertPluginTarget(
typeof value !== "function"
) {
throw new Error(
`.${key}[${index}]${inArray
? `[0]`
: ""} must be a string, object, function`,
`.${key}[${index}]${
inArray ? `[0]` : ""
} must be a string, object, function`,
);
}
return value;

View File

@@ -17,6 +17,7 @@ import {
} from "./option-assertions";
const ROOT_VALIDATORS: ValidatorSet = {
cwd: (assertString: Validator<$PropertyType<ValidatedOptions, "cwd">>),
filename: (assertString: Validator<
$PropertyType<ValidatedOptions, "filename">,
>),
@@ -28,6 +29,10 @@ const ROOT_VALIDATORS: ValidatorSet = {
>),
code: (assertBoolean: Validator<$PropertyType<ValidatedOptions, "code">>),
ast: (assertBoolean: Validator<$PropertyType<ValidatedOptions, "ast">>),
envName: (assertString: Validator<
$PropertyType<ValidatedOptions, "envName">,
>),
};
const NONPRESET_VALIDATORS: ValidatorSet = {
@@ -124,12 +129,14 @@ const COMMON_VALIDATORS: ValidatorSet = {
export type InputOptions = ValidatedOptions;
export type ValidatedOptions = {
cwd?: string,
filename?: string,
filenameRelative?: string,
babelrc?: boolean,
code?: boolean,
ast?: boolean,
inputSourceMap?: RootInputSourceMapOption,
envName?: string,
extends?: string,
env?: EnvSet<ValidatedOptions>,
@@ -180,8 +187,13 @@ export type EnvSet<T> = {
export type IgnoreItem = string | Function | RegExp;
export type IgnoreList = $ReadOnlyArray<IgnoreItem>;
export type PluginOptions = {} | void | false;
export type PluginTarget = string | {} | Function;
export type PluginItem = PluginTarget | [PluginTarget, {} | void];
export type PluginItem =
| Plugin
| PluginTarget
| [PluginTarget, PluginOptions]
| [PluginTarget, PluginOptions, string];
export type PluginList = $ReadOnlyArray<PluginItem>;
export type SourceMapsOption = boolean | "inline" | "both";
@@ -201,6 +213,9 @@ export function validate(type: OptionsType, opts: {}): ValidatedOptions {
if (type !== "arguments" && ROOT_VALIDATORS[key]) {
throw new Error(`.${key} is only allowed in root programmatic options`);
}
if (type === "env" && key === "env") {
throw new Error(`.${key} is not allowed inside another env block`);
}
const validator =
COMMON_VALIDATORS[key] ||

View File

@@ -0,0 +1,95 @@
import {
assertString,
assertFunction,
assertObject,
type ValidatorSet,
type Validator,
} from "./option-assertions";
// Note: The casts here are just meant to be static assertions to make sure
// that the assertion functions actually assert that the value's type matches
// the declared types.
const VALIDATORS: ValidatorSet = {
name: (assertString: Validator<$PropertyType<PluginObject, "name">>),
manipulateOptions: (assertFunction: Validator<
$PropertyType<PluginObject, "manipulateOptions">,
>),
pre: (assertFunction: Validator<$PropertyType<PluginObject, "pre">>),
post: (assertFunction: Validator<$PropertyType<PluginObject, "post">>),
inherits: (assertFunction: Validator<
$PropertyType<PluginObject, "inherits">,
>),
visitor: (assertVisitorMap: Validator<
$PropertyType<PluginObject, "visitor">,
>),
parserOverride: (assertFunction: Validator<
$PropertyType<PluginObject, "parserOverride">,
>),
generatorOverride: (assertFunction: Validator<
$PropertyType<PluginObject, "generatorOverride">,
>),
};
function assertVisitorMap(key: string, value: mixed): VisitorMap {
const obj = assertObject(key, value);
if (obj) {
Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop]));
if (obj.enter || obj.exit) {
throw new Error(
`.${key} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`,
);
}
}
return (obj: any);
}
function assertVisitorHandler(
key: string,
value: mixed,
): VisitorHandler | void {
if (value && typeof value === "object") {
Object.keys(value).forEach(handler => {
if (handler !== "enter" && handler !== "exit") {
throw new Error(
`.visitor["${key}"] may only have .enter and/or .exit handlers.`,
);
}
});
} else if (typeof value !== "function") {
throw new Error(`.visitor["${key}"] must be a function`);
}
return (value: any);
}
type VisitorHandler = Function | { enter?: Function, exit?: Function };
export type VisitorMap = {
[string]: VisitorHandler,
};
export type PluginObject = {
name?: string,
manipulateOptions?: Function,
pre?: Function,
post?: Function,
inherits?: Function,
visitor?: VisitorMap,
parserOverride?: Function,
generatorOverride?: Function,
};
export function validatePluginObject(obj: {}): PluginObject {
Object.keys(obj).forEach(key => {
const validator = VALIDATORS[key];
if (validator) validator(key, obj[key]);
else throw new Error(`.${key} is not a valid Plugin property`);
});
return (obj: any);
}

View File

@@ -4,7 +4,7 @@ export { default as File } from "./transformation/file/file";
export {
default as buildExternalHelpers,
} from "./tools/build-external-helpers";
export { resolvePlugin, resolvePreset } from "./config/loading/files";
export { resolvePlugin, resolvePreset } from "./config/files";
export { version } from "../package.json";
export { getEnv } from "./config/helpers/environment";

View File

@@ -8,13 +8,14 @@ export default function transformFileSync(
filename: string,
opts: ?InputOptions,
): FileResult | null {
let options;
if (opts == null) {
opts = { filename };
options = { filename };
} else if (opts && typeof opts === "object") {
opts = Object.assign(opts, { filename });
options = Object.assign({}, opts, { filename });
}
const config = loadConfig(opts);
const config = loadConfig(options);
if (config === null) return null;
return runSync(config, fs.readFileSync(filename, "utf8"));

View File

@@ -10,21 +10,22 @@ type TransformFile = {
};
export default ((function transformFile(filename, opts, callback) {
let options;
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
if (opts == null) {
opts = { filename };
options = { filename };
} else if (opts && typeof opts === "object") {
opts = Object.assign(opts, { filename });
options = Object.assign({}, opts, { filename });
}
process.nextTick(() => {
let cfg;
try {
cfg = loadConfig(opts);
cfg = loadConfig(options);
if (cfg === null) return callback(null, null);
} catch (err) {
return callback(err);

View File

@@ -38,6 +38,15 @@ export default function generateCode(
result = generate(ast, opts.generatorOpts, code);
} else if (results.length === 1) {
result = results[0];
if (typeof result.then === "function") {
throw new Error(
`You appear to be using an async parser plugin, ` +
`which your current version of Babel does not support. ` +
`If you're using a published plugin, ` +
`you may need to upgrade your @babel/core version.`,
);
}
} else {
throw new Error("More than one plugin attempted to override codegen.");
}

View File

@@ -86,7 +86,18 @@ function transformFile(file: File, pluginPasses: PluginPasses): void {
for (const [plugin, pass] of passPairs) {
const fn = plugin.pre;
if (fn) fn.call(pass, file);
if (fn) {
const result = fn.call(pass, file);
if (isThenable(result)) {
throw new Error(
`You appear to be using an plugin with an async .pre, ` +
`which your current version of Babel does not support.` +
`If you're using a published plugin, you may need to upgrade ` +
`your @babel/core version.`,
);
}
}
}
// merge all plugin visitors into a single visitor
@@ -99,7 +110,26 @@ function transformFile(file: File, pluginPasses: PluginPasses): void {
for (const [plugin, pass] of passPairs) {
const fn = plugin.post;
if (fn) fn.call(pass, file);
if (fn) {
const result = fn.call(pass, file);
if (isThenable(result)) {
throw new Error(
`You appear to be using an plugin with an async .post, ` +
`which your current version of Babel does not support.` +
`If you're using a published plugin, you may need to upgrade ` +
`your @babel/core version.`,
);
}
}
}
}
}
function isThenable(val: mixed): boolean {
return (
!!val &&
(typeof val === "object" || typeof val === "function") &&
typeof val.then === "function"
);
}

View File

@@ -6,6 +6,7 @@ import convertSourceMap, { typeof Converter } from "convert-source-map";
import { parse } from "babylon";
import { codeFrameColumns } from "@babel/code-frame";
import File from "./file/file";
import generateMissingPluginMessage from "./util/missing-plugin-helper";
const shebangRegex = /^#!.*/;
@@ -76,25 +77,39 @@ function parser(pluginPasses, options, code) {
if (results.length === 0) {
return parse(code, options.parserOpts);
} else if (results.length === 1) {
if (typeof results[0].then === "function") {
throw new Error(
`You appear to be using an async codegen plugin, ` +
`which your current version of Babel does not support. ` +
`If you're using a published plugin, you may need to upgrade ` +
`your @babel/core version.`,
);
}
return results[0];
}
throw new Error("More than one plugin attempted to override parsing.");
} catch (err) {
const loc = err.loc;
const { loc, missingPlugin } = err;
if (loc) {
err.loc = null;
err.message =
`${options.filename || "unknown"}: ${err.message}\n` +
codeFrameColumns(
code,
{
start: {
line: loc.line,
column: loc.column + 1,
},
const codeFrame = codeFrameColumns(
code,
{
start: {
line: loc.line,
column: loc.column + 1,
},
options,
);
},
options,
);
if (missingPlugin) {
err.message =
`${options.filename || "unknown"}: ` +
generateMissingPluginMessage(missingPlugin[0], loc, codeFrame);
} else {
err.message =
`${options.filename || "unknown"}: ${err.message}\n\n` + codeFrame;
}
}
throw err;
}

View File

@@ -41,9 +41,9 @@ export default function normalizeOptions(config: ResolvedConfig): {} {
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
retainLines: opts.retainLines,
comments,
shouldPrintComment: opts.shouldPrintComment,
compact,
minified: opts.minified,
concise: opts.concise,
// Source-map generation flags.
sourceMaps,

View File

@@ -0,0 +1,236 @@
// @flow
const pluginNameMap = {
asyncGenerators: {
syntax: {
name: "@babel/plugin-syntax-async-generators",
url: "https://git.io/vb4SY",
},
transform: {
name: "@babel/plugin-proposal-async-generator-functions",
url: "https://git.io/vb4yp",
},
},
classProperties: {
syntax: {
name: "@babel/plugin-syntax-class-properties",
url: "https://git.io/vb4yQ",
},
transform: {
name: "@babel/plugin-proposal-class-properties",
url: "https://git.io/vb4SL",
},
},
decorators: {
syntax: {
name: "@babel/plugin-syntax-decorators",
url: "https://git.io/vb4y9",
},
transform: {
name: "@babel/plugin-proposal-decorators",
url: "https://git.io/vb4ST",
},
},
doExpressions: {
syntax: {
name: "@babel/plugin-syntax-do-expressions",
url: "https://git.io/vb4yh",
},
transform: {
name: "@babel/plugin-proposal-do-expressions",
url: "https://git.io/vb4S3",
},
},
dynamicImport: {
syntax: {
name: "@babel/plugin-syntax-dynamic-import",
url: "https://git.io/vb4Sv",
},
},
exportDefaultFrom: {
syntax: {
name: "@babel/plugin-syntax-export-default-from",
url: "https://git.io/vb4SO",
},
transform: {
name: "@babel/plugin-proposal-export-default-from",
url: "https://git.io/vb4yH",
},
},
exportNamespaceFrom: {
syntax: {
name: "@babel/plugin-syntax-export-namespace-from",
url: "https://git.io/vb4Sf",
},
transform: {
name: "@babel/plugin-proposal-export-namespace-from",
url: "https://git.io/vb4SG",
},
},
flow: {
syntax: {
name: "@babel/plugin-syntax-flow",
url: "https://git.io/vb4yb",
},
transform: {
name: "@babel/plugin-transform-flow-strip-types",
url: "https://git.io/vb49g",
},
},
functionBind: {
syntax: {
name: "@babel/plugin-syntax-function-bind",
url: "https://git.io/vb4y7",
},
transform: {
name: "@babel/plugin-proposal-function-bind",
url: "https://git.io/vb4St",
},
},
functionSent: {
syntax: {
name: "@babel/plugin-syntax-function-sent",
url: "https://git.io/vb4yN",
},
transform: {
name: "@babel/plugin-proposal-function-sent",
url: "https://git.io/vb4SZ",
},
},
importMeta: {
syntax: {
name: "@babel/plugin-syntax-import-meta",
url: "https://git.io/vbKK6",
},
},
jsx: {
syntax: {
name: "@babel/plugin-syntax-jsx",
url: "https://git.io/vb4yA",
},
transform: {
name: "@babel/plugin-transform-react-jsx",
url: "https://git.io/vb4yd",
},
},
nullishCoalescingOperator: {
syntax: {
name: "@babel/plugin-syntax-nullish-coalescing-operator",
url: "https://git.io/vb4yx",
},
transform: {
name: "@babel/plugin-proposal-nullish-coalescing-operator",
url: "https://git.io/vb4Se",
},
},
numericSeparator: {
syntax: {
name: "@babel/plugin-syntax-numeric-separator",
url: "https://git.io/vb4Sq",
},
transform: {
name: "@babel/plugin-proposal-numeric-separator",
url: "https://git.io/vb4yS",
},
},
objectRestSpread: {
syntax: {
name: "@babel/plugin-syntax-object-rest-spread",
url: "https://git.io/vb4y5",
},
transform: {
name: "@babel/plugin-proposal-object-rest-spread",
url: "https://git.io/vb4Ss",
},
},
optionalCatchBinding: {
syntax: {
name: "@babel/plugin-syntax-optional-catch-binding",
url: "https://git.io/vb4Sn",
},
transform: {
name: "@babel/plugin-proposal-optional-catch-binding",
url: "https://git.io/vb4SI",
},
},
optionalChaining: {
syntax: {
name: "@babel/plugin-syntax-optional-chaining",
url: "https://git.io/vb4Sc",
},
transform: {
name: "@babel/plugin-proposal-optional-chaining",
url: "https://git.io/vb4Sk",
},
},
pipelineOperator: {
syntax: {
name: "@babel/plugin-syntax-pipeline-operator",
url: "https://git.io/vb4yj",
},
transform: {
name: "@babel/plugin-proposal-pipeline-operator",
url: "https://git.io/vb4SU",
},
},
throwExpressions: {
syntax: {
name: "@babel/plugin-syntax-throw-expressions",
url: "https://git.io/vb4SJ",
},
transform: {
name: "@babel/plugin-proposal-throw-expressions",
url: "https://git.io/vb4yF",
},
},
typescript: {
syntax: {
name: "@babel/plugin-syntax-typescript",
url: "https://git.io/vb4SC",
},
transform: {
name: "@babel/plugin-transform-typescript",
url: "https://git.io/vb4Sm",
},
},
};
const getNameURLCombination = ({ name, url }) => `${name} (${url})`;
/*
Returns a string of the format:
Support for the experimental syntax [babylon plugin name] isn't currently enabled ([loc]):
[code frame]
Add [npm package name] ([url]) to the 'plugins' section of your Babel config
to enable [parsing|transformation].
*/
export default function generateMissingPluginMessage(
missingPluginName: string,
loc: { line: number, column: number },
codeFrame: string,
): string {
let helpMessage =
`Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` +
`(${loc.line}:${loc.column + 1}):\n\n` +
codeFrame;
const pluginInfo = pluginNameMap[missingPluginName];
if (pluginInfo) {
const { syntax: syntaxPlugin, transform: transformPlugin } = pluginInfo;
if (syntaxPlugin) {
if (transformPlugin) {
const transformPluginInfo = getNameURLCombination(transformPlugin);
helpMessage +=
`\n\nAdd ${transformPluginInfo} to the 'plugins' section of your Babel config ` +
`to enable transformation.`;
} else {
const syntaxPluginInfo = getNameURLCombination(syntaxPlugin);
helpMessage +=
`\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` +
`to enable parsing.`;
}
}
}
return helpMessage;
}

View File

@@ -118,26 +118,33 @@ describe("api", function() {
});
it("transformFile", function(done) {
babel.transformFile(
__dirname + "/fixtures/api/file.js",
{
babelrc: false,
},
function(err, res) {
if (err) return done(err);
assert.equal(res.code, "foo();");
done();
},
);
const options = {
babelrc: false,
};
Object.freeze(options);
babel.transformFile(__dirname + "/fixtures/api/file.js", options, function(
err,
res,
) {
if (err) return done(err);
assert.equal(res.code, "foo();");
// keep user options untouched
assert.deepEqual(options, { babelrc: false });
done();
});
});
it("transformFileSync", function() {
const options = {
babelrc: false,
};
Object.freeze(options);
assert.equal(
babel.transformFileSync(__dirname + "/fixtures/api/file.js", {
babelrc: false,
}).code,
babel.transformFileSync(__dirname + "/fixtures/api/file.js", options)
.code,
"foo();",
);
assert.deepEqual(options, { babelrc: false });
});
it("options throw on falsy true", function() {
@@ -296,12 +303,6 @@ describe("api", function() {
development: {
passPerPreset: true,
presets: [pushPreset("argthree"), pushPreset("argfour")],
env: {
development: {
passPerPreset: true,
presets: [pushPreset("argfive"), pushPreset("argsix")],
},
},
},
},
});
@@ -309,32 +310,30 @@ describe("api", function() {
assert.equal(
result.code,
[
"argtwo;",
"argone;",
"eleven;",
"twelve;",
"thirteen;",
"fourteen;",
"seventeen;",
"eighteen;",
"one;",
"two;",
"eleven;",
"twelve;",
"argtwo;",
"argone;",
"five;",
"six;",
"three;",
"four;",
"seventeen;",
"eighteen;",
"nineteen;",
"twenty;",
"thirteen;",
"fourteen;",
"fifteen;",
"sixteen;",
"argfive;",
"argsix;",
"argthree;",
"argfour;",
"seven;",
"eight;",
"nine;",
"ten;",
"argthree;",
"argfour;",
].join("\n"),
);
});
@@ -600,4 +599,52 @@ describe("api", function() {
assert.ok(script.indexOf("typeof") >= 0);
});
});
describe("handle parsing errors", function() {
const options = {
babelrc: false,
};
it("only syntax plugin available", function(done) {
babel.transformFile(
__dirname + "/fixtures/api/parsing-errors/only-syntax/file.js",
options,
function(err) {
assert.ok(
RegExp(
"Support for the experimental syntax 'dynamicImport' isn't currently enabled \\(1:9\\):",
).exec(err.message),
);
assert.ok(
RegExp(
"Add @babel/plugin-syntax-dynamic-import \\(https://git.io/vb4Sv\\) to the " +
"'plugins' section of your Babel config to enable parsing.",
).exec(err.message),
);
done();
},
);
});
it("both syntax and transform plugin available", function(done) {
babel.transformFile(
__dirname + "/fixtures/api/parsing-errors/syntax-and-transform/file.js",
options,
function(err) {
assert.ok(
RegExp(
"Support for the experimental syntax 'asyncGenerators' isn't currently enabled \\(1:15\\):",
).exec(err.message),
);
assert.ok(
RegExp(
"Add @babel/plugin-proposal-async-generator-functions \\(https://git.io/vb4yp\\) to the " +
"'plugins' section of your Babel config to enable transformation.",
).exec(err.message),
);
done();
},
);
});
});
});

View File

@@ -19,23 +19,6 @@ describe("caching API", () => {
assert.notEqual(fn("one"), fn("two"));
});
it("should allow permacaching with cache(true)", () => {
let count = 0;
const fn = makeStrongCache((arg, cache) => {
cache(true);
return { arg, count: count++ };
});
assert.deepEqual(fn("one"), { arg: "one", count: 0 });
assert.equal(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", count: 1 });
assert.equal(fn("two"), fn("two"));
assert.notEqual(fn("one"), fn("two"));
});
it("should allow disabling caching with .never()", () => {
let count = 0;
@@ -55,25 +38,6 @@ describe("caching API", () => {
assert.notEqual(fn("one"), fn("two"));
});
it("should allow disabling caching with cache(false)", () => {
let count = 0;
const fn = makeStrongCache((arg, cache) => {
cache(false);
return { arg, count: count++ };
});
assert.deepEqual(fn("one"), { arg: "one", count: 0 });
assert.deepEqual(fn("one"), { arg: "one", count: 1 });
assert.notEqual(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", count: 4 });
assert.deepEqual(fn("two"), { arg: "two", count: 5 });
assert.notEqual(fn("two"), fn("two"));
assert.notEqual(fn("one"), fn("two"));
});
it("should allow caching based on a value with .using(fn)", () => {
let count = 0;
let other = "default";
@@ -115,47 +79,6 @@ describe("caching API", () => {
assert.equal(fn("two"), fn("two"));
});
it("should allow caching based on a value with cache(fn)", () => {
let count = 0;
let other = "default";
const fn = makeStrongCache((arg, cache) => {
const val = cache(() => other);
return { arg, val, count: count++ };
});
assert.deepEqual(fn("one"), { arg: "one", val: "default", count: 0 });
assert.equal(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", val: "default", count: 1 });
assert.equal(fn("two"), fn("two"));
other = "new";
assert.deepEqual(fn("one"), { arg: "one", val: "new", count: 2 });
assert.equal(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", val: "new", count: 3 });
assert.equal(fn("two"), fn("two"));
other = "default";
assert.deepEqual(fn("one"), { arg: "one", val: "default", count: 0 });
assert.equal(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", val: "default", count: 1 });
assert.equal(fn("two"), fn("two"));
other = "new";
assert.deepEqual(fn("one"), { arg: "one", val: "new", count: 2 });
assert.equal(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", val: "new", count: 3 });
assert.equal(fn("two"), fn("two"));
});
it("should allow invalidation based on a value with .invalidate(fn)", () => {
let count = 0;
let other = "default";
@@ -298,12 +221,6 @@ describe("caching API", () => {
assert.equal(fn("two"), fn("two"));
});
it("should throw if caching is never configured and not defaulting", () => {
const fn = makeStrongCache(() => {}, false /* autoPermacache */);
assert.throws(() => fn(), /Error: Caching was left unconfigured./);
});
it("should auto-permacache by default", () => {
let count = 0;
@@ -410,4 +327,89 @@ describe("caching API", () => {
/Cannot change caching after evaluation/,
);
});
describe("simple", () => {
it("should allow permacaching with cache(true)", () => {
let count = 0;
const fn = makeStrongCache((arg, cache) => {
cache = cache.simple();
cache(true);
return { arg, count: count++ };
});
assert.deepEqual(fn("one"), { arg: "one", count: 0 });
assert.equal(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", count: 1 });
assert.equal(fn("two"), fn("two"));
assert.notEqual(fn("one"), fn("two"));
});
it("should allow disabling caching with cache(false)", () => {
let count = 0;
const fn = makeStrongCache((arg, cache) => {
cache = cache.simple();
cache(false);
return { arg, count: count++ };
});
assert.deepEqual(fn("one"), { arg: "one", count: 0 });
assert.deepEqual(fn("one"), { arg: "one", count: 1 });
assert.notEqual(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", count: 4 });
assert.deepEqual(fn("two"), { arg: "two", count: 5 });
assert.notEqual(fn("two"), fn("two"));
assert.notEqual(fn("one"), fn("two"));
});
it("should allow caching based on a value with cache(fn)", () => {
let count = 0;
let other = "default";
const fn = makeStrongCache((arg, cache) => {
cache = cache.simple();
const val = cache(() => other);
return { arg, val, count: count++ };
});
assert.deepEqual(fn("one"), { arg: "one", val: "default", count: 0 });
assert.equal(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", val: "default", count: 1 });
assert.equal(fn("two"), fn("two"));
other = "new";
assert.deepEqual(fn("one"), { arg: "one", val: "new", count: 2 });
assert.equal(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", val: "new", count: 3 });
assert.equal(fn("two"), fn("two"));
other = "default";
assert.deepEqual(fn("one"), { arg: "one", val: "default", count: 0 });
assert.equal(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", val: "default", count: 1 });
assert.equal(fn("two"), fn("two"));
other = "new";
assert.deepEqual(fn("one"), { arg: "one", val: "new", count: 2 });
assert.equal(fn("one"), fn("one"));
assert.deepEqual(fn("two"), { arg: "two", val: "new", count: 3 });
assert.equal(fn("two"), fn("two"));
});
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -42,10 +42,10 @@ describe("@babel/core config loading", () => {
const options1 = loadConfig(opts).options;
expect(options1.plugins.map(p => p.key)).to.eql([
"plugin6",
"plugin5",
"plugin1",
"plugin2",
"plugin6",
"plugin5",
"plugin4",
"plugin3",
]);
@@ -86,7 +86,7 @@ describe("@babel/core config loading", () => {
expect(options2.plugins.length).to.equal(options1.plugins.length);
for (let i = 0; i < options1.plugins.length; i++) {
if (i === 2) {
if (i === 0) {
expect(options2.plugins[i]).not.to.equal(options1.plugins[i]);
} else {
expect(options2.plugins[i]).to.equal(options1.plugins[i]);
@@ -99,7 +99,7 @@ describe("@babel/core config loading", () => {
expect(options3.plugins.length).to.equal(options1.plugins.length);
for (let i = 0; i < options1.plugins.length; i++) {
if (i === 2 || i === 5) {
if (i === 0 || i === 5) {
expect(options3.plugins[i]).not.to.equal(options1.plugins[i]);
} else {
expect(options3.plugins[i]).to.equal(options1.plugins[i]);
@@ -150,7 +150,7 @@ describe("@babel/core config loading", () => {
expect(options2.plugins.length).to.equal(options1.plugins.length);
for (let i = 0; i < options1.plugins.length; i++) {
if (i === 2 || i === 3 || i === 4 || i === 5 || i === 6) {
if (i === 0 || i === 1 || i === 4 || i === 5 || i === 6) {
expect(options2.plugins[i]).not.to.equal(options1.plugins[i]);
} else {
expect(options2.plugins[i]).to.equal(options1.plugins[i]);
@@ -185,7 +185,7 @@ describe("@babel/core config loading", () => {
expect(options2.plugins.length).to.equal(options1.plugins.length);
for (let i = 0; i < options2.plugins.length; i++) {
if (i === 0) {
if (i === 2) {
expect(options2.plugins[i]).not.to.equal(options1.plugins[i]);
} else {
expect(options2.plugins[i]).to.equal(options1.plugins[i]);
@@ -205,7 +205,7 @@ describe("@babel/core config loading", () => {
expect(options2.plugins.length).to.equal(options1.plugins.length);
for (let i = 0; i < options2.plugins.length; i++) {
if (i === 1) {
if (i === 3) {
expect(options2.plugins[i]).not.to.equal(options1.plugins[i]);
} else {
expect(options2.plugins[i]).to.equal(options1.plugins[i]);
@@ -224,7 +224,7 @@ describe("@babel/core config loading", () => {
expect(options2.plugins.length).to.equal(options1.plugins.length);
for (let i = 0; i < options1.plugins.length; i++) {
if (i === 0) {
if (i === 2) {
expect(options2.plugins[i]).not.to.equal(options1.plugins[i]);
} else {
expect(options2.plugins[i]).to.equal(options1.plugins[i]);
@@ -243,7 +243,7 @@ describe("@babel/core config loading", () => {
expect(options2.plugins.length).to.equal(options1.plugins.length);
for (let i = 0; i < options1.plugins.length; i++) {
if (i === 1) {
if (i === 3) {
expect(options2.plugins[i]).not.to.equal(options1.plugins[i]);
} else {
expect(options2.plugins[i]).to.equal(options1.plugins[i]);

View File

@@ -0,0 +1 @@
var $ = import("jquery");

View File

@@ -0,0 +1,4 @@
async function* agf() {
await 1;
yield 2;
}

View File

@@ -1 +0,0 @@
root-ignore

View File

@@ -1,4 +0,0 @@
{
"plugins": ["root"],
"extends": "./extended.babelrc.json"
}

View File

@@ -18,4 +18,5 @@ seventeen.js
eighteen.js
nineteen.js
twenty.js
plugin.js
**/plugin.js

View File

@@ -2,6 +2,8 @@ module.exports = function(api) {
api.env();
return {
comments: false,
plugins: [
require("./plugin"),
],
};
}

View File

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

View File

@@ -1,3 +1,3 @@
{
comments: false,
plugins: ["./plugin"],
}

View File

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

View File

@@ -1,5 +1,5 @@
{
"babel": {
"comments": false
"plugins": ["./plugin"]
}
}

View File

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

View File

@@ -0,0 +1 @@
# Placeholder so the monorepo ignore isn't accessed

View File

@@ -0,0 +1 @@
src.js

View File

@@ -0,0 +1 @@
{45

View File

@@ -0,0 +1,3 @@
module.exports = function() {
throw new Error("Babelrc threw an error");
};

View File

@@ -0,0 +1,3 @@
module.exports = {
comments: true,
};

View File

@@ -0,0 +1,3 @@
{
comments: true,
}

View File

@@ -0,0 +1 @@
module.exports = {};

View File

@@ -0,0 +1 @@
module.exports = {};

View File

@@ -0,0 +1 @@
{}

View File

@@ -0,0 +1,3 @@
{
"babel": {235
}

View File

@@ -0,0 +1,3 @@
{
comments: true,
}

View File

@@ -0,0 +1 @@
{}

View File

@@ -0,0 +1,5 @@
{
"babel": {
"comments": true
}
}

View File

@@ -1 +0,0 @@
// empty

View File

@@ -1,5 +0,0 @@
{
"plugins": [
"dir2"
]
}

View File

@@ -1 +0,0 @@
// empty

View File

@@ -1,5 +0,0 @@
{
"name": "application-name",
"version": "0.0.1"
}

View File

@@ -1 +0,0 @@
// empty

View File

@@ -1,11 +0,0 @@
{
"plugins": ["env-base"],
"env": {
"foo": {
"plugins": ["env-foo"]
},
"bar": {
"plugins": ["env-bar"]
}
}
}

View File

@@ -1 +0,0 @@
// empty

View File

@@ -1,5 +0,0 @@
{
"plugins": [
"extended"
]
}

View File

@@ -1,6 +0,0 @@
{
ignore: [
"*",
"!folder",
],
}

View File

@@ -1,2 +0,0 @@
# Blank .gitignore to ensure this directory exists.
!.gitignore

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