diff --git a/.eslintignore b/.eslintignore index e035a9263a01..1954cc29ef41 100644 --- a/.eslintignore +++ b/.eslintignore @@ -3,7 +3,6 @@ scripts lib packages/babel-runtime packages/*/node_modules -packages/*/test packages/*/dist vendor _babel.github.io diff --git a/.eslintrc b/.eslintrc index 0277c4647c2b..00dd6a98ade9 100644 --- a/.eslintrc +++ b/.eslintrc @@ -4,6 +4,7 @@ "max-len": 0 }, "env": { - "node": true + "node": true, + "mocha": true } } diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000000..fcadb2cf9791 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text eol=lf diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 56f4dc80da9a..3bdbe759bf7b 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -9,7 +9,7 @@ If you have a support request or question please submit them to one of this reso * Also have a look at the Readme for more information on how to get support: https://github.com/babel/babel/blob/master/README.md -Issues on github are only related to problems of babel itself and we cannot answer +Issues on GitHub are only related to problems of babel itself and we cannot answer support questions here. --> @@ -22,7 +22,7 @@ support questions here. var your => (code) => here; ``` -### Babel Configuration (.bablerc, package.json, cli command) +### Babel Configuration (.babelrc, package.json, cli command) ```js diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index e349b70bab58..4d7a1e8be339 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,5 +1,5 @@ diff --git a/.istanbul.yml b/.istanbul.yml index 5830ddb66284..6489c5aeff0e 100644 --- a/.istanbul.yml +++ b/.istanbul.yml @@ -1,3 +1,5 @@ instrumentation: root: . - excludes: "**/node_modules/**" + excludes: + - "**/node_modules/**" + - "scripts/*.js" diff --git a/.travis.yml b/.travis.yml index 103112668073..a9f26431342d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ git: - depth: 1 + depth: 10 sudo: false language: node_js cache: diff --git a/CHANGELOG.md b/CHANGELOG.md index bde91f17e215..3c4a8980f469 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,13 +1,13 @@ # Changelog > **Tags:** -> - :boom: [Breaking Change] -> - :eyeglasses:[Spec Compliancy] -> - :rocket: [New Feature] -> - :bug: [Bug Fix] -> - :memo: [Documentation] -> - :house: [Internal] -> - :nail_care: [Polish] +> - :boom: [Breaking Change] +> - :eyeglasses: [Spec Compliancy] +> - :rocket: [New Feature] +> - :bug: [Bug Fix] +> - :memo: [Documentation] +> - :house: [Internal] +> - :nail_care: [Polish] _Note: Gaps between patch versions are faulty, broken or test releases._ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 842a8d791f5e..725914914924 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,25 +14,33 @@ ---- + # Contributing -Contributions are always welcome, no matter how large or small. Before -contributing, please read our [code of conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md). +> Before contributing, please read our [code of conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md). + +Contributions are always welcome, no matter how large or small. ## 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): Our current [spec](https://github.com/babel/babel/tree/master/doc/ast) is a bit different from [ESTree](https://github.com/estree/estree). + - [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (Abstract Syntax Tree): The Babel AST [spec](https://github.com/babel/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/babylon#output). - This repository's [`/doc`](/doc) directory for notes on 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 -- When you feel ready to finally jump into the babel source code a good start is to look out for issues which are labeled with `help wanted` and/or `beginner-friendly`. +- When you feel ready to finally jump into the babel source code a good start is to look out for issues which are labeled with [help-wanted](https://github.com/babel/babel/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) and/or [beginner-friendly](https://github.com/babel/babel/issues?q=is%3Aissue+is%3Aopen+label%3A%22beginner-friendly%22). + +## Chat -> If you're stuck, feel free to check out the `#development` channel on our [slack](https://slack.babeljs.io). +Feel free to check out the `#discussion`/`#development` channels on our [slack](https://slack.babeljs.io). Some of us are always online to chat! ## Developing -**Note:** Versions `< 5.1.10` can't be built. Make sure you are on npm 3. +**Note:** Versions `< 5.1.10` can't be built. + +Babel is built for node 0.10 and up but we develop using node 6. Make sure you are on npm 3. + +You can check this with `node -v` and `npm -v`. #### Setup @@ -64,15 +72,38 @@ If you wish to build a copy of Babel for distribution, then run: $ make build-dist ``` -#### Running tests +#### Running linting/tests + +You can run lint via: + +```sh +# ~6 sec on a MacBook Pro (Mid 2015) +$ make lint +``` + +You can run eslint's autofix via: -You can run tests for all packages via: +```sh +$ make fix +``` + +You can run tests + lint for all packages (slow) via: ```sh +# ~46 sec on a MacBook Pro (Mid 2015) $ make test ``` -To run tests for a specific package, you can use the `TEST_ONLY` environment variable: +If you just want to run all tests: + +```sh +# ~40 sec on a MacBook Pro (Mid 2015) +$ make test-only +``` + +Most likely you'll want to focus in on a specific issue. + +To run tests for a specific package in [packages](/packages), you can use the `TEST_ONLY` environment variable: ```sh $ TEST_ONLY=babel-cli make test @@ -143,9 +174,9 @@ If you need to check for an error that is thrown you can add to the `options.jso } ``` -##### `babylon` +##### Bootstrapping expected output -For `babylon` specifically, you can easily generate an `expected.json` automatically by just providing the `actual.js` and running `make test-only` 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 diff --git a/Makefile b/Makefile index e8aeb08b24e4..fac4ebbfffa2 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ MAKEFLAGS = -j1 export NODE_ENV = test -.PHONY: build build-dist watch lint clean test-clean test-only test test-cov test-ci publish bootstrap +.PHONY: build build-dist watch lint fix clean test-clean test-only test test-cov test-ci publish bootstrap build: clean ./node_modules/.bin/gulp build @@ -18,7 +18,10 @@ watch: clean ./node_modules/.bin/gulp watch lint: - ./node_modules/.bin/eslint packages/*/src + ./node_modules/.bin/eslint packages/*/{src,test}/*.js + +fix: + ./node_modules/.bin/eslint packages/*/{src,test}/*.js --fix clean: test-clean rm -rf packages/*/lib @@ -31,6 +34,11 @@ test-clean: rm -rf packages/*/test/tmp rm -rf packages/*/test-fixtures.json +clean-all: + rm -rf node_modules + rm -rf packages/*/node_modules + make clean + # without lint test-only: ./scripts/test.sh @@ -61,6 +69,7 @@ publish: #./scripts/build-website.sh bootstrap: + make clean-all npm install ./node_modules/.bin/lerna bootstrap make build diff --git a/README.md b/README.md index 6552fe30abb7..0461ebcf6695 100644 --- a/README.md +++ b/README.md @@ -29,13 +29,9 @@ Bugs and feature requests can be posted at https://github.com/babel/babel/issues > We've moved our issues from phabricator back to github issues! -> Former phabricator links are going to redirect to the corresponding Github issue, for example You can use http://phabricator.babeljs.io/T7567. +Former phabricator issue urls now automatically redirect to their corresponding Github issue: -``` -https://phabricator.babeljs.io/T2168 -mostly corresponds to -https://github.com/babel/babel/issues/2168 -``` +https://phabricator.babeljs.io/T2168 mostly corresponds to https://github.com/babel/babel/issues/2168. ## Want to report an issue with [babeljs.io](https://babeljs.io) (the website)? @@ -209,6 +205,7 @@ These just enable the transform plugins to be able to parse certain features (th | [`babel-plugin-syntax-flow`](/packages/babel-plugin-syntax-flow) | [![npm](https://img.shields.io/npm/v/babel-plugin-syntax-flow.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-plugin-syntax-flow) | | [`babel-plugin-syntax-function-bind`](/packages/babel-plugin-syntax-function-bind) | [![npm](https://img.shields.io/npm/v/babel-plugin-syntax-function-bind.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-plugin-syntax-function-bind) | | [`babel-plugin-syntax-function-sent`](/packages/babel-plugin-syntax-function-sent) | [![npm](https://img.shields.io/npm/v/babel-plugin-syntax-function-sent.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-plugin-syntax-function-sent) | +| [`babel-plugin-syntax-dynamic-import`](/packages/babel-plugin-syntax-dynamic-import) | [![npm](https://img.shields.io/npm/v/babel-plugin-syntax-dynamic-import.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-plugin-syntax-dynamic-import) | | [`babel-plugin-syntax-jsx`](/packages/babel-plugin-syntax-jsx) | [![npm](https://img.shields.io/npm/v/babel-plugin-syntax-jsx.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-plugin-syntax-jsx) | | [`babel-plugin-syntax-object-rest-spread`](/packages/babel-plugin-syntax-object-rest-spread) | [![npm](https://img.shields.io/npm/v/babel-plugin-syntax-object-rest-spread.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-plugin-syntax-object-rest-spread) | diff --git a/lib/parser.js b/lib/parser.js index a7fbb5318616..7c796731cea0 100644 --- a/lib/parser.js +++ b/lib/parser.js @@ -1,10 +1,5 @@ type BabelParserOptions = { - strictMode?: boolean; - looseModules?: boolean; - highlightCode?: boolean; - nonStandard?: boolean; + sourceFilename?: string; sourceType?: "module" | "script"; - filename?: string; - features?: Object; - plugins?: Object; + plugins?: Array; }; diff --git a/package.json b/package.json index da4f821f3051..21b4ed512990 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,9 @@ "license": "MIT", "scripts": { "test": "make test", - "build": "make build" + "build": "make build", + "lint": "make lint", + "fix": "make fix" }, "devDependencies": { "async": "^1.5.0", @@ -14,17 +16,18 @@ "babel-plugin-transform-runtime": "^6.3.13", "babel-preset-es2015": "^6.13.2", "babel-preset-stage-0": "^6.0.0", + "babel-register": "^6.14.0", "babel-runtime": "^6.0.0", - "browserify": "^11.2.0", + "browserify": "^13.1.1", "bundle-collapser": "^1.2.1", "chai": "^2.2.0", "chalk": "1.1.1", "codecov.io": "^0.1.6", "derequire": "^2.0.2", "eslint": "^3.7.1", - "eslint-config-babel": "^1.0.1", + "eslint-config-babel": "^2.0.1", "eslint-plugin-babel": "^3.3.0", - "eslint-plugin-flow-vars": "^0.5.0", + "eslint-plugin-flowtype": "^2.20.0", "flow-bin": "^0.33.0", "gulp": "^3.9.0", "gulp-babel": "^6.0.0", diff --git a/packages/babel-cli/bin/babel-doctor.js b/packages/babel-cli/bin/babel-doctor.js old mode 100755 new mode 100644 index e22664f438c3..d3d0a3ec9625 --- a/packages/babel-cli/bin/babel-doctor.js +++ b/packages/babel-cli/bin/babel-doctor.js @@ -1,3 +1,3 @@ #!/usr/bin/env node -require("../lib/babel-doctor"); +throw new Error("babel-doctor has been removed."); diff --git a/packages/babel-cli/package.json b/packages/babel-cli/package.json index 6001e4d67bc7..962668d1a050 100644 --- a/packages/babel-cli/package.json +++ b/packages/babel-cli/package.json @@ -11,18 +11,13 @@ "babel-register": "^6.16.0", "babel-polyfill": "^6.16.0", "babel-runtime": "^6.9.0", - "bin-version-check": "^2.1.0", - "chalk": "1.1.1", "commander": "^2.8.1", "convert-source-map": "^1.1.0", "fs-readdir-recursive": "^1.0.0", "glob": "^5.0.5", "lodash": "^4.2.0", - "log-symbols": "^1.0.2", "output-file-sync": "^1.1.0", - "path-exists": "^1.0.0", "path-is-absolute": "^1.0.0", - "request": "^2.65.0", "slash": "^1.0.0", "source-map": "^0.5.0", "v8flags": "^2.0.10" diff --git a/packages/babel-cli/src/babel-doctor/index.js b/packages/babel-cli/src/babel-doctor/index.js deleted file mode 100644 index 3bf118d2401d..000000000000 --- a/packages/babel-cli/src/babel-doctor/index.js +++ /dev/null @@ -1,96 +0,0 @@ -import chalk from "chalk"; -import path from "path"; -import fs from "fs"; -import * as rules from "./rules"; -import symbols from "log-symbols"; - -let didError = false; -let lastWasSep = false; - -function sep() { - if (lastWasSep) return; - lastWasSep = true; - - console.log(); -} - -function log(msg) { - lastWasSep = false; - console.log(msg); -} - -// - -log("\n" + chalk.underline.yellow("Babel Doctor")); -log("Running sanity checks on your system. This may take a few minutes...\n"); - -// - -let packages = []; - -let nodeModulesDirectories = [ - path.join(process.cwd(), "node_modules") -]; - -while (nodeModulesDirectories.length) { - let loc = nodeModulesDirectories.shift(); - if (!fs.existsSync(loc)) continue; - - let packagesNames: Array = fs.readdirSync(loc); - - for (let packageName of packagesNames) { - if (packageName[0] === ".") continue; - - let packageLoc = path.join(loc, packageName); - let packageJsonLoc = path.join(packageLoc, "package.json"); - if (!fs.existsSync(packageJsonLoc)) continue; - - packages.push({ - name: packageName, - loc: packageLoc, - version: require(packageJsonLoc).version - }); - - nodeModulesDirectories.push(path.join(packageLoc, "node_modules")); - } -} - -// - -async function run() { - let promises = []; - - for (let key in rules) { - if (key[0] === "_") continue; - - let fn = rules[key]; - promises.push(fn(packages)); - } - - let results = await Promise.all(promises); - - for (let [success, message] of results) { - if (!success) didError = true; - let multiline = message.indexOf("\n") >= 0; - if (multiline) sep(); - log(`${success ? symbols.success : symbols.error} ${message}`); - if (multiline) sep(); - } - - sep(); - - if (didError) { - log(chalk.red("Found potential issues on your machine :(")); - } else { - log(chalk.green("Everything looks all right!")); - } - - sep(); -} - -run().then(function () { - process.exit(0); -}, function (err) { - console.error(err.stack); - process.exit(1); -}); diff --git a/packages/babel-cli/src/babel-doctor/rules/deduped.js b/packages/babel-cli/src/babel-doctor/rules/deduped.js deleted file mode 100644 index 43e28b6d7f5d..000000000000 --- a/packages/babel-cli/src/babel-doctor/rules/deduped.js +++ /dev/null @@ -1,31 +0,0 @@ -export default async function (packages) { // eslint-disable-line require-yield - let foundDeps = {}; - let foundDuplicated = false; - let duplicatedPackages = {}; - - function checkDep(name) { - if (name.indexOf("babel-") === 0 && foundDeps[name]) { - foundDuplicated = true; - duplicatedPackages[name] = (duplicatedPackages[name] || 0) + 1; - } - - foundDeps[name] = true; - } - - for (let pkg of packages) { - checkDep(pkg.name); - } - - if (foundDuplicated) { - let msg = "Found these duplicate packages:\n\n"; - - for (let name in duplicatedPackages) { - msg += `- ${name} x ${duplicatedPackages[name]}\n`; - } - - msg += "\nRecommend running `npm dedupe`"; - return [false, msg]; - } else { - return [true, "No duplicate babel packages found"]; - } -} diff --git a/packages/babel-cli/src/babel-doctor/rules/has-config.js b/packages/babel-cli/src/babel-doctor/rules/has-config.js deleted file mode 100644 index 83ef13c1367f..000000000000 --- a/packages/babel-cli/src/babel-doctor/rules/has-config.js +++ /dev/null @@ -1,29 +0,0 @@ -import path from "path"; -import fs from "fs"; - -export default async function () { // eslint-disable-line require-yield - let cwd = process.cwd(); - let parts = cwd.split(path.sep); - - do { - let loc = parts.join(path.sep); - if (!loc) break; - - let babelrc = path.join(loc, ".babelrc"); - if (fs.existsSync(babelrc)) { - return [true, `Found config at ${babelrc}`]; - } - - let packagejson = path.join(loc, "package.json"); - if (fs.existsSync(packagejson)) { - let pkg = require(packagejson); - if (pkg.babel) { - return [true, `Found config at ${packagejson}`]; - } - } - - parts.pop(); - } while (parts.length); - - return [false, "Found no .babelrc config"]; -} diff --git a/packages/babel-cli/src/babel-doctor/rules/index.js b/packages/babel-cli/src/babel-doctor/rules/index.js deleted file mode 100644 index 48e3754718fc..000000000000 --- a/packages/babel-cli/src/babel-doctor/rules/index.js +++ /dev/null @@ -1,4 +0,0 @@ -export { default as hasConfig } from "./has-config"; -export { default as deduped } from "./deduped"; -export { default as latestPackages } from "./latest-packages"; -export { default as npm } from "./npm-3"; diff --git a/packages/babel-cli/src/babel-doctor/rules/latest-packages.js b/packages/babel-cli/src/babel-doctor/rules/latest-packages.js deleted file mode 100644 index ddea4a2efa1e..000000000000 --- a/packages/babel-cli/src/babel-doctor/rules/latest-packages.js +++ /dev/null @@ -1,55 +0,0 @@ -import request from "request"; - -let cache = {}; - -function getInfo(packageName) { - if (cache[packageName]) { - return cache[packageName]; - } else { - return cache[packageName] = new Promise(function (resolve, reject) { - request.get({ - url: `https://registry.npmjs.org/${packageName}/latest`, - json: true - }, function (err, res, body) { - if (err) { - reject(err); - } else { - resolve(cache[packageName] = body); - } - }); - }); - } -} - -export default async function (packages) { - let filteredPackages = []; - let promises = []; - - for (let pkg of packages) { - if (pkg.name.indexOf("babel-") !== 0) continue; - - promises.push(getInfo(pkg.name)); - filteredPackages.push(pkg); - } - - let infos = await Promise.all(promises); - let messages = []; - - for (let i = 0; i < infos.length; i++) { - let info = infos[i]; - let pkg = filteredPackages[i]; - - // https://github.com/babel/babel/issues/2915 - if (pkg.name === "babel-runtime") continue; - - if (info.version !== pkg.version) { - messages.push(`${pkg.name} - Latest is ${info.version}. Local version is ${pkg.version}`); - } - } - - if (messages.length) { - return [false, `We found some outdated packages:\n\n- ${messages.join("\n- ")}`]; - } else { - return [true, "All babel packages appear to be up to date"]; - } -} diff --git a/packages/babel-cli/src/babel-doctor/rules/npm-3.js b/packages/babel-cli/src/babel-doctor/rules/npm-3.js deleted file mode 100644 index d1be0b5b46c9..000000000000 --- a/packages/babel-cli/src/babel-doctor/rules/npm-3.js +++ /dev/null @@ -1,20 +0,0 @@ -/* eslint max-len: 0 */ - -import binVersionCheck from "bin-version-check"; -import chalk from "chalk"; - -export default function () { - return new Promise(function (resolve) { - binVersionCheck("npm", ">=3.3.0", function (err) { - if (err) { - let message = `Your npm version is outdated. Upgrade to the latest version by running:\n$ ${chalk.magenta("npm install -g npm")}.`; - if (process.platform === "win32") { - message += ` See this guide if you are having trouble upgrading: ${chalk.underline.blue("https://github.com/npm/npm/wiki/Troubleshooting#upgrading-on-windows")}`; - } - resolve([false, message]); - } else { - resolve([true, "You're on npm >=3.3.0"]); - } - }); - }); -} diff --git a/packages/babel-cli/src/babel/dir.js b/packages/babel-cli/src/babel/dir.js index 6bdb2fc19461..78be975c8885 100644 --- a/packages/babel-cli/src/babel/dir.js +++ b/packages/babel-cli/src/babel/dir.js @@ -1,5 +1,4 @@ let outputFileSync = require("output-file-sync"); -let pathExists = require("path-exists"); let slash = require("slash"); let path = require("path"); let util = require("./util"); @@ -45,7 +44,7 @@ module.exports = function (commander, filenames) { } function handle(filename) { - if (!pathExists.sync(filename)) return; + if (!fs.existsSync(filename)) return; let stat = fs.statSync(filename); diff --git a/packages/babel-cli/src/babel/file.js b/packages/babel-cli/src/babel/file.js index d2ab659ab84e..1feb8d2aadc3 100644 --- a/packages/babel-cli/src/babel/file.js +++ b/packages/babel-cli/src/babel/file.js @@ -1,5 +1,4 @@ let convertSourceMap = require("convert-source-map"); -let pathExists = require("path-exists"); let sourceMap = require("source-map"); let slash = require("slash"); let path = require("path"); @@ -109,7 +108,7 @@ module.exports = function (commander, filenames, opts) { results = []; _.each(filenames, function (filename) { - if (!pathExists.sync(filename)) return; + if (!fs.existsSync(filename)) return; let stat = fs.statSync(filename); if (stat.isDirectory()) { diff --git a/packages/babel-cli/src/babel/index.js b/packages/babel-cli/src/babel/index.js index 09ef16731e2d..236c2df72aae 100755 --- a/packages/babel-cli/src/babel/index.js +++ b/packages/babel-cli/src/babel/index.js @@ -3,7 +3,7 @@ require("babel-core"); -let pathExists = require("path-exists"); +let fs = require("fs"); let commander = require("commander"); let kebabCase = require("lodash/kebabCase"); let options = require("babel-core").options; @@ -70,7 +70,7 @@ let filenames = commander.args.reduce(function (globbed, input) { filenames = uniq(filenames); each(filenames, function (filename) { - if (!pathExists.sync(filename)) { + if (!fs.existsSync(filename)) { errors.push(filename + " doesn't exist"); } }); diff --git a/packages/babel-cli/test/fixtures/babel/stdin --filename/stderr.txt b/packages/babel-cli/test/fixtures/babel/stdin --filename/stderr.txt index 70be01b6f3d8..38b7bb91ce08 100644 --- a/packages/babel-cli/test/fixtures/babel/stdin --filename/stderr.txt +++ b/packages/babel-cli/test/fixtures/babel/stdin --filename/stderr.txt @@ -1 +1 @@ -SyntaxError: test.js: Unexpected token (2:10) +SyntaxError: test.js: Unexpected token, expected ; (2:10) diff --git a/packages/babel-cli/test/index.js b/packages/babel-cli/test/index.js index f5dbe30232cc..61cb19aed949 100644 --- a/packages/babel-cli/test/index.js +++ b/packages/babel-cli/test/index.js @@ -1,33 +1,30 @@ -if (process.env.running_under_istanbul) return; - -var readdir = require("fs-readdir-recursive"); -var helper = require("babel-helper-fixtures"); -var assert = require("assert"); -var rimraf = require("rimraf"); -var outputFileSync = require("output-file-sync"); -var child = require("child_process"); -var path = require("path"); -var chai = require("chai"); -var fs = require("fs"); -var pathExists = require("path-exists"); -var _ = require("lodash"); - -var fixtureLoc = path.join(__dirname, "fixtures"); -var tmpLoc = path.join(__dirname, "tmp"); - -var presetLocs = [ +let readdir = require("fs-readdir-recursive"); +let helper = require("babel-helper-fixtures"); +let assert = require("assert"); +let rimraf = require("rimraf"); +let outputFileSync = require("output-file-sync"); +let child = require("child_process"); +let path = require("path"); +let chai = require("chai"); +let fs = require("fs"); +let _ = require("lodash"); + +let fixtureLoc = path.join(__dirname, "fixtures"); +let tmpLoc = path.join(__dirname, "tmp"); + +let presetLocs = [ path.join(__dirname, "../../babel-preset-es2015"), path.join(__dirname, "../../babel-preset-react") ].join(","); -var pluginLocs = [ +let pluginLocs = [ path.join(__dirname, "/../../babel-plugin-transform-strict-mode"), path.join(__dirname, "/../../babel-plugin-transform-es2015-modules-commonjs"), ].join(","); -var readDir = function (loc) { - var files = {}; - if (pathExists.sync(loc)) { +let readDir = function (loc) { + let files = {}; + if (fs.existsSync(loc)) { _.each(readdir(loc), function (filename) { files[filename] = helper.readFile(path.join(loc, filename)); }); @@ -35,14 +32,14 @@ var readDir = function (loc) { return files; }; -var saveInFiles = function (files) { +let saveInFiles = function (files) { _.each(files, function (content, filename) { outputFileSync(filename, content); }); }; -var assertTest = function (stdout, stderr, opts) { - var expectStderr = opts.stderr.trim(); +let assertTest = function (stdout, stderr, opts) { + let expectStderr = opts.stderr.trim(); stderr = stderr.trim(); if (opts.stderr) { @@ -55,7 +52,7 @@ var assertTest = function (stdout, stderr, opts) { throw new Error("stderr:\n" + stderr); } - var expectStdout = opts.stdout.trim(); + let expectStdout = opts.stdout.trim(); stdout = stdout.trim(); stdout = stdout.replace(/\\/g, "/"); @@ -70,20 +67,19 @@ var assertTest = function (stdout, stderr, opts) { } _.each(opts.outFiles, function (expect, filename) { - var actual = helper.readFile(filename); + let actual = helper.readFile(filename); chai.expect(actual).to.equal(expect, "out-file " + filename); }); }; -var buildTest = function (binName, testName, opts) { - var binLoc = path.join(__dirname, "../lib", binName); +let buildTest = function (binName, testName, opts) { + let binLoc = path.join(__dirname, "../lib", binName); return function (callback) { - this.timeout(5000); clear(); saveInFiles(opts.inFiles); - var args = [binLoc]; + let args = [binLoc]; if (binName !== "babel-external-helpers") { args.push("--presets", presetLocs, "--plugins", pluginLocs); @@ -95,10 +91,10 @@ var buildTest = function (binName, testName, opts) { args = args.concat(opts.args); - var spawn = child.spawn(process.execPath, args); + let spawn = child.spawn(process.execPath, args); - var stderr = ""; - var stdout = ""; + let stderr = ""; + let stdout = ""; spawn.stderr.on("data", function (chunk) { stderr += chunk; @@ -109,7 +105,7 @@ var buildTest = function (binName, testName, opts) { }); spawn.on("close", function () { - var err; + let err; try { assertTest(stdout, stderr, opts); @@ -131,9 +127,9 @@ var buildTest = function (binName, testName, opts) { }; }; -var clear = function () { +let clear = function () { process.chdir(__dirname); - if (pathExists.sync(tmpLoc)) rimraf.sync(tmpLoc); + if (fs.existsSync(tmpLoc)) rimraf.sync(tmpLoc); fs.mkdirSync(tmpLoc); process.chdir(tmpLoc); }; @@ -141,23 +137,23 @@ var clear = function () { _.each(fs.readdirSync(fixtureLoc), function (binName) { if (binName[0] === ".") return; - var suiteLoc = path.join(fixtureLoc, binName); - suite("bin/" + binName, function () { + let suiteLoc = path.join(fixtureLoc, binName); + describe("bin/" + binName, function () { _.each(fs.readdirSync(suiteLoc), function (testName) { if (testName[0] === ".") return; - var testLoc = path.join(suiteLoc, testName); + let testLoc = path.join(suiteLoc, testName); - var opts = { + let opts = { args: [] }; - var optionsLoc = path.join(testLoc, "options.json"); - if (pathExists.sync(optionsLoc)) _.merge(opts, require(optionsLoc)); + let optionsLoc = path.join(testLoc, "options.json"); + if (fs.existsSync(optionsLoc)) _.merge(opts, require(optionsLoc)); _.each(["stdout", "stdin", "stderr"], function (key) { - var loc = path.join(testLoc, key + ".txt"); - if (pathExists.sync(loc)) { + let loc = path.join(testLoc, key + ".txt"); + if (fs.existsSync(loc)) { opts[key] = helper.readFile(loc); } else { opts[key] = opts[key] || ""; @@ -167,13 +163,13 @@ _.each(fs.readdirSync(fixtureLoc), function (binName) { opts.outFiles = readDir(path.join(testLoc, "out-files")); opts.inFiles = readDir(path.join(testLoc, "in-files")); - var babelrcLoc = path.join(testLoc, ".babelrc"); - if (pathExists.sync(babelrcLoc)) { + let babelrcLoc = path.join(testLoc, ".babelrc"); + if (fs.existsSync(babelrcLoc)) { // copy .babelrc file to tmp directory - opts.inFiles['.babelrc'] = helper.readFile(babelrcLoc); + opts.inFiles[".babelrc"] = helper.readFile(babelrcLoc); } - test(testName, buildTest(binName, testName, opts)); + it(testName, buildTest(binName, testName, opts)); }); }); }); diff --git a/packages/babel-code-frame/test/index.js b/packages/babel-code-frame/test/index.js index 59eef365e920..39813d7e1690 100644 --- a/packages/babel-code-frame/test/index.js +++ b/packages/babel-code-frame/test/index.js @@ -1,9 +1,9 @@ -var assert = require("assert"); -var chalk = require("chalk"); -var codeFrame = require(".."); +let assert = require("assert"); +let chalk = require("chalk"); +let codeFrame = require(".."); -suite("babel-code-frame", function () { - test("basic usage", function () { +describe("babel-code-frame", function () { + it("basic usage", function () { const rawLines = [ "class Foo {", " constructor()", @@ -17,7 +17,7 @@ suite("babel-code-frame", function () { ].join("\n")); }); - test("optional column number", function () { + it("optional column number", function () { const rawLines = [ "class Foo {", " constructor()", @@ -30,7 +30,7 @@ suite("babel-code-frame", function () { ].join("\n")); }); - test("optional column number", function () { + it("optional column number", function () { const rawLines = [ "class Foo {", " constructor()", @@ -43,7 +43,7 @@ suite("babel-code-frame", function () { ].join("\n")); }); - test("maximum context lines and padding", function () { + it("maximum context lines and padding", function () { const rawLines = [ "/**", " * Sums two numbers.", @@ -68,7 +68,7 @@ suite("babel-code-frame", function () { ].join("\n")); }); - test("no unnecessary padding due to one-off errors", function () { + it("no unnecessary padding due to one-off errors", function () { const rawLines = [ "/**", " * Sums two numbers.", @@ -93,12 +93,12 @@ suite("babel-code-frame", function () { ].join("\n")); }); - test("tabs", function () { + it("tabs", function () { const rawLines = [ "\tclass Foo {", "\t \t\t constructor\t(\t)", "\t};", - ].join('\n'); + ].join("\n"); assert.equal(codeFrame(rawLines, 2, 25), [ " 1 | \tclass Foo {", "> 2 | \t \t\t constructor\t(\t)", @@ -107,7 +107,7 @@ suite("babel-code-frame", function () { ].join("\n")); }); - test("opts.highlightCode", function () { + it("opts.highlightCode", function () { const rawLines = "console.log('babel')"; const result = codeFrame(rawLines, 1, 9, {highlightCode: true}); const stripped = chalk.stripColor(result); @@ -118,8 +118,8 @@ suite("babel-code-frame", function () { ].join("\n")); }); - test("opts.linesAbove", function () { - var rawLines = [ + it("opts.linesAbove", function () { + let rawLines = [ "/**", " * Sums two numbers.", " *", @@ -142,8 +142,8 @@ suite("babel-code-frame", function () { ].join("\n")); }); - test("opts.linesBelow", function () { - var rawLines = [ + it("opts.linesBelow", function () { + let rawLines = [ "/**", " * Sums two numbers.", " *", @@ -165,8 +165,8 @@ suite("babel-code-frame", function () { ].join("\n")); }); - test("opts.linesAbove and opts.linesBelow", function () { - var rawLines = [ + it("opts.linesAbove and opts.linesBelow", function () { + let rawLines = [ "/**", " * Sums two numbers.", " *", diff --git a/packages/babel-core/package.json b/packages/babel-core/package.json index 0e644c503c9a..ac433daae610 100644 --- a/packages/babel-core/package.json +++ b/packages/babel-core/package.json @@ -39,7 +39,6 @@ "json5": "^0.5.0", "lodash": "^4.2.0", "minimatch": "^3.0.2", - "path-exists": "^1.0.0", "path-is-absolute": "^1.0.0", "private": "^0.1.6", "slash": "^1.0.0", diff --git a/packages/babel-core/src/transformation/file/index.js b/packages/babel-core/src/transformation/file/index.js index 7a3bc883f74a..01d5b7efc9d3 100644 --- a/packages/babel-core/src/transformation/file/index.js +++ b/packages/babel-core/src/transformation/file/index.js @@ -52,12 +52,9 @@ export default class File extends Store { this.opts = this.initOptions(opts); this.parserOpts = { - highlightCode: this.opts.highlightCode, - nonStandard: this.opts.nonStandard, - sourceType: this.opts.sourceType, - filename: this.opts.filename, - sourceFileName:this.opts.filename, - plugins: [] + sourceType: this.opts.sourceType, + sourceFileName: this.opts.filename, + plugins: [] }; this.pluginVisitors = []; diff --git a/packages/babel-core/src/transformation/file/options/build-config-chain.js b/packages/babel-core/src/transformation/file/options/build-config-chain.js index f9b43e3a6bbc..02ce7376413a 100644 --- a/packages/babel-core/src/transformation/file/options/build-config-chain.js +++ b/packages/babel-core/src/transformation/file/options/build-config-chain.js @@ -3,7 +3,6 @@ import type Logger from "../logger"; import resolve from "../../../helpers/resolve"; import json5 from "json5"; import isAbsolute from "path-is-absolute"; -import pathExists from "path-exists"; import path from "path"; import fs from "fs"; @@ -17,7 +16,7 @@ const PACKAGE_FILENAME = "package.json"; function exists(filename) { let cached = existsCache[filename]; if (cached == null) { - return existsCache[filename] = pathExists.sync(filename); + return existsCache[filename] = fs.existsSync(filename); } else { return cached; } @@ -26,7 +25,7 @@ function exists(filename) { export default function buildConfigChain(opts: Object = {}, log?: Logger) { let filename = opts.filename; let builder = new ConfigChainBuilder(log); - + // resolve all .babelrc files if (opts.babelrc !== false) { builder.findConfigs(filename); @@ -37,7 +36,7 @@ export default function buildConfigChain(opts: Object = {}, log?: Logger) { alias: "base", dirname: filename && path.dirname(filename) }); - + return builder.configs; } diff --git a/packages/babel-core/src/transformation/file/options/option-manager.js b/packages/babel-core/src/transformation/file/options/option-manager.js index b14bdd1059ca..5af5f58fc96a 100644 --- a/packages/babel-core/src/transformation/file/options/option-manager.js +++ b/packages/babel-core/src/transformation/file/options/option-manager.js @@ -178,12 +178,13 @@ export default class OptionManager { // check for an unknown option if (!option && this.log) { - let pluginOptsInfo = "Check out http://babeljs.io/docs/usage/options/ for more info"; - if (removed[key]) { this.log.error(`Using removed Babel 5 option: ${alias}.${key} - ${removed[key].message}`, ReferenceError); } else { - this.log.error(`Unknown option: ${alias}.${key}. ${pluginOptsInfo}`, ReferenceError); + let unknownOptErr = `Unknown option: ${alias}.${key}. Check out http://babeljs.io/docs/usage/options/ for more information about options.`; + let presetConfigErr = `A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n \`{ presets: [{option: value}] }\`\nValid:\n \`{ presets: ['pluginName', {option: value}] }\`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options.`; + + this.log.error(`${unknownOptErr}\n\n${presetConfigErr}`, ReferenceError); } } } diff --git a/packages/babel-core/src/transformation/internal-plugins/shadow-functions.js b/packages/babel-core/src/transformation/internal-plugins/shadow-functions.js index 4eb08783f240..572b9bb37967 100644 --- a/packages/babel-core/src/transformation/internal-plugins/shadow-functions.js +++ b/packages/babel-core/src/transformation/internal-plugins/shadow-functions.js @@ -49,21 +49,25 @@ function remap(path, key) { let currentFunction; let passedShadowFunction = false; - let fnPath = path.findParent(function (path) { - if (path.isProgram() || path.isFunction()) { + let fnPath = path.find(function (innerPath) { + if (innerPath.parentPath && innerPath.parentPath.isClassProperty() && innerPath.key === "value") { + return true; + } + if (path === innerPath) return false; + if (innerPath.isProgram() || innerPath.isFunction()) { // catch current function in case this is the shadowed one and we can ignore it - currentFunction = currentFunction || path; + currentFunction = currentFunction || innerPath; } - if (path.isProgram()) { + if (innerPath.isProgram()) { passedShadowFunction = true; return true; - } else if (path.isFunction() && !path.isArrowFunctionExpression()) { + } else if (innerPath.isFunction() && !innerPath.isArrowFunctionExpression()) { if (shadowFunction) { - if (path === shadowFunction || path.node === shadowFunction.node) return true; + if (innerPath === shadowFunction || innerPath.node === shadowFunction.node) return true; } else { - if (!path.is("shadow")) return true; + if (!innerPath.is("shadow")) return true; } passedShadowFunction = true; diff --git a/packages/babel-core/src/util.js b/packages/babel-core/src/util.js index 0ee5e62a96bc..4da7503e8cbf 100644 --- a/packages/babel-core/src/util.js +++ b/packages/babel-core/src/util.js @@ -116,7 +116,7 @@ export function shouldIgnore( ignore: Array = [], only?: Array, ): boolean { - filename = slash(filename); + filename = filename.replace(/\\/g, "/"); if (only) { for (let pattern of only) { diff --git a/packages/babel-core/test/api.js b/packages/babel-core/test/api.js index ef72572511ff..1122e497e8bc 100644 --- a/packages/babel-core/test/api.js +++ b/packages/babel-core/test/api.js @@ -1,11 +1,9 @@ -var babel = require("../lib/api/node"); -var buildExternalHelpers = require("../lib/tools/build-external-helpers"); -var Pipeline = require("../lib/transformation/pipeline"); -var sourceMap = require("source-map"); -var assert = require("assert"); -var File = require("../lib/transformation/file").default; -var Plugin = require("../lib/transformation/plugin"); -var generator = require("babel-generator").default; +let babel = require("../lib/api/node"); +let buildExternalHelpers = require("../lib/tools/build-external-helpers"); +let sourceMap = require("source-map"); +let assert = require("assert"); +let Plugin = require("../lib/transformation/plugin"); +let generator = require("babel-generator").default; function assertIgnored(result) { assert.ok(result.ignored); @@ -24,8 +22,8 @@ function transformAsync(code, opts) { }; } -suite("parser and generator options", function() { - var recast = { +describe("parser and generator options", function() { + let recast = { parse: function(code, opts) { return opts.parser.parse(code); }, @@ -47,14 +45,14 @@ suite("parser and generator options", function() { }); } - test("options", function() { - var string = "original;"; + it("options", function() { + let string = "original;"; assert.deepEqual(newTransform(string).ast, babel.transform(string).ast); assert.equal(newTransform(string).code, string); }); - test("experimental syntax", function() { - var experimental = "var a: number = 1;"; + it("experimental syntax", function() { + let experimental = "var a: number = 1;"; assert.deepEqual(newTransform(experimental).ast, babel.transform(experimental, { parserOpts: { @@ -83,8 +81,8 @@ suite("parser and generator options", function() { assert.equal(newTransformWithPlugins(experimental).code, experimental); }); - test("other options", function() { - var experimental = "if (true) {\n import a from 'a';\n}"; + it("other options", function() { + let experimental = "if (true) {\n import a from 'a';\n}"; assert.notEqual(newTransform(experimental).ast, babel.transform(experimental, { parserOpts: { @@ -95,8 +93,8 @@ suite("parser and generator options", function() { }); }); -suite("api", function () { - test("analyze", function () { +describe("api", function () { + it("analyze", function () { assert.equal(babel.analyse("foobar;").marked.length, 0); assert.equal(babel.analyse("foobar;", { @@ -116,7 +114,7 @@ suite("api", function () { }).marked[0].message, "foobar"); }); - test("transformFile", function (done) { + it("transformFile", function (done) { babel.transformFile(__dirname + "/fixtures/api/file.js", {}, function (err, res) { if (err) return done(err); assert.equal(res.code, "foo();"); @@ -124,11 +122,11 @@ suite("api", function () { }); }); - test("transformFileSync", function () { + it("transformFileSync", function () { assert.equal(babel.transformFileSync(__dirname + "/fixtures/api/file.js", {}).code, "foo();"); }); - test("options throw on falsy true", function () { + it("options throw on falsy true", function () { return assert.throws( function () { babel.transform("", { @@ -139,7 +137,7 @@ suite("api", function () { ); }); - test("options merge backwards", function () { + it("options merge backwards", function () { return transformAsync("", { presets: [__dirname + "/../../babel-preset-es2015"], plugins: [__dirname + "/../../babel-plugin-syntax-jsx"] @@ -148,9 +146,9 @@ suite("api", function () { }); }); - test("option wrapPluginVisitorMethod", function () { - var calledRaw = 0; - var calledIntercept = 0; + it("option wrapPluginVisitorMethod", function () { + let calledRaw = 0; + let calledIntercept = 0; babel.transform("function foo() { bar(foobar); }", { wrapPluginVisitorMethod: function (pluginAlias, visitorType, callback) { @@ -180,11 +178,11 @@ suite("api", function () { assert.equal(calledIntercept, 4); }); - test("pass per preset", function () { - var aliasBaseType = null; + it("pass per preset", function () { + let aliasBaseType = null; function execTest(passPerPreset) { - return babel.transform('type Foo = number; let x = (y): Foo => y;', { + return babel.transform("type Foo = number; let x = (y): Foo => y;", { passPerPreset: passPerPreset, presets: [ // First preset with our plugin, "before" @@ -193,7 +191,7 @@ suite("api", function () { new Plugin({ visitor: { Function: function(path) { - var alias = path.scope.getProgramParent().path.get('body')[0].node; + let alias = path.scope.getProgramParent().path.get("body")[0].node; if (!babel.types.isTypeAlias(alias)) return; // In case of `passPerPreset` being `false`, the @@ -227,37 +225,37 @@ suite("api", function () { // 1. passPerPreset: true - var result = execTest(true); + let result = execTest(true); assert.equal(aliasBaseType, "NumberTypeAnnotation"); assert.deepEqual([ - '"use strict";', - '', - 'var x = function x(y) {', - ' return y;', - '};' + "\"use strict\";", + "", + "var x = function x(y) {", + " return y;", + "};" ].join("\n"), result.code); // 2. passPerPreset: false aliasBaseType = null; - var result = execTest(false); + result = execTest(false); assert.equal(aliasBaseType, null); assert.deepEqual([ - '"use strict";', - '', - 'var x = function x(y) {', - ' return y;', - '};' + "\"use strict\";", + "", + "var x = function x(y) {", + " return y;", + "};" ].join("\n"), result.code); }); - test("handles preset shortcuts (adds babel-preset-)", function () { + it("handles preset shortcuts (adds babel-preset-)", function () { return assert.throws( function () { babel.transform("", { @@ -268,7 +266,7 @@ suite("api", function () { ); }); - test("handles preset shortcuts 2 (adds babel-preset-)", function () { + it("handles preset shortcuts 2 (adds babel-preset-)", function () { return assert.throws( function () { babel.transform("", { @@ -279,15 +277,15 @@ suite("api", function () { ); }); - test("source map merging", function () { - var result = babel.transform([ - 'function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }', - '', - 'let Foo = function Foo() {', - ' _classCallCheck(this, Foo);', - '};', - '', - '//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZG91dCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztJQUFNLEdBQUcsWUFBSCxHQUFHO3dCQUFILEdBQUciLCJmaWxlIjoidW5kZWZpbmVkIiwic291cmNlc0NvbnRlbnQiOlsiY2xhc3MgRm9vIHt9XG4iXX0=' + it("source map merging", function () { + let result = babel.transform([ + "function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }", + "", + "let Foo = function Foo() {", + " _classCallCheck(this, Foo);", + "};", + "", + "//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZG91dCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztJQUFNLEdBQUcsWUFBSCxHQUFHO3dCQUFILEdBQUciLCJmaWxlIjoidW5kZWZpbmVkIiwic291cmNlc0NvbnRlbnQiOlsiY2xhc3MgRm9vIHt9XG4iXX0=" ].join("\n"), { sourceMap: true }); @@ -295,7 +293,7 @@ suite("api", function () { assert.deepEqual([ "function _classCallCheck(instance, Constructor) {", " if (!(instance instanceof Constructor)) {", - ' throw new TypeError("Cannot call a class as a function");', + " throw new TypeError(\"Cannot call a class as a function\");", " }", "}", "", @@ -304,7 +302,7 @@ suite("api", function () { "};" ].join("\n"), result.code); - var consumer = new sourceMap.SourceMapConsumer(result.map); + let consumer = new sourceMap.SourceMapConsumer(result.map); assert.deepEqual(consumer.originalPositionFor({ line: 7, @@ -317,24 +315,24 @@ suite("api", function () { }); }); - test("code option false", function () { + it("code option false", function () { return transformAsync("foo('bar');", { code: false }).then(function (result) { assert.ok(!result.code); }); }); - test("ast option false", function () { + it("ast option false", function () { return transformAsync("foo('bar');", { ast: false }).then(function (result) { assert.ok(!result.ast); }); }); - test("auxiliaryComment option", function () { + it("auxiliaryComment option", function () { return transformAsync("class Foo {}", { auxiliaryCommentBefore: "before", auxiliaryCommentAfter: "after", plugins: [function (babel) { - var t = babel.types; + let t = babel.types; return { visitor: { Program: function (path) { @@ -349,9 +347,9 @@ suite("api", function () { }); }); - test("modules metadata", function () { + it("modules metadata", function () { return Promise.all([ - transformAsync('import { externalName as localName } from "external";').then(function (result) { + transformAsync("import { externalName as localName } from \"external\";").then(function (result) { assert.deepEqual(result.metadata.modules.imports[0], { source: "external", imported: ["externalName"], @@ -363,7 +361,7 @@ suite("api", function () { }); }), - transformAsync('import * as localName2 from "external";').then(function (result) { + transformAsync("import * as localName2 from \"external\";").then(function (result) { assert.deepEqual(result.metadata.modules.imports[0], { source: "external", imported: ["*"], @@ -374,7 +372,7 @@ suite("api", function () { }); }), - transformAsync('import localName3 from "external";').then(function (result) { + transformAsync("import localName3 from \"external\";").then(function (result) { assert.deepEqual(result.metadata.modules.imports[0], { source: "external", imported: ["default"], @@ -386,7 +384,7 @@ suite("api", function () { }); }), - transformAsync('import localName from "./array";', { + transformAsync("import localName from \"./array\";", { resolveModuleSource: function() { return "override-source"; } @@ -406,11 +404,11 @@ suite("api", function () { ]); }), - transformAsync('export * as externalName1 from "external";', { + transformAsync("export * as externalName1 from \"external\";", { plugins: [require("../../babel-plugin-syntax-export-extensions")] }).then(function (result) { - assert.deepEqual(result.metadata.modules.exports, { - exported: ['externalName1'], + assert.deepEqual(result.metadata.modules.exports, { + exported: ["externalName1"], specifiers: [{ kind: "external-namespace", exported: "externalName1", @@ -419,7 +417,7 @@ suite("api", function () { }); }), - transformAsync('export externalName2 from "external";', { + transformAsync("export externalName2 from \"external\";", { plugins: [require("../../babel-plugin-syntax-export-extensions")] }).then(function (result) { assert.deepEqual(result.metadata.modules.exports, { @@ -433,7 +431,7 @@ suite("api", function () { }); }), - transformAsync('export function namedFunction() {}').then(function (result) { + transformAsync("export function namedFunction() {}").then(function (result) { assert.deepEqual(result.metadata.modules.exports, { exported: ["namedFunction"], specifiers: [{ @@ -444,7 +442,7 @@ suite("api", function () { }); }), - transformAsync('export var foo = "bar";').then(function (result) { + transformAsync("export var foo = \"bar\";").then(function (result) { assert.deepEqual(result.metadata.modules.exports, { "exported": ["foo"], specifiers: [{ @@ -466,7 +464,7 @@ suite("api", function () { }); }), - transformAsync('export { externalName4 } from "external";').then(function (result) { + transformAsync("export { externalName4 } from \"external\";").then(function (result) { assert.deepEqual(result.metadata.modules.exports, { exported: ["externalName4"], specifiers: [{ @@ -478,7 +476,7 @@ suite("api", function () { }); }), - transformAsync('export * from "external";').then(function (result) { + transformAsync("export * from \"external\";").then(function (result) { assert.deepEqual(result.metadata.modules.exports, { exported: [], specifiers: [{ @@ -501,7 +499,7 @@ suite("api", function () { ]); }); - test("ignore option", function () { + it("ignore option", function () { return Promise.all([ transformAsync("", { ignore: "node_modules", @@ -520,7 +518,7 @@ suite("api", function () { ]); }); - test("only option", function () { + it("only option", function () { return Promise.all([ transformAsync("", { only: "node_modules", @@ -551,12 +549,12 @@ suite("api", function () { only: "foo/node_modules/*.bar", filename: "/foo/node_modules/bar.foo" }).then(assertIgnored) - ]) + ]); }); - suite("env option", function () { - var oldBabelEnv = process.env.BABEL_ENV; - var oldNodeEnv = process.env.NODE_ENV; + describe("env option", function () { + let oldBabelEnv = process.env.BABEL_ENV; + let oldNodeEnv = process.env.NODE_ENV; setup(function () { // Tests need to run with the default and specific values for these. They @@ -570,8 +568,8 @@ suite("api", function () { process.env.NODE_ENV = oldNodeEnv; }); - test("default", function () { - var result = babel.transform("foo;", { + it("default", function () { + let result = babel.transform("foo;", { env: { development: { code: false } } @@ -580,9 +578,9 @@ suite("api", function () { assert.equal(result.code, undefined); }); - test("BABEL_ENV", function () { + it("BABEL_ENV", function () { process.env.BABEL_ENV = "foo"; - var result = babel.transform("foo;", { + let result = babel.transform("foo;", { env: { foo: { code: false } } @@ -590,9 +588,9 @@ suite("api", function () { assert.equal(result.code, undefined); }); - test("NODE_ENV", function () { + it("NODE_ENV", function () { process.env.NODE_ENV = "foo"; - var result = babel.transform("foo;", { + let result = babel.transform("foo;", { env: { foo: { code: false } } @@ -601,9 +599,9 @@ suite("api", function () { }); }); - test("resolveModuleSource option", function () { - var actual = 'import foo from "foo-import-default";\nimport "foo-import-bare";\nexport { foo } from "foo-export-named";'; - var expected = 'import foo from "resolved/foo-import-default";\nimport "resolved/foo-import-bare";\nexport { foo } from "resolved/foo-export-named";'; + it("resolveModuleSource option", function () { + let actual = "import foo from \"foo-import-default\";\nimport \"foo-import-bare\";\nexport { foo } from \"foo-export-named\";"; + let expected = "import foo from \"resolved/foo-import-default\";\nimport \"resolved/foo-import-bare\";\nexport { foo } from \"resolved/foo-export-named\";"; return transformAsync(actual, { resolveModuleSource: function (originalSource) { @@ -614,27 +612,27 @@ suite("api", function () { }); }); - suite("buildExternalHelpers", function () { - test("all", function () { - var script = buildExternalHelpers(); + describe("buildExternalHelpers", function () { + it("all", function () { + let script = buildExternalHelpers(); assert.ok(script.indexOf("classCallCheck") >= -1); assert.ok(script.indexOf("inherits") >= 0); }); - test("whitelist", function () { - var script = buildExternalHelpers(["inherits"]); + it("whitelist", function () { + let script = buildExternalHelpers(["inherits"]); assert.ok(script.indexOf("classCallCheck") === -1); assert.ok(script.indexOf("inherits") >= 0); }); - test("empty whitelist", function () { - var script = buildExternalHelpers([]); + it("empty whitelist", function () { + let script = buildExternalHelpers([]); assert.ok(script.indexOf("classCallCheck") === -1); assert.ok(script.indexOf("inherits") === -1); }); - test("underscored", function () { - var script = buildExternalHelpers(["typeof"]); + it("underscored", function () { + let script = buildExternalHelpers(["typeof"]); assert.ok(script.indexOf("typeof") >= 0); }); }); diff --git a/packages/babel-core/test/browserify.js b/packages/babel-core/test/browserify.js index a7e7b5727e0d..9923f6c52ea8 100644 --- a/packages/babel-core/test/browserify.js +++ b/packages/babel-core/test/browserify.js @@ -1,11 +1,11 @@ -var browserify = require("browserify"); -var assert = require("assert"); -var path = require("path"); -var vm = require("vm"); +let browserify = require("browserify"); +let assert = require("assert"); +let path = require("path"); +let vm = require("vm"); -suite("browserify", function() { - test("babel/register may be used without breaking browserify", function(done) { - var bundler = browserify(path.join(__dirname, "fixtures/browserify/register.js")); +describe("browserify", function() { + it("babel/register may be used without breaking browserify", function(done) { + let bundler = browserify(path.join(__dirname, "fixtures/browserify/register.js")); bundler.bundle(function(err, bundle) { if (err) return done(err); @@ -14,6 +14,6 @@ suite("browserify", function() { // ensure that the code runs without throwing an exception vm.runInNewContext("var global = this;\n" + bundle, {}); done(); - }) - }) + }); + }); }); diff --git a/packages/babel-core/test/config-chain.js b/packages/babel-core/test/config-chain.js index dbcf48b4e51d..0a0b952d5123 100644 --- a/packages/babel-core/test/config-chain.js +++ b/packages/babel-core/test/config-chain.js @@ -1,18 +1,18 @@ -var assert = require("assert"); -var path = require("path"); -var buildConfigChain = require("../lib/transformation/file/options/build-config-chain"); +let assert = require("assert"); +let path = require("path"); +let buildConfigChain = require("../lib/transformation/file/options/build-config-chain"); function fixture() { - var args = [__dirname, "fixtures", "config"]; - for (var i = 0; i < arguments.length; i ++) { + let args = [__dirname, "fixtures", "config"]; + for (let i = 0; i < arguments.length; i ++) { args.push(arguments[i]); } return path.join.apply(path, args); } -suite("buildConfigChain", function () { - var oldBabelEnv; - var oldNodeEnv; +describe("buildConfigChain", function () { + let oldBabelEnv; + let oldNodeEnv; beforeEach(function () { oldBabelEnv = process.env.BABEL_ENV; @@ -27,12 +27,12 @@ suite("buildConfigChain", function () { process.env.NODE_ENV = oldNodeEnv; }); - test("dir1", function () { - var chain = buildConfigChain({ + it("dir1", function () { + let chain = buildConfigChain({ filename: fixture("dir1", "src.js") }); - var expected = [ + let expected = [ { options: { plugins: [ @@ -76,12 +76,12 @@ suite("buildConfigChain", function () { assert.deepEqual(chain, expected); }); - test("dir2", function () { - var chain = buildConfigChain({ + it("dir2", function () { + let chain = buildConfigChain({ filename: fixture("dir2", "src.js") }); - var expected = [ + let expected = [ { options: { plugins: [ @@ -115,12 +115,12 @@ suite("buildConfigChain", function () { assert.deepEqual(chain, expected); }); - test("env - base", function () { - var chain = buildConfigChain({ + it("env - base", function () { + let chain = buildConfigChain({ filename: fixture("env", "src.js") }); - var expected = [ + let expected = [ { options: { plugins: [ @@ -154,14 +154,14 @@ suite("buildConfigChain", function () { assert.deepEqual(chain, expected); }); - test("env - foo", function () { + it("env - foo", function () { process.env.NODE_ENV = "foo"; - var chain = buildConfigChain({ + let chain = buildConfigChain({ filename: fixture("env", "src.js") }); - var expected = [ + let expected = [ { options: { plugins: [ @@ -205,15 +205,15 @@ suite("buildConfigChain", function () { assert.deepEqual(chain, expected); }); - test("env - bar", function () { + it("env - bar", function () { process.env.NODE_ENV = "foo"; // overridden process.env.NODE_ENV = "bar"; - var chain = buildConfigChain({ + let chain = buildConfigChain({ filename: fixture("env", "src.js") }); - var expected = [ + let expected = [ { options: { plugins: [ @@ -258,14 +258,14 @@ suite("buildConfigChain", function () { }); - test("env - foo", function () { + it("env - foo", function () { process.env.NODE_ENV = "foo"; - var chain = buildConfigChain({ + let chain = buildConfigChain({ filename: fixture("pkg", "src.js") }); - var expected = [ + let expected = [ { options: { plugins: ["pkg-plugin"] diff --git a/packages/babel-core/test/evaluation.js b/packages/babel-core/test/evaluation.js index 6d8b4dfbd386..1af3bc739933 100644 --- a/packages/babel-core/test/evaluation.js +++ b/packages/babel-core/test/evaluation.js @@ -1,16 +1,16 @@ -var traverse = require("babel-traverse").default; -var assert = require("assert"); -var parse = require("babylon").parse; +let traverse = require("babel-traverse").default; +let assert = require("assert"); +let parse = require("babylon").parse; -suite("evaluation", function () { +describe("evaluation", function () { function addTest(code, type, value, notConfident) { - test(type + ": " + code, function () { - var visitor = {}; + it(type + ": " + code, function () { + let visitor = {}; visitor[type] = function (path) { - var evaluate = path.evaluate(); + let evaluate = path.evaluate(); assert.equal(evaluate.confident, !notConfident); - assert.equal(evaluate.value, value); + assert.deepEqual(evaluate.value, value); }; traverse(parse(code, { @@ -63,4 +63,7 @@ suite("evaluation", function () { addTest("'abc' === 'xyz' || (1 === 1 && config.flag)", "LogicalExpression", undefined, true); addTest("'abc' === 'xyz' || (1 === 1 && 'four' === 'four')", "LogicalExpression", true); addTest("'abc' === 'abc' && (1 === 1 && 'four' === 'four')", "LogicalExpression", true); + addTest("({})", "ObjectExpression", {}); + addTest("({a: '1'})", "ObjectExpression", {a: "1"}); + addTest("({['a' + 'b']: 10 * 20, 'z': [1, 2, 3]})", "ObjectExpression", {ab: 200, z: [1, 2, 3]}); }); diff --git a/packages/babel-core/test/fixtures/transformation/errors/syntax/options.json b/packages/babel-core/test/fixtures/transformation/errors/syntax/options.json index 7c05159f4573..b6814bef5f23 100644 --- a/packages/babel-core/test/fixtures/transformation/errors/syntax/options.json +++ b/packages/babel-core/test/fixtures/transformation/errors/syntax/options.json @@ -1,3 +1,3 @@ { - "throws": "Unexpected token (2:10)" + "throws": "Unexpected token, expected ; (2:10)" } diff --git a/packages/babel-core/test/fixtures/transformation/misc/class-property-initializer-blocks-shadow/actual.js b/packages/babel-core/test/fixtures/transformation/misc/class-property-initializer-blocks-shadow/actual.js new file mode 100644 index 000000000000..0a1fda2178b5 --- /dev/null +++ b/packages/babel-core/test/fixtures/transformation/misc/class-property-initializer-blocks-shadow/actual.js @@ -0,0 +1,10 @@ +class A { + prop1 = () => this; + static prop2 = () => this; + prop3 = () => arguments; + static prop4 = () => arguments; + prop5 = this; + static prop6 = this; + prop7 = arguments; + static prop8 = arguments; +} diff --git a/packages/babel-core/test/fixtures/transformation/misc/class-property-initializer-blocks-shadow/expected.js b/packages/babel-core/test/fixtures/transformation/misc/class-property-initializer-blocks-shadow/expected.js new file mode 100644 index 000000000000..0a1fda2178b5 --- /dev/null +++ b/packages/babel-core/test/fixtures/transformation/misc/class-property-initializer-blocks-shadow/expected.js @@ -0,0 +1,10 @@ +class A { + prop1 = () => this; + static prop2 = () => this; + prop3 = () => arguments; + static prop4 = () => arguments; + prop5 = this; + static prop6 = this; + prop7 = arguments; + static prop8 = arguments; +} diff --git a/packages/babel-core/test/fixtures/transformation/misc/class-property-initializer-blocks-shadow/options.json b/packages/babel-core/test/fixtures/transformation/misc/class-property-initializer-blocks-shadow/options.json new file mode 100644 index 000000000000..7b4b86975020 --- /dev/null +++ b/packages/babel-core/test/fixtures/transformation/misc/class-property-initializer-blocks-shadow/options.json @@ -0,0 +1,3 @@ +{ + "plugins": ["syntax-class-properties"] +} diff --git a/packages/babel-core/test/option-manager.js b/packages/babel-core/test/option-manager.js index 63f53b5d8867..592c431d5481 100644 --- a/packages/babel-core/test/option-manager.js +++ b/packages/babel-core/test/option-manager.js @@ -1,70 +1,75 @@ -var assert = require("assert"); -var OptionManager = require("../lib/transformation/file/options/option-manager"); -var Logger = require("../lib/transformation/file/logger"); -var path = require("path"); +import assert from "assert"; +import OptionManager from "../lib/transformation/file/options/option-manager"; +import Logger from "../lib/transformation/file/logger"; +import path from "path"; -suite("option-manager", function () { - suite("memoisePluginContainer", function () { - test("throws for babel 5 plugin", function() { +describe("option-manager", () => { + describe("memoisePluginContainer", () => { + it("throws for babel 5 plugin", () => { return assert.throws( - function () { - OptionManager.memoisePluginContainer( - function (ref) { - var Plugin = ref.Plugin; - return new Plugin("object-assign", {}); - } - ); - }, + () => OptionManager.memoisePluginContainer(({ Plugin }) => new Plugin("object-assign", {})), /Babel 5 plugin is being run with Babel 6/ ); - }) + }); }); - suite("mergeOptions", function () { - test("throws for removed babel 5 options", function() { + describe("mergeOptions", () => { + it("throws for removed babel 5 options", () => { return assert.throws( - function () { - var opt = new OptionManager(new Logger(null, "unknown")); + () => { + let opt = new OptionManager(new Logger(null, "unknown")); opt.init({ - 'randomOption': true + "randomOption": true }); }, /Unknown option: base.randomOption/ ); }); - test("throws for removed babel 5 options", function() { + it("throws for removed babel 5 options", () => { return assert.throws( - function () { - var opt = new OptionManager(new Logger(null, "unknown")); + () => { + let opt = new OptionManager(new Logger(null, "unknown")); opt.init({ - 'auxiliaryComment': true, - 'blacklist': true + "auxiliaryComment": true, + "blacklist": true }); }, /Using removed Babel 5 option: base.auxiliaryComment - Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`/ ); }); - test("throws for resolved but erroring preset", function() { + it("throws for resolved but erroring preset", () => { return assert.throws( - function () { - var opt = new OptionManager(new Logger(null, "unknown")); + () => { + let opt = new OptionManager(new Logger(null, "unknown")); opt.init({ - 'presets': [path.join(__dirname, "fixtures/option-manager/not-a-preset")] + "presets": [path.join(__dirname, "fixtures/option-manager/not-a-preset")] }); }, /While processing preset: .*option-manager(?:\/|\\\\)not-a-preset\.js/ ); }); + + it("throws for invalid preset configuration", function() { + return assert.throws( + function () { + let opt = new OptionManager(new Logger(null, "unknown")); + opt.init({ + "presets": [{ option: "value" }] + }); + }, + /Unknown option: foreign.option\.(?:.|\n)+A common cause of this error is the presence of a configuration options object without the corresponding preset name/ + ); + }); }); - suite("presets", function () { + describe("presets", function () { function presetTest(name) { - test(name, function () { - var opt = new OptionManager(new Logger(null, "unknown")); - var options = opt.init({ - 'presets': [path.join(__dirname, "fixtures/option-manager/presets", name)] + it(name, function () { + let opt = new OptionManager(new Logger(null, "unknown")); + let options = opt.init({ + "presets": [path.join(__dirname, "fixtures/option-manager/presets", name)] }); assert.equal(true, Array.isArray(options.plugins)); @@ -72,14 +77,14 @@ suite("option-manager", function () { }); } - presetTest('es5'); - presetTest('es5_function'); - presetTest('es2015_default'); - presetTest('es2015_default_function'); - presetTest('es2015_default_object_function'); - presetTest('es2015_function'); - presetTest('es2015_function_fallback'); - presetTest('es2015_named'); + presetTest("es5"); + presetTest("es5_function"); + presetTest("es2015_default"); + presetTest("es2015_default_function"); + presetTest("es2015_default_object_function"); + presetTest("es2015_function"); + presetTest("es2015_function_fallback"); + presetTest("es2015_named"); }); }); diff --git a/packages/babel-core/test/path.js b/packages/babel-core/test/path.js index 1b8ae9044a23..c76fc31e59bd 100644 --- a/packages/babel-core/test/path.js +++ b/packages/babel-core/test/path.js @@ -1,13 +1,12 @@ -var transform = require("../lib/api/node").transform; -var Plugin = require("../lib/transformation/plugin"); -var babel = require("../lib/api/node"); -var chai = require("chai"); +let transform = require("../lib/api/node").transform; +let Plugin = require("../lib/transformation/plugin"); +let chai = require("chai"); -suite("traversal path", function () { - test("replaceWithSourceString", function () { - var expectCode = "function foo() {}"; +describe("traversal path", function () { + it("replaceWithSourceString", function () { + let expectCode = "function foo() {}"; - var actualCode = transform(expectCode, { + let actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { FunctionDeclaration: function (path) { @@ -20,10 +19,10 @@ suite("traversal path", function () { chai.expect(actualCode).to.be.equal("console.whatever();"); }); - test("replaceWith (arrow expression body to block statement body)", function () { - var expectCode = "var fn = () => true;"; + it("replaceWith (arrow expression body to block statement body)", function () { + let expectCode = "var fn = () => true;"; - var actualCode = transform(expectCode, { + let actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ArrowFunctionExpression: function (path) { @@ -45,10 +44,10 @@ suite("traversal path", function () { chai.expect(actualCode).to.be.equal("var fn = () => {\n return true;\n};"); }); - test("replaceWith (arrow block statement body to expression body)", function () { - var expectCode = "var fn = () => { return true; }"; + it("replaceWith (arrow block statement body to expression body)", function () { + let expectCode = "var fn = () => { return true; }"; - var actualCode = transform(expectCode, { + let actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ArrowFunctionExpression: function (path) { @@ -64,10 +63,10 @@ suite("traversal path", function () { chai.expect(actualCode).to.be.equal("var fn = () => true;"); }); - test("replaceWith (for-in left expression to variable declaration)", function () { - var expectCode = "for (KEY in right);"; + it("replaceWith (for-in left expression to variable declaration)", function () { + let expectCode = "for (KEY in right);"; - var actualCode = transform(expectCode, { + let actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ForInStatement: function (path) { @@ -90,10 +89,10 @@ suite("traversal path", function () { chai.expect(actualCode).to.be.equal("for (var KEY in right);"); }); - test("replaceWith (for-in left variable declaration to expression)", function () { - var expectCode = "for (var KEY in right);"; + it("replaceWith (for-in left variable declaration to expression)", function () { + let expectCode = "for (var KEY in right);"; - var actualCode = transform(expectCode, { + let actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ForInStatement: function (path) { @@ -109,10 +108,10 @@ suite("traversal path", function () { chai.expect(actualCode).to.be.equal("for (KEY in right);"); }); - test("replaceWith (for-loop left expression to variable declaration)", function () { - var expectCode = "for (KEY;;);"; + it("replaceWith (for-loop left expression to variable declaration)", function () { + let expectCode = "for (KEY;;);"; - var actualCode = transform(expectCode, { + let actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ForStatement: function (path) { @@ -135,10 +134,10 @@ suite("traversal path", function () { chai.expect(actualCode).to.be.equal("for (var KEY;;);"); }); - test("replaceWith (for-loop left variable declaration to expression)", function () { - var expectCode = "for (var KEY;;);"; + it("replaceWith (for-loop left variable declaration to expression)", function () { + let expectCode = "for (var KEY;;);"; - var actualCode = transform(expectCode, { + let actualCode = transform(expectCode, { plugins: [new Plugin({ visitor: { ForStatement: function (path) { diff --git a/packages/babel-core/test/resolution.js b/packages/babel-core/test/resolution.js index 79294a95fee0..bdffce466d98 100644 --- a/packages/babel-core/test/resolution.js +++ b/packages/babel-core/test/resolution.js @@ -1,14 +1,14 @@ -var assert = require("assert"); -var async = require("async"); -var babel = require("../lib/api/node"); -var fs = require("fs"); -var path = require("path"); +let assert = require("assert"); +let async = require("async"); +let babel = require("../lib/api/node"); +let fs = require("fs"); +let path = require("path"); // Test that plugins & presets are resolved relative to `filename`. -suite("addon resolution", function () { - test("addon resolution", function (done) { - var fixtures = {}; - var paths = {}; +describe("addon resolution", function () { + it("addon resolution", function (done) { + let fixtures = {}; + let paths = {}; paths.fixtures = path.join( __dirname, @@ -33,7 +33,7 @@ suite("addon resolution", function () { function fixturesReady (err) { if (err) return done(err); - var actual = babel.transform(fixtures.actual, { + let actual = babel.transform(fixtures.actual, { filename: paths.actual, plugins: ["addons/plugin"], presets: ["addons/preset"], diff --git a/packages/babel-core/test/util.js b/packages/babel-core/test/util.js index e6ee23ca1afe..ae1e83e91399 100644 --- a/packages/babel-core/test/util.js +++ b/packages/babel-core/test/util.js @@ -1,9 +1,9 @@ -var assert = require("assert"); -var util = require("../lib/util"); -var t = require("babel-types"); +let assert = require("assert"); +let util = require("../lib/util"); +let t = require("babel-types"); -suite("util", function () { - test("canCompile", function () { +describe("util", function () { + it("canCompile", function () { assert.ok(util.canCompile("test.js")); assert.ok(util.canCompile("/test.js")); assert.ok(util.canCompile("/scripts/test.js")); @@ -26,7 +26,7 @@ suite("util", function () { assert.ok(!util.canCompile("/scripts/test.css")); }); - test("list", function () { + it("list", function () { assert.deepEqual(util.list(undefined), []); assert.deepEqual(util.list(false), []); assert.deepEqual(util.list(null), []); @@ -36,11 +36,11 @@ suite("util", function () { assert.deepEqual(util.list(["foo", "bar"]), ["foo", "bar"]); assert.deepEqual(util.list(/foo/), [/foo/]); - var date = new Date; + let date = new Date; assert.deepEqual(util.list(date), [date]); }); - test("arrayify", function () { + it("arrayify", function () { assert.deepEqual(util.arrayify(undefined), []); assert.deepEqual(util.arrayify(false), []); assert.deepEqual(util.arrayify(null), []); @@ -52,7 +52,7 @@ suite("util", function () { assert.deepEqual(util.arrayify(function () { return "foo"; })[0](), "foo"); }); - test("regexify", function () { + it("regexify", function () { assert.deepEqual(util.regexify(undefined), /.^/); assert.deepEqual(util.regexify(false), /.^/); assert.deepEqual(util.regexify(null), /.^/); @@ -73,19 +73,19 @@ suite("util", function () { }, /illegal type for regexify/); }); - test("booleanify", function () { + it("booleanify", function () { assert.strictEqual(util.booleanify("true"), true); assert.strictEqual(util.booleanify("false"), false); assert.strictEqual(util.booleanify("inline"), "inline"); }); - test("toIdentifier", function () { + it("toIdentifier", function () { assert.equal(t.toIdentifier("swag-lord"), "swagLord"); }); - test("shouldIgnore", function () { - var reIgnore = /\-reIgnore\.js/; - var fnIgnore = function (src) { + it("shouldIgnore", function () { + let reIgnore = /\-reIgnore\.js/; + let fnIgnore = function (src) { if (src.indexOf("fnIgnore") > 0) { return true; } diff --git a/packages/babel-generator/src/generators/classes.js b/packages/babel-generator/src/generators/classes.js index db3151f51693..67c3aed42b10 100644 --- a/packages/babel-generator/src/generators/classes.js +++ b/packages/babel-generator/src/generators/classes.js @@ -60,6 +60,7 @@ export function ClassProperty(node: Object) { this.print(node.key, node); this.token("]"); } else { + this._variance(node); this.print(node.key, node); } this.print(node.typeAnnotation, node); diff --git a/packages/babel-generator/src/generators/flow.js b/packages/babel-generator/src/generators/flow.js index ac1a9e0b2293..b6c5a8b20d69 100644 --- a/packages/babel-generator/src/generators/flow.js +++ b/packages/babel-generator/src/generators/flow.js @@ -147,6 +147,14 @@ export function _interfaceish(node: Object) { this.print(node.body, node); } +export function _variance(node) { + if (node.variance === "plus") { + this.token("+"); + } else if (node.variance === "minus") { + this.token("-"); + } +} + export function InterfaceDeclaration(node: Object) { this.word("interface"); this.space(); @@ -167,6 +175,10 @@ export function MixedTypeAnnotation() { this.word("mixed"); } +export function EmptyTypeAnnotation() { + this.word("empty"); +} + export function NullableTypeAnnotation(node: Object) { this.token("?"); this.print(node.typeAnnotation, node); @@ -221,11 +233,7 @@ export function TypeAnnotation(node: Object) { } export function TypeParameter(node: Object) { - if (node.variance === "plus") { - this.token("+"); - } else if (node.variance === "minus") { - this.token("-"); - } + this._variance(node); this.word(node.name); @@ -295,6 +303,7 @@ export function ObjectTypeIndexer(node: Object) { this.word("static"); this.space(); } + this._variance(node); this.token("["); this.print(node.id, node); this.token(":"); @@ -311,6 +320,7 @@ export function ObjectTypeProperty(node: Object) { this.word("static"); this.space(); } + this._variance(node); this.print(node.key, node); if (node.optional) this.token("?"); this.token(":"); diff --git a/packages/babel-generator/test/fixtures/flow/def-site-variance/actual.js b/packages/babel-generator/test/fixtures/flow/def-site-variance/actual.js index f046505722fe..a9cf25b9c27a 100644 --- a/packages/babel-generator/test/fixtures/flow/def-site-variance/actual.js +++ b/packages/babel-generator/test/fixtures/flow/def-site-variance/actual.js @@ -1,3 +1,17 @@ -class C<+T, -U> {} +class C1<+T, -U> {} function f<+T, -U>() {} type T<+T, -U> = {}; +type T = { +p: T }; +type T = { -p: T }; +type T = { +[k:K]: V }; +type T = { -[k:K]: V }; +interface I { +p: T }; +interface I { -p: T }; +interface I { +[k:K]: V }; +interface I { -[k:K]: V }; +declare class I { +p: T }; +declare class I { -p: T }; +declare class I { +[k:K]: V }; +declare class I { -[k:K]: V }; +class C2 { +p: T = e }; +class C3 { -p: T = e }; diff --git a/packages/babel-generator/test/fixtures/flow/def-site-variance/expected.js b/packages/babel-generator/test/fixtures/flow/def-site-variance/expected.js index f046505722fe..1538e1ec99c6 100644 --- a/packages/babel-generator/test/fixtures/flow/def-site-variance/expected.js +++ b/packages/babel-generator/test/fixtures/flow/def-site-variance/expected.js @@ -1,3 +1,21 @@ -class C<+T, -U> {} +class C1<+T, -U> {} function f<+T, -U>() {} type T<+T, -U> = {}; +type T = { +p: T }; +type T = { -p: T }; +type T = { +[k: K]: V }; +type T = { -[k: K]: V }; +interface I { +p: T }; +interface I { -p: T }; +interface I { +[k: K]: V }; +interface I { -[k: K]: V }; +declare class I { +p: T }; +declare class I { -p: T }; +declare class I { +[k: K]: V }; +declare class I { -[k: K]: V }; +class C2 { + +p: T = e; +}; +class C3 { + -p: T = e; +}; diff --git a/packages/babel-generator/test/index.js b/packages/babel-generator/test/index.js index 450de50ae1d9..92b4c5b3d274 100644 --- a/packages/babel-generator/test/index.js +++ b/packages/babel-generator/test/index.js @@ -1,14 +1,14 @@ -var Whitespace = require("../lib/whitespace"); -var Printer = require("../lib/printer"); -var generate = require("../lib"); -var assert = require("assert"); -var parse = require("babylon").parse; -var chai = require("chai"); -var t = require("babel-types"); -var _ = require("lodash"); - -suite("generation", function () { - test("completeness", function () { +let Whitespace = require("../lib/whitespace"); +let Printer = require("../lib/printer"); +let generate = require("../lib"); +let assert = require("assert"); +let parse = require("babylon").parse; +let chai = require("chai"); +let t = require("babel-types"); +let _ = require("lodash"); + +describe("generation", function () { + it("completeness", function () { _.each(t.VISITOR_KEYS, function (keys, type) { assert.ok(!!Printer.prototype[type], type + " should exist"); }); @@ -19,17 +19,17 @@ suite("generation", function () { }); }); - test("multiple sources", function () { - var sources = { + it("multiple sources", function () { + let sources = { "a.js": "function hi (msg) { console.log(msg); }\n", "b.js": "hi('hello');\n" }; - var parsed = _.keys(sources).reduce(function (_parsed, filename) { + let parsed = _.keys(sources).reduce(function (_parsed, filename) { _parsed[filename] = parse(sources[filename], { sourceFilename: filename }); return _parsed; }, {}); - var combinedAst = { + let combinedAst = { "type": "File", "program": { "type": "Program", @@ -38,22 +38,21 @@ suite("generation", function () { } }; - var generated = generate.default(combinedAst, { sourceMaps: true }, sources); + let generated = generate.default(combinedAst, { sourceMaps: true }, sources); chai.expect(generated.map).to.deep.equal({ version: 3, - sources: [ 'a.js', 'b.js' ], - names: [], - mappings: 'AAAA,SAASA,EAAT,CAAaC,GAAb,EAAkB;AAAEC,UAAQC,GAAR,CAAYF,GAAZ;AAAmB;;ACAvCD,GAAG,OAAH', + sources: [ "a.js", "b.js" ], + mappings: "AAAA,SAASA,EAAT,CAAaC,GAAb,EAAkB;AAAEC,UAAQC,GAAR,CAAYF,GAAZ;AAAmB;;ACAvCD,GAAG,OAAH", names: [ - 'hi', - 'msg', - 'console', - 'log', + "hi", + "msg", + "console", + "log", ], sourcesContent: [ - 'function hi (msg) { console.log(msg); }\n', - 'hi(\'hello\');\n' + "function hi (msg) { console.log(msg); }\n", + "hi('hello');\n" ] }, "sourcemap was incorrectly generated"); @@ -63,21 +62,21 @@ suite("generation", function () { ); }); - test("identifierName", function () { - var code = "function foo() { bar; }\n"; + it("identifierName", function () { + let code = "function foo() { bar; }\n"; - var ast = parse(code, { filename: "inline" }).program; - var fn = ast.body[0]; + let ast = parse(code, { filename: "inline" }).program; + let fn = ast.body[0]; - var id = fn.id; + let id = fn.id; id.name += "2"; id.loc.identifierName = "foo"; - var id2 = fn.body.body[0].expression; + let id2 = fn.body.body[0].expression; id2.name += "2"; id2.loc.identiferName = "bar"; - var generated = generate.default(ast, { + let generated = generate.default(ast, { filename: "inline", sourceFileName: "inline", sourceMaps: true @@ -99,15 +98,15 @@ suite("generation", function () { }); -suite("programmatic generation", function() { - test("numeric member expression", function() { +describe("programmatic generation", function() { + it("numeric member expression", function() { // Should not generate `0.foo` - var mem = t.memberExpression(t.numericLiteral(60702), t.identifier("foo")); + let mem = t.memberExpression(t.numericLiteral(60702), t.identifier("foo")); new Function(generate.default(mem).code); }); - test("nested if statements needs block", function() { - var ifStatement = t.ifStatement( + it("nested if statements needs block", function() { + let ifStatement = t.ifStatement( t.stringLiteral("top cond"), t.whileStatement( t.stringLiteral("while cond"), @@ -119,15 +118,15 @@ suite("programmatic generation", function() { t.expressionStatement(t.stringLiteral("alt")) ); - var ast = parse(generate.default(ifStatement).code); - assert.equal(ast.program.body[0].consequent.type, 'BlockStatement'); + let ast = parse(generate.default(ifStatement).code); + assert.equal(ast.program.body[0].consequent.type, "BlockStatement"); }); - test("flow object indentation", function() { - var objectStatement = t.objectTypeAnnotation( + it("flow object indentation", function() { + let objectStatement = t.objectTypeAnnotation( [ t.objectTypeProperty( - t.identifier('bar'), + t.identifier("bar"), t.stringTypeAnnotation() ), ], @@ -135,32 +134,32 @@ suite("programmatic generation", function() { null ); - var output = generate.default(objectStatement).code; + let output = generate.default(objectStatement).code; assert.equal(output, [ - '{', - ' bar: string;', - '}', - ].join('\n')); + "{", + " bar: string;", + "}", + ].join("\n")); }); }); -suite("whitespace", function () { - test("empty token list", function () { - var w = new Whitespace([]); - assert.equal(w.getNewlinesBefore(t.stringLiteral('1')), 0); +describe("whitespace", function () { + it("empty token list", function () { + let w = new Whitespace([]); + assert.equal(w.getNewlinesBefore(t.stringLiteral("1")), 0); }); }); -var suites = require("babel-helper-fixtures").default(__dirname + "/fixtures"); +let suites = require("babel-helper-fixtures").default(__dirname + "/fixtures"); suites.forEach(function (testSuite) { - suite("generation/" + testSuite.title, function () { + describe("generation/" + testSuite.title, function () { _.each(testSuite.tests, function (task) { - test(task.title, !task.disabled && function () { - var expect = task.expect; - var actual = task.actual; + it(task.title, !task.disabled && function () { + let expect = task.expect; + let actual = task.actual; - var actualAst = parse(actual.code, { + let actualAst = parse(actual.code, { filename: actual.loc, plugins: [ "jsx", @@ -176,7 +175,7 @@ suites.forEach(function (testSuite) { sourceType: "module", }); - var actualCode = generate.default(actualAst, task.options, actual.code).code; + let actualCode = generate.default(actualAst, task.options, actual.code).code; chai.expect(actualCode).to.equal(expect.code, actual.loc + " !== " + expect.loc); }); }); diff --git a/packages/babel-helper-bindify-decorators/package.json b/packages/babel-helper-bindify-decorators/package.json index 07cb5947202e..e8c7d8e891c4 100644 --- a/packages/babel-helper-bindify-decorators/package.json +++ b/packages/babel-helper-bindify-decorators/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-bindify-decorators", "version": "6.8.0", - "description": "", + "description": "Helper function to bindify decorators", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-bindify-decorators", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-builder-binary-assignment-operator-visitor/package.json b/packages/babel-helper-builder-binary-assignment-operator-visitor/package.json index 3609783f3cdc..5344d904260d 100644 --- a/packages/babel-helper-builder-binary-assignment-operator-visitor/package.json +++ b/packages/babel-helper-builder-binary-assignment-operator-visitor/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-builder-binary-assignment-operator-visitor", "version": "6.15.0", - "description": "", + "description": "Helper function to build binary assignment operator visitors", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-builder-binary-assignment-operator-visitor", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-builder-conditional-assignment-operator-visitor/package.json b/packages/babel-helper-builder-conditional-assignment-operator-visitor/package.json index 083caae233b9..95f77f091361 100644 --- a/packages/babel-helper-builder-conditional-assignment-operator-visitor/package.json +++ b/packages/babel-helper-builder-conditional-assignment-operator-visitor/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-builder-conditional-assignment-operator-visitor", "version": "6.8.0", - "description": "", + "description": "Helper function to build conditional assignment operator visitors", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-builder-conditional-assignment-operator-visitor", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-builder-react-jsx/package.json b/packages/babel-helper-builder-react-jsx/package.json index fa1ac5bd220b..c23eada17358 100644 --- a/packages/babel-helper-builder-react-jsx/package.json +++ b/packages/babel-helper-builder-react-jsx/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-builder-react-jsx", "version": "6.9.0", - "description": "", + "description": "Helper function to build react jsx", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-builder-react-jsx", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-builder-react-jsx/src/index.js b/packages/babel-helper-builder-react-jsx/src/index.js index 7d1301deb0fe..2438070df0d7 100644 --- a/packages/babel-helper-builder-react-jsx/src/index.js +++ b/packages/babel-helper-builder-react-jsx/src/index.js @@ -118,7 +118,7 @@ export default function (opts) { /** * The logic for this is quite terse. It's because we need to * support spread elements. We loop over all attributes, - * breaking on spreads, we then push a new object containg + * breaking on spreads, we then push a new object containing * all prior attributes to an array for later processing. */ @@ -126,6 +126,11 @@ export default function (opts) { let _props = []; let objs = []; + let useBuiltIns = file.opts.useBuiltIns || false; + if (typeof useBuiltIns !== "boolean") { + throw new Error("transform-react-jsx currently only accepts a boolean option for useBuiltIns (defaults to false)"); + } + function pushProps() { if (!_props.length) return; @@ -154,11 +159,12 @@ export default function (opts) { objs.unshift(t.objectExpression([])); } + const helper = useBuiltIns ? + t.memberExpression(t.identifier("Object"), t.identifier("assign")) : + file.addHelper("extends"); + // spread it - attribs = t.callExpression( - file.addHelper("extends"), - objs - ); + attribs = t.callExpression(helper, objs); } return attribs; diff --git a/packages/babel-helper-call-delegate/package.json b/packages/babel-helper-call-delegate/package.json index cd8cd1e01fbb..916874c0c3b1 100644 --- a/packages/babel-helper-call-delegate/package.json +++ b/packages/babel-helper-call-delegate/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-call-delegate", "version": "6.8.0", - "description": "", + "description": "Helper function to call delegate", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-call-delegate", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-define-map/package.json b/packages/babel-helper-define-map/package.json index e93d37b4f7c8..90b2668c5ef1 100644 --- a/packages/babel-helper-define-map/package.json +++ b/packages/babel-helper-define-map/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-define-map", "version": "6.9.0", - "description": "", + "description": "Helper function to define a map", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-define-map", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-explode-assignable-expression/package.json b/packages/babel-helper-explode-assignable-expression/package.json index 7136298b481d..7cdb2c901b62 100644 --- a/packages/babel-helper-explode-assignable-expression/package.json +++ b/packages/babel-helper-explode-assignable-expression/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-explode-assignable-expression", "version": "6.8.0", - "description": "", + "description": "Helper function to explode an assignable expression", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-explode-assignable-expression", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-explode-class/package.json b/packages/babel-helper-explode-class/package.json index 5cd09a2fa6d4..2769415686f3 100644 --- a/packages/babel-helper-explode-class/package.json +++ b/packages/babel-helper-explode-class/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-explode-class", "version": "6.8.0", - "description": "", + "description": "Helper function to explode class", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-explode-class", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-fixtures/package.json b/packages/babel-helper-fixtures/package.json index a43eb35295ee..c70c93cfb9b5 100644 --- a/packages/babel-helper-fixtures/package.json +++ b/packages/babel-helper-fixtures/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-fixtures", "version": "6.9.0", - "description": "", + "description": "Helper function to support fixtures", "author": "Sebastian McKenzie ", "license": "MIT", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-fixtures", @@ -9,7 +9,6 @@ "dependencies": { "babel-runtime": "^6.9.0", "lodash": "^4.2.0", - "path-exists": "^1.0.0", "try-resolve": "^1.0.0" } } diff --git a/packages/babel-helper-fixtures/src/index.js b/packages/babel-helper-fixtures/src/index.js index 9abbf8845ea4..28481e1d6743 100644 --- a/packages/babel-helper-fixtures/src/index.js +++ b/packages/babel-helper-fixtures/src/index.js @@ -1,4 +1,3 @@ -import pathExists from "path-exists"; import resolve from "try-resolve"; import path from "path"; import fs from "fs"; @@ -132,12 +131,12 @@ export default function get(entryLoc): Array { suite.tests.push(test); let sourceMappingsLoc = taskDir + "/source-mappings.json"; - if (pathExists.sync(sourceMappingsLoc)) { + if (fs.existsSync(sourceMappingsLoc)) { test.sourceMappings = JSON.parse(readFile(sourceMappingsLoc)); } let sourceMapLoc = taskDir + "/source-map.json"; - if (pathExists.sync(sourceMapLoc)) { + if (fs.existsSync(sourceMapLoc)) { test.sourceMap = JSON.parse(readFile(sourceMapLoc)); } } @@ -162,7 +161,7 @@ export function multiple(entryLoc, ignore?: Array) { } export function readFile(filename) { - if (pathExists.sync(filename)) { + if (fs.existsSync(filename)) { let file = _.trimEnd(fs.readFileSync(filename, "utf8")); file = file.replace(/\r\n/g, "\n"); return file; diff --git a/packages/babel-helper-function-name/package.json b/packages/babel-helper-function-name/package.json index 1b41e1793a28..3fdca522f301 100644 --- a/packages/babel-helper-function-name/package.json +++ b/packages/babel-helper-function-name/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-function-name", "version": "6.8.0", - "description": "", + "description": "Helper function to change the property 'name' of every function", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-function-name", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-get-function-arity/package.json b/packages/babel-helper-get-function-arity/package.json index cdf25a5baa04..fabafd1632f2 100644 --- a/packages/babel-helper-get-function-arity/package.json +++ b/packages/babel-helper-get-function-arity/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-get-function-arity", "version": "6.8.0", - "description": "", + "description": "Helper function to get function arity", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-get-function-arity", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-hoist-variables/package.json b/packages/babel-helper-hoist-variables/package.json index 5512078c90c3..c43546fb0f69 100644 --- a/packages/babel-helper-hoist-variables/package.json +++ b/packages/babel-helper-hoist-variables/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-hoist-variables", "version": "6.8.0", - "description": "", + "description": "Helper function to hoist variables", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-hoist-variables", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-optimise-call-expression/package.json b/packages/babel-helper-optimise-call-expression/package.json index fa4821d4c309..e9638b0a82a9 100644 --- a/packages/babel-helper-optimise-call-expression/package.json +++ b/packages/babel-helper-optimise-call-expression/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-optimise-call-expression", "version": "6.8.0", - "description": "", + "description": "Helper function to optimise call expression", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-optimise-call-expression", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-plugin-test-runner/package.json b/packages/babel-helper-plugin-test-runner/package.json index f044c935a510..ad8f2de29d80 100644 --- a/packages/babel-helper-plugin-test-runner/package.json +++ b/packages/babel-helper-plugin-test-runner/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-plugin-test-runner", "version": "6.8.0", - "description": "", + "description": "Helper function to support test runner", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-plugin-test-runner", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-regex/package.json b/packages/babel-helper-regex/package.json index 8d6d3e3d6213..7381fe45dbec 100644 --- a/packages/babel-helper-regex/package.json +++ b/packages/babel-helper-regex/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-regex", "version": "6.9.0", - "description": "", + "description": "Helper function to check for literal RegEx", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-regex", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-remap-async-to-generator/package.json b/packages/babel-helper-remap-async-to-generator/package.json index 92c2c5ab03ad..429a58f59f9a 100644 --- a/packages/babel-helper-remap-async-to-generator/package.json +++ b/packages/babel-helper-remap-async-to-generator/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-remap-async-to-generator", "version": "6.16.2", - "description": "", + "description": "Helper function to remap async functions to generators", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-remap-async-to-generator", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-remap-async-to-generator/src/index.js b/packages/babel-helper-remap-async-to-generator/src/index.js index 64c2a474391d..056606da3aab 100644 --- a/packages/babel-helper-remap-async-to-generator/src/index.js +++ b/packages/babel-helper-remap-async-to-generator/src/index.js @@ -90,6 +90,10 @@ function classOrObjectMethod(path: NodePath, callId: Object) { [] )) ]; + + // Regardless of whether or not the wrapped function is a an async method + // or generator the outer function should not be + node.generator = false; } function plainFunction(path: NodePath, callId: Object) { diff --git a/packages/babel-helper-replace-supers/package.json b/packages/babel-helper-replace-supers/package.json index 2e46084d3b31..bbc96f69b298 100644 --- a/packages/babel-helper-replace-supers/package.json +++ b/packages/babel-helper-replace-supers/package.json @@ -1,7 +1,7 @@ { "name": "babel-helper-replace-supers", "version": "6.16.0", - "description": "", + "description": "Helper function to replace supers", "repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-replace-supers", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-helper-transform-fixture-test-runner/src/index.js b/packages/babel-helper-transform-fixture-test-runner/src/index.js index f1361482ff65..42ce63a16ebe 100644 --- a/packages/babel-helper-transform-fixture-test-runner/src/index.js +++ b/packages/babel-helper-transform-fixture-test-runner/src/index.js @@ -1,6 +1,3 @@ -/* global test */ -/* global suite */ - import * as babel from "babel-core"; import { buildExternalHelpers } from "babel-core"; import getFixtures from "babel-helper-fixtures"; @@ -11,6 +8,8 @@ import assert from "assert"; import chai from "chai"; import _ from "lodash"; import "babel-polyfill"; +import fs from "fs"; +import path from "path"; let babelHelpers = eval(buildExternalHelpers(null, "var")); @@ -66,14 +65,12 @@ function run(task) { let actualCode = actual.code; let expectCode = expect.code; if (!execCode || actualCode) { - result = babel.transform(actualCode, getOpts(actual)); - actualCode = result.code.trim(); - - try { + result = babel.transform(actualCode, getOpts(actual)); + if (!expect.code && result.code && !opts.throws && fs.statSync(path.dirname(expect.loc)).isDirectory() && !process.env.CI) { + fs.writeFileSync(expect.loc, result.code); + } else { + actualCode = result.code.trim(); chai.expect(actualCode).to.be.equal(expectCode, actual.loc + " !== " + expect.loc); - } catch (err) { - //require("fs").writeFileSync(expect.loc, actualCode); - throw err; } } @@ -123,12 +120,12 @@ export default function ( for (let testSuite of suites) { if (_.includes(suiteOpts.ignoreSuites, testSuite.title)) continue; - suite(name + "/" + testSuite.title, function () { + describe(name + "/" + testSuite.title, function () { for (let task of testSuite.tests) { if (_.includes(suiteOpts.ignoreTasks, task.title) || _.includes(suiteOpts.ignoreTasks, testSuite.title + "/" + task.title)) continue; - test(task.title, !task.disabled && function () { + it(task.title, !task.disabled && function () { function runTask() { run(task); } diff --git a/packages/babel-plugin-check-es2015-constants/test/fixtures/general/destructuring/expected.js b/packages/babel-plugin-check-es2015-constants/test/fixtures/general/destructuring/expected.js index 3ad6e248ea16..ebf2bc22451b 100644 --- a/packages/babel-plugin-check-es2015-constants/test/fixtures/general/destructuring/expected.js +++ b/packages/babel-plugin-check-es2015-constants/test/fixtures/general/destructuring/expected.js @@ -1,10 +1,10 @@ -var a = 1; -var b = 2; -var c = 3; -var d = 4; -var _e$f = { e: 5, f: 6 }; -var e = _e$f.e; -var f = _e$f.f; -var _a$b = { a: 7, b: 8 }; -var g = _a$b.a; -var h = _a$b.b; +var a = 1, + b = 2; +var c = 3, + d = 4; +var _e$f = { e: 5, f: 6 }, + e = _e$f.e, + f = _e$f.f; +var _a$b = { a: 7, b: 8 }, + g = _a$b.a, + h = _a$b.b; diff --git a/packages/babel-plugin-external-helpers/package.json b/packages/babel-plugin-external-helpers/package.json index 66be1f18bb78..323ddbadd01e 100644 --- a/packages/babel-plugin-external-helpers/package.json +++ b/packages/babel-plugin-external-helpers/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-external-helpers", "version": "6.8.0", - "description": "", + "description": "This plugin contains helper functions that’ll be placed at the top of the generated code", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-external-helpers", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-syntax-class-constructor-call/README.md b/packages/babel-plugin-syntax-class-constructor-call/README.md index 45b97a326319..174c8d555dc8 100644 --- a/packages/babel-plugin-syntax-class-constructor-call/README.md +++ b/packages/babel-plugin-syntax-class-constructor-call/README.md @@ -1,4 +1,4 @@ -# babel-plugin-syntax-class-constructor-call +# babel-plugin-syntax-class-constructor-call (deprecated) Allow parsing of do expressions. diff --git a/packages/babel-plugin-syntax-class-constructor-call/package.json b/packages/babel-plugin-syntax-class-constructor-call/package.json index 287c8dce7e4f..185dda30cee1 100644 --- a/packages/babel-plugin-syntax-class-constructor-call/package.json +++ b/packages/babel-plugin-syntax-class-constructor-call/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-syntax-class-constructor-call", "version": "6.13.0", - "description": "Allow parsing of class constructor calls", + "description": "Allow parsing of class constructor calls (deprecated)", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-class-constructor-call", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-syntax-dynamic-import/.npmignore b/packages/babel-plugin-syntax-dynamic-import/.npmignore new file mode 100644 index 000000000000..cace0d6ddcdd --- /dev/null +++ b/packages/babel-plugin-syntax-dynamic-import/.npmignore @@ -0,0 +1,3 @@ +node_modules +*.log +src diff --git a/packages/babel-plugin-syntax-dynamic-import/README.md b/packages/babel-plugin-syntax-dynamic-import/README.md new file mode 100644 index 000000000000..47279fcd36d3 --- /dev/null +++ b/packages/babel-plugin-syntax-dynamic-import/README.md @@ -0,0 +1,35 @@ +# babel-plugin-syntax-dynamic-import + +Allow parsing of `import()`. + +## Installation + +```sh +$ npm install babel-plugin-syntax-dynamic-import +``` + +## Usage + +### Via `.babelrc` (Recommended) + +**.babelrc** + +```json +{ + "plugins": ["syntax-dynamic-import"] +} +``` + +### Via CLI + +```sh +$ babel --plugins syntax-dynamic-import script.js +``` + +### Via Node API + +```javascript +require("babel-core").transform("code", { + plugins: ["syntax-dynamic-import"] +}); +``` diff --git a/packages/babel-plugin-syntax-dynamic-import/package.json b/packages/babel-plugin-syntax-dynamic-import/package.json new file mode 100644 index 000000000000..ab6baf23dced --- /dev/null +++ b/packages/babel-plugin-syntax-dynamic-import/package.json @@ -0,0 +1,13 @@ +{ + "name": "babel-plugin-syntax-dynamic-import", + "version": "6.13.0", + "description": "Allow parsing of import()", + "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-dynamic-import", + "license": "MIT", + "main": "lib/index.js", + "keywords": [ + "babel-plugin" + ], + "dependencies": {}, + "devDependencies": {} +} diff --git a/packages/babel-plugin-syntax-dynamic-import/src/index.js b/packages/babel-plugin-syntax-dynamic-import/src/index.js new file mode 100644 index 000000000000..729c74162981 --- /dev/null +++ b/packages/babel-plugin-syntax-dynamic-import/src/index.js @@ -0,0 +1,7 @@ +export default function () { + return { + manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("dynamicImport"); + } + }; +} diff --git a/packages/babel-plugin-syntax-flow/package.json b/packages/babel-plugin-syntax-flow/package.json index b8cd2de4b62c..922c79791a4a 100644 --- a/packages/babel-plugin-syntax-flow/package.json +++ b/packages/babel-plugin-syntax-flow/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-syntax-flow", "version": "6.13.0", - "description": "", + "description": "Allow parsing of the flow syntax", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-flow", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-syntax-jsx/package.json b/packages/babel-plugin-syntax-jsx/package.json index 4a9939851360..498310bea145 100644 --- a/packages/babel-plugin-syntax-jsx/package.json +++ b/packages/babel-plugin-syntax-jsx/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-syntax-jsx", "version": "6.13.0", - "description": "", + "description": "Allow parsing of jsx", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-jsx", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/class-method/expected.js b/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/class-method/expected.js index a774b790eb38..4d300b50dcdf 100644 --- a/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/class-method/expected.js +++ b/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/class-method/expected.js @@ -1,5 +1,5 @@ class C { - *g() { + g() { var _this = this; return babelHelpers.asyncGenerator.wrap(function* () { diff --git a/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/object-method/expected.js b/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/object-method/expected.js index e4fefacc6c50..c374fe93f4b3 100644 --- a/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/object-method/expected.js +++ b/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/object-method/expected.js @@ -1,5 +1,5 @@ ({ - *g() { + g() { var _this = this; return babelHelpers.asyncGenerator.wrap(function* () { diff --git a/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/static-method/expected.js b/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/static-method/expected.js index 01bbe9574235..751788620620 100644 --- a/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/static-method/expected.js +++ b/packages/babel-plugin-transform-async-generator-functions/test/fixtures/async-generators/static-method/expected.js @@ -1,5 +1,5 @@ class C { - static *g() { + static g() { var _this = this; return babelHelpers.asyncGenerator.wrap(function* () { diff --git a/packages/babel-plugin-transform-class-constructor-call/README.md b/packages/babel-plugin-transform-class-constructor-call/README.md index 5a2667057671..b06dab710f73 100644 --- a/packages/babel-plugin-transform-class-constructor-call/README.md +++ b/packages/babel-plugin-transform-class-constructor-call/README.md @@ -1,4 +1,4 @@ -# babel-plugin-transform-class-constructor-call +# babel-plugin-transform-class-constructor-call (deprecated) ## Installation diff --git a/packages/babel-plugin-transform-class-constructor-call/package.json b/packages/babel-plugin-transform-class-constructor-call/package.json index ba4809c670f4..9debb69a1dc3 100644 --- a/packages/babel-plugin-transform-class-constructor-call/package.json +++ b/packages/babel-plugin-transform-class-constructor-call/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-transform-class-constructor-call", "version": "6.8.0", - "description": "", + "description": "This plugin allows Babel to transform class constructors (deprecated)", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-class-constructor-call", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-transform-class-properties/package.json b/packages/babel-plugin-transform-class-properties/package.json index a6c4c753ad39..f73a12df8e8a 100644 --- a/packages/babel-plugin-transform-class-properties/package.json +++ b/packages/babel-plugin-transform-class-properties/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-transform-class-properties", "version": "6.16.0", - "description": "", + "description": "This plugin transforms static class properties as well as properties declared with the property initializer syntax", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-class-properties", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-transform-es2015-destructuring/src/index.js b/packages/babel-plugin-transform-es2015-destructuring/src/index.js index 0a80489ac9a1..cad6e15b93ee 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/src/index.js +++ b/packages/babel-plugin-transform-es2015-destructuring/src/index.js @@ -492,7 +492,21 @@ export default function ({ types: t }) { } } - path.replaceWithMultiple(nodes); + const nodesOut = []; + for (const node of nodes) { + const tail = nodesOut[nodesOut.length - 1]; + if (tail && t.isVariableDeclaration(tail) && t.isVariableDeclaration(node) && tail.kind === node.kind) { + tail.declarations.push(...node.declarations); + } else { + nodesOut.push(node); + } + } + + if (nodesOut.length === 1) { + path.replaceWith(nodesOut[0]); + } else { + path.replaceWithMultiple(nodesOut); + } } } }; diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/array-unpack-optimisation/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/array-unpack-optimisation/expected.js index e26edabdaf23..32816cdc73c4 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/array-unpack-optimisation/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/array-unpack-optimisation/expected.js @@ -1,36 +1,36 @@ -var a = 1; -var b = 2; -var a = 1; -var b = 2; -var a = 1; -var b = 2; -var c = [3, 4]; -var a = 1; -var b = 2; -var c = [3, 4]; -var _ref = [1, 2, 3]; -var a = _ref[0]; -var b = _ref[1]; -var _ref2 = [1, 2, 3]; -var a = _ref2[0]; -var b = _ref2[1]; -var _ref3 = [a, b]; -var a = _ref3[0]; -var b = _ref3[1]; +var a = 1, + b = 2; +var a = 1, + b = 2; +var a = 1, + b = 2, + c = [3, 4]; +var a = 1, + b = 2, + c = [3, 4]; +var _ref = [1, 2, 3], + a = _ref[0], + b = _ref[1]; +var _ref2 = [1, 2, 3], + a = _ref2[0], + b = _ref2[1]; +var _ref3 = [a, b], + a = _ref3[0], + b = _ref3[1]; var _ref4 = [a[1], a[0]]; a[0] = _ref4[0]; a[1] = _ref4[1]; -var _ref5 = [].concat(babelHelpers.toConsumableArray(foo), [bar]); +var _ref5 = [].concat(babelHelpers.toConsumableArray(foo), [bar]), + a = _ref5[0], + b = _ref5[1]; -var a = _ref5[0]; -var b = _ref5[1]; -var _ref6 = [foo(), bar]; -var a = _ref6[0]; -var b = _ref6[1]; -var _ref7 = [clazz.foo(), bar]; -var a = _ref7[0]; -var b = _ref7[1]; -var _ref8 = [clazz.foo, bar]; -var a = _ref8[0]; -var b = _ref8[1]; +var _ref6 = [foo(), bar], + a = _ref6[0], + b = _ref6[1]; +var _ref7 = [clazz.foo(), bar], + a = _ref7[0], + b = _ref7[1]; +var _ref8 = [clazz.foo, bar], + a = _ref8[0], + b = _ref8[1]; diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/array/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/array/expected.js index ca9b5413ef6e..74bd2ba3b448 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/array/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/array/expected.js @@ -1,7 +1,7 @@ -var a = "hello"; -var _ref = [", ", "junk"]; -var b = _ref[0]; -var c = "world"; +var a = "hello", + _ref = [", ", "junk"], + b = _ref[0], + c = "world"; a = "hello"; var _ref2 = [", ", "junk"]; b = _ref2[0]; diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/empty/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/empty/expected.js index f075fa100002..006976fc0e96 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/empty/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/empty/expected.js @@ -1,11 +1,7 @@ -var _ref = ["foo", "hello", [", ", "junk"], ["world"]]; -var a = _ref[1]; - -var _ref$ = babelHelpers.slicedToArray(_ref[2], 1); - -var b = _ref$[0]; - -var _ref$2 = babelHelpers.slicedToArray(_ref[3], 1); - -var c = _ref$2[0]; -var d = _ref[4]; +var _ref = ["foo", "hello", [", ", "junk"], ["world"]], + a = _ref[1], + _ref$ = babelHelpers.slicedToArray(_ref[2], 1), + b = _ref$[0], + _ref$2 = babelHelpers.slicedToArray(_ref[3], 1), + c = _ref$2[0], + d = _ref[4]; diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/es7-object-rest/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/es7-object-rest/expected.js index 935f76c0e018..7fa15501b22d 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/es7-object-rest/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/es7-object-rest/expected.js @@ -1,11 +1,11 @@ var z = {}; var x = babelHelpers.objectWithoutProperties(z, []); -var x = z.x; -var y = babelHelpers.objectWithoutProperties(z, ["x"]); -var x = z[x]; -var y = babelHelpers.objectWithoutProperties(z, [x]); +var x = z.x, + y = babelHelpers.objectWithoutProperties(z, ["x"]); +var x = z[x], + y = babelHelpers.objectWithoutProperties(z, [x]); (function (_ref) { - var x = _ref.x; - var y = babelHelpers.objectWithoutProperties(_ref, ["x"]); + var x = _ref.x, + y = babelHelpers.objectWithoutProperties(_ref, ["x"]); }); diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/export-variable/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/export-variable/expected.js index 01bd34a21536..54ea198599df 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/export-variable/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/export-variable/expected.js @@ -1,6 +1,6 @@ var _ref = {}; -var a = _ref.a; -var b = _ref.b; +var a = _ref.a, + b = _ref.b; var _ref$c = _ref.c; var d = _ref$c.d; var _ref$c$e$f = _ref$c.e.f; diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/issue-3081/actual.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/issue-3081/actual.js new file mode 100644 index 000000000000..bb96a2b37bb4 --- /dev/null +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/issue-3081/actual.js @@ -0,0 +1,4 @@ +let list = [1, 2, 3, 4]; +for (let i = 0, { length } = list; i < length; i++) { + list[i]; +} diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/issue-3081/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/issue-3081/expected.js new file mode 100644 index 000000000000..849668b3e1be --- /dev/null +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/issue-3081/expected.js @@ -0,0 +1,4 @@ +var list = [1, 2, 3, 4]; +for (var i = 0, length = list.length; i < length; i++) { + list[i]; +} diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/known-array/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/known-array/expected.js index 34c0ca8df510..83f1e945219a 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/known-array/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/known-array/expected.js @@ -1,3 +1,3 @@ var z = []; -var x = z[0]; -var y = z.slice(1); +var x = z[0], + y = z.slice(1); diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/mixed/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/mixed/expected.js index dfb38be734c1..724eb30084e0 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/mixed/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/mixed/expected.js @@ -1,11 +1,8 @@ var rect = {}; -var _rect$topLeft = babelHelpers.slicedToArray(rect.topLeft, 2); - -var x1 = _rect$topLeft[0]; -var y1 = _rect$topLeft[1]; - -var _rect$bottomRight = babelHelpers.slicedToArray(rect.bottomRight, 2); - -var x2 = _rect$bottomRight[0]; -var y2 = _rect$bottomRight[1]; +var _rect$topLeft = babelHelpers.slicedToArray(rect.topLeft, 2), + x1 = _rect$topLeft[0], + y1 = _rect$topLeft[1], + _rect$bottomRight = babelHelpers.slicedToArray(rect.bottomRight, 2), + x2 = _rect$bottomRight[0], + y2 = _rect$bottomRight[1]; diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/multiple/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/multiple/expected.js index b77339c9e8f6..2d16bfa7ae00 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/multiple/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/multiple/expected.js @@ -1,4 +1,4 @@ var coords = [1, 2]; -var x = coords.x; -var y = coords.y; -var foo = "bar"; +var x = coords.x, + y = coords.y, + foo = "bar"; diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/object-advanced/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/object-advanced/expected.js index 8086ab92eef0..188ae7e610f5 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/object-advanced/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/object-advanced/expected.js @@ -1,10 +1,10 @@ var rect = {}; -var _rect$topLeft = rect.topLeft; -var x1 = _rect$topLeft.x; -var y1 = _rect$topLeft.y; -var _rect$bottomRight = rect.bottomRight; -var x2 = _rect$bottomRight.x; -var y2 = _rect$bottomRight.y; -var _ref = [0, 1, 2, 3, 4, 5, 6]; -var foo = _ref[3]; -var bar = _ref[5]; +var _rect$topLeft = rect.topLeft, + x1 = _rect$topLeft.x, + y1 = _rect$topLeft.y, + _rect$bottomRight = rect.bottomRight, + x2 = _rect$bottomRight.x, + y2 = _rect$bottomRight.y; +var _ref = [0, 1, 2, 3, 4, 5, 6], + foo = _ref[3], + bar = _ref[5]; diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/object-basic/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/object-basic/expected.js index 24833dda4ca9..08012b6cccf7 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/object-basic/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/object-basic/expected.js @@ -1,3 +1,3 @@ var coords = [1, 2]; -var x = coords.x; -var y = coords.y; +var x = coords.x, + y = coords.y; diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/parameters/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/parameters/expected.js index bfd42de2b8f4..9ac248f802f6 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/parameters/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/parameters/expected.js @@ -1,17 +1,17 @@ function somethingAdvanced(_ref, p2, p3) { var _ref$topLeft = _ref.topLeft; _ref$topLeft = _ref$topLeft === undefined ? {} : _ref$topLeft; - var x1 = _ref$topLeft.x; - var y1 = _ref$topLeft.y; - var _ref$bottomRight = _ref.bottomRight; + var x1 = _ref$topLeft.x, + y1 = _ref$topLeft.y, + _ref$bottomRight = _ref.bottomRight; _ref$bottomRight = _ref$bottomRight === undefined ? {} : _ref$bottomRight; - var x2 = _ref$bottomRight.x; - var y2 = _ref$bottomRight.y; + var x2 = _ref$bottomRight.x, + y2 = _ref$bottomRight.y; } function unpackObject(_ref2) { - var title = _ref2.title; - var author = _ref2.author; + var title = _ref2.title, + author = _ref2.author; return title + " " + author; } @@ -19,17 +19,15 @@ function unpackObject(_ref2) { console.log(unpackObject({ title: "title", author: "author" })); var unpackArray = function (_ref3, _ref4) { - var _ref6 = babelHelpers.slicedToArray(_ref3, 3); - - var a = _ref6[0]; - var b = _ref6[1]; - var c = _ref6[2]; - - var _ref5 = babelHelpers.slicedToArray(_ref4, 3); - - var x = _ref5[0]; - var y = _ref5[1]; - var z = _ref5[2]; + var _ref6 = babelHelpers.slicedToArray(_ref3, 3), + a = _ref6[0], + b = _ref6[1], + c = _ref6[2]; + + var _ref5 = babelHelpers.slicedToArray(_ref4, 3), + x = _ref5[0], + y = _ref5[1], + z = _ref5[2]; return a + b + c; }; diff --git a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/spread/expected.js b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/spread/expected.js index 798f3a407a93..0b25cb693e59 100644 --- a/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/spread/expected.js +++ b/packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/spread/expected.js @@ -1,10 +1,8 @@ function isSorted(_ref) { - var _ref2 = babelHelpers.toArray(_ref); - - var x = _ref2[0]; - var y = _ref2[1]; - - var wow = _ref2.slice(2); + var _ref2 = babelHelpers.toArray(_ref), + x = _ref2[0], + y = _ref2[1], + wow = _ref2.slice(2); if (!zs.length) return true; if (y > x) return isSorted(zs); diff --git a/packages/babel-plugin-transform-es2015-for-of/src/index.js b/packages/babel-plugin-transform-es2015-for-of/src/index.js index bac099073e02..ca5ab6c09084 100644 --- a/packages/babel-plugin-transform-es2015-for-of/src/index.js +++ b/packages/babel-plugin-transform-es2015-for-of/src/index.js @@ -93,7 +93,11 @@ export default function ({ messages, template, types: t }) { visitor: { ForOfStatement(path, state) { if (path.get("right").isArrayExpression()) { - return path.replaceWithMultiple(_ForOfStatementArray.call(this, path, state)); + if (path.parentPath.isLabeledStatement()) { + return path.parentPath.replaceWithMultiple(_ForOfStatementArray(path)); + } else { + return path.replaceWithMultiple(_ForOfStatementArray(path)); + } } let callback = spec; diff --git a/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-block-label-3858/actual.js b/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-block-label-3858/actual.js new file mode 100644 index 000000000000..df89379c41f5 --- /dev/null +++ b/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-block-label-3858/actual.js @@ -0,0 +1,5 @@ +if ( true ) { + loop: for (let ch of []) { + } +} + diff --git a/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-block-label-3858/expected.js b/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-block-label-3858/expected.js new file mode 100644 index 000000000000..79a8edf0bce7 --- /dev/null +++ b/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-block-label-3858/expected.js @@ -0,0 +1,7 @@ +if (true) { + var _arr = []; + + loop: for (var _i = 0; _i < _arr.length; _i++) { + let ch = _arr[_i]; + } +} diff --git a/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-label-3858/actual.js b/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-label-3858/actual.js new file mode 100644 index 000000000000..356ae3a45c08 --- /dev/null +++ b/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-label-3858/actual.js @@ -0,0 +1,4 @@ +if ( true ) + loop: for (let ch of []) { + } + diff --git a/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-label-3858/expected.js b/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-label-3858/expected.js new file mode 100644 index 000000000000..79a8edf0bce7 --- /dev/null +++ b/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/if-label-3858/expected.js @@ -0,0 +1,7 @@ +if (true) { + var _arr = []; + + loop: for (var _i = 0; _i < _arr.length; _i++) { + let ch = _arr[_i]; + } +} diff --git a/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/options.json b/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/options.json new file mode 100644 index 000000000000..dd11655f5519 --- /dev/null +++ b/packages/babel-plugin-transform-es2015-for-of/test/fixtures/regression/options.json @@ -0,0 +1,3 @@ +{ + "plugins": ["transform-es2015-for-of"] +} diff --git a/packages/babel-plugin-transform-es2015-instanceof/package.json b/packages/babel-plugin-transform-es2015-instanceof/package.json index 7fe0c59e94d1..3152e9786e1b 100644 --- a/packages/babel-plugin-transform-es2015-instanceof/package.json +++ b/packages/babel-plugin-transform-es2015-instanceof/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-transform-es2015-instanceof", "version": "6.8.0", - "description": "", + "description": "This plugin transforms all the ES2015 'instanceof' methods", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-es2015-instanceof", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-transform-es2015-modules-amd/package.json b/packages/babel-plugin-transform-es2015-modules-amd/package.json index 4ac8fbd31111..6f734747297a 100644 --- a/packages/babel-plugin-transform-es2015-modules-amd/package.json +++ b/packages/babel-plugin-transform-es2015-modules-amd/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-transform-es2015-modules-amd", "version": "6.8.0", - "description": "", + "description": "This plugin transforms ES2015 modules to AMD", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-es2015-modules-amd", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-transform-es2015-modules-commonjs/package.json b/packages/babel-plugin-transform-es2015-modules-commonjs/package.json index bbe7a5f9dd6b..7935b60df8a3 100644 --- a/packages/babel-plugin-transform-es2015-modules-commonjs/package.json +++ b/packages/babel-plugin-transform-es2015-modules-commonjs/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-transform-es2015-modules-commonjs", "version": "6.16.0", - "description": "", + "description": "This plugin transforms ES2015 modules to CommonJS", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-es2015-modules-commonjs", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-transform-es2015-modules-commonjs/test/esmodule-flag.js b/packages/babel-plugin-transform-es2015-modules-commonjs/test/esmodule-flag.js index 465936d67a2b..beee1e9cd3ee 100644 --- a/packages/babel-plugin-transform-es2015-modules-commonjs/test/esmodule-flag.js +++ b/packages/babel-plugin-transform-es2015-modules-commonjs/test/esmodule-flag.js @@ -1,14 +1,14 @@ -var assert = require("assert"); -var babel = require("babel-core"); -var vm = require("vm"); +let assert = require("assert"); +let babel = require("babel-core"); +let vm = require("vm"); test("Re-export doesn't overwrite __esModule flag", function () { - var code = 'export * from "./dep";'; - var depStub = { + let code = "export * from \"./dep\";"; + let depStub = { __esModule: false, }; - var context = { + let context = { module: { exports: {} }, diff --git a/packages/babel-plugin-transform-es2015-modules-commonjs/test/fixtures/regression/T7199/expected.js b/packages/babel-plugin-transform-es2015-modules-commonjs/test/fixtures/regression/T7199/expected.js index 04d5367ebdad..3c4355854367 100644 --- a/packages/babel-plugin-transform-es2015-modules-commonjs/test/fixtures/regression/T7199/expected.js +++ b/packages/babel-plugin-transform-es2015-modules-commonjs/test/fixtures/regression/T7199/expected.js @@ -8,8 +8,7 @@ var _foo2 = _interopRequireDefault(_foo); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } -var _bar = bar; - -var _bar2 = _slicedToArray(_bar, 1); +var _bar = bar, + _bar2 = _slicedToArray(_bar, 1); const x = _bar2[0]; diff --git a/packages/babel-plugin-transform-es2015-modules-systemjs/package.json b/packages/babel-plugin-transform-es2015-modules-systemjs/package.json index 401d13ba6c85..e07287da731a 100644 --- a/packages/babel-plugin-transform-es2015-modules-systemjs/package.json +++ b/packages/babel-plugin-transform-es2015-modules-systemjs/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-transform-es2015-modules-systemjs", "version": "6.14.0", - "description": "", + "description": "This plugin transforms ES2015 modules to SystemJS", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-es2015-modules-systemjs", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-transform-es2015-modules-systemjs/src/index.js b/packages/babel-plugin-transform-es2015-modules-systemjs/src/index.js index 5b1619d245b2..ac8a8e2889d6 100644 --- a/packages/babel-plugin-transform-es2015-modules-systemjs/src/index.js +++ b/packages/babel-plugin-transform-es2015-modules-systemjs/src/index.js @@ -174,7 +174,7 @@ export default function ({ types: t }) { beforeBody.push(buildExportCall(name, node.id)); removedPaths.push(path); } else { - bindingIdentifiers = { [name]: node.id }; + bindingIdentifiers = { [name]: node.id }; } } else { bindingIdentifiers = declar.getBindingIdentifiers(); diff --git a/packages/babel-plugin-transform-es2015-modules-umd/package.json b/packages/babel-plugin-transform-es2015-modules-umd/package.json index 9b2fc59880d5..38c5cf3a1ae6 100644 --- a/packages/babel-plugin-transform-es2015-modules-umd/package.json +++ b/packages/babel-plugin-transform-es2015-modules-umd/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-transform-es2015-modules-umd", "version": "6.12.0", - "description": "", + "description": "This plugin transforms ES2015 modules to UMD", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-es2015-modules-umd", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-transform-es2015-parameters/src/rest.js b/packages/babel-plugin-transform-es2015-parameters/src/rest.js index e1bd77594959..70b3666770f1 100644 --- a/packages/babel-plugin-transform-es2015-parameters/src/rest.js +++ b/packages/babel-plugin-transform-es2015-parameters/src/rest.js @@ -161,6 +161,9 @@ function optimiseIndexGetter(path, argsId, offset) { if (t.isNumericLiteral(path.parent.property)) { index = t.numericLiteral(path.parent.property.value + offset); + } else if (offset === 0) { + // Avoid unnecessary '+ 0' + index = path.parent.property; } else { index = t.binaryExpression("+", path.parent.property, t.numericLiteral(offset)); } diff --git a/packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/destructuring-rest/expected.js b/packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/destructuring-rest/expected.js index 5350b8fade93..13f1b457d769 100644 --- a/packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/destructuring-rest/expected.js +++ b/packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/destructuring-rest/expected.js @@ -2,12 +2,12 @@ function t() { var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "default"; var _ref = arguments[1]; - var a = _ref.a; - var b = _ref.b; + var a = _ref.a, + b = _ref.b; for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } console.log(x, a, b, args); -} \ No newline at end of file +} diff --git a/packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/regression-4348/expected.js b/packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/regression-4348/expected.js index 2cee31ca38cf..72353b43e329 100644 --- a/packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/regression-4348/expected.js +++ b/packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/regression-4348/expected.js @@ -2,5 +2,5 @@ function first() { var _ref; var index = 0; - return _ref = index++ + 0, arguments.length <= _ref ? undefined : arguments[_ref]; + return _ref = index++, arguments.length <= _ref ? undefined : arguments[_ref]; } diff --git a/packages/babel-plugin-transform-es2015-typeof-symbol/package.json b/packages/babel-plugin-transform-es2015-typeof-symbol/package.json index 47da929b0ee9..626ac7d3714c 100644 --- a/packages/babel-plugin-transform-es2015-typeof-symbol/package.json +++ b/packages/babel-plugin-transform-es2015-typeof-symbol/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-transform-es2015-typeof-symbol", "version": "6.8.0", - "description": "", + "description": "This transformer wraps all typeof expressions with a method that replicates native behaviour. (ie. returning “symbol” for symbols)", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-es2015-typeof-symbol", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-plugin-transform-flow-strip-types/src/index.js b/packages/babel-plugin-transform-flow-strip-types/src/index.js index 80b52476d750..24e9bf8d10c0 100644 --- a/packages/babel-plugin-transform-flow-strip-types/src/index.js +++ b/packages/babel-plugin-transform-flow-strip-types/src/index.js @@ -22,6 +22,7 @@ export default function ({ types: t }) { }, ClassProperty(path) { + path.node.variance = null; path.node.typeAnnotation = null; if (!path.node.value) path.remove(); }, diff --git a/packages/babel-plugin-transform-flow-strip-types/test/fixtures/regression/property-variance-with-class-properties/actual.js b/packages/babel-plugin-transform-flow-strip-types/test/fixtures/regression/property-variance-with-class-properties/actual.js new file mode 100644 index 000000000000..8b4161346375 --- /dev/null +++ b/packages/babel-plugin-transform-flow-strip-types/test/fixtures/regression/property-variance-with-class-properties/actual.js @@ -0,0 +1,3 @@ +class C { + +p: T = e; +} diff --git a/packages/babel-plugin-transform-flow-strip-types/test/fixtures/regression/property-variance-with-class-properties/expected.js b/packages/babel-plugin-transform-flow-strip-types/test/fixtures/regression/property-variance-with-class-properties/expected.js new file mode 100644 index 000000000000..da28fb47901f --- /dev/null +++ b/packages/babel-plugin-transform-flow-strip-types/test/fixtures/regression/property-variance-with-class-properties/expected.js @@ -0,0 +1,3 @@ +class C { + p = e; +} diff --git a/packages/babel-plugin-transform-flow-strip-types/test/fixtures/regression/property-variance-with-class-properties/options.json b/packages/babel-plugin-transform-flow-strip-types/test/fixtures/regression/property-variance-with-class-properties/options.json new file mode 100644 index 000000000000..56245d91c6c1 --- /dev/null +++ b/packages/babel-plugin-transform-flow-strip-types/test/fixtures/regression/property-variance-with-class-properties/options.json @@ -0,0 +1,3 @@ +{ + "plugins": ["transform-flow-strip-types", "syntax-class-properties"] +} diff --git a/packages/babel-plugin-transform-flow-strip-types/test/fixtures/strip-types/def-site-variance/actual.js b/packages/babel-plugin-transform-flow-strip-types/test/fixtures/strip-types/def-site-variance/actual.js index f046505722fe..a97695f41813 100644 --- a/packages/babel-plugin-transform-flow-strip-types/test/fixtures/strip-types/def-site-variance/actual.js +++ b/packages/babel-plugin-transform-flow-strip-types/test/fixtures/strip-types/def-site-variance/actual.js @@ -1,3 +1,17 @@ -class C<+T, -U> {} +class C1<+T, -U> {} function f<+T, -U>() {} -type T<+T, -U> = {}; +type T<+T, -U> = {} +type T = { +p: T } +type T = { -p: T } +type T = { +[k:K]: V } +type T = { -[k:K]: V } +interface I { +p: T } +interface I { -p: T } +interface I { +[k:K]: V } +interface I { -[k:K]: V } +declare class I { +p: T } +declare class I { -p: T } +declare class I { +[k:K]: V } +declare class I { -[k:K]: V } +class C2 { +p: T } +class C3 { -p: T } diff --git a/packages/babel-plugin-transform-flow-strip-types/test/fixtures/strip-types/def-site-variance/expected.js b/packages/babel-plugin-transform-flow-strip-types/test/fixtures/strip-types/def-site-variance/expected.js index 9eb99a782f8a..dce129ae1ec1 100644 --- a/packages/babel-plugin-transform-flow-strip-types/test/fixtures/strip-types/def-site-variance/expected.js +++ b/packages/babel-plugin-transform-flow-strip-types/test/fixtures/strip-types/def-site-variance/expected.js @@ -1,2 +1,5 @@ -class C {} +class C1 {} function f() {} + +class C2 {} +class C3 {} diff --git a/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment-invalid-option/actual.js b/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment-invalid-option/actual.js new file mode 100644 index 000000000000..4caacb6aa17d --- /dev/null +++ b/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment-invalid-option/actual.js @@ -0,0 +1 @@ +var div = diff --git a/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment-invalid-option/options.json b/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment-invalid-option/options.json new file mode 100644 index 000000000000..3baf37938e7d --- /dev/null +++ b/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment-invalid-option/options.json @@ -0,0 +1,4 @@ +{ + "plugins": [["transform-react-jsx", { "useBuiltIns": "invalidOption" }]], + "throws": "transform-react-jsx currently only accepts a boolean option for useBuiltIns (defaults to false)" +} diff --git a/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment/actual.js b/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment/actual.js new file mode 100644 index 000000000000..4caacb6aa17d --- /dev/null +++ b/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment/actual.js @@ -0,0 +1 @@ +var div = diff --git a/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment/expected.js b/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment/expected.js new file mode 100644 index 000000000000..ecbc7d94b162 --- /dev/null +++ b/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/assignment/expected.js @@ -0,0 +1 @@ +var div = React.createElement(Component, Object.assign({}, props, { foo: "bar" })); diff --git a/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/options.json b/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/options.json new file mode 100644 index 000000000000..2404117dccce --- /dev/null +++ b/packages/babel-plugin-transform-react-jsx/test/fixtures/useBuiltIns/options.json @@ -0,0 +1,3 @@ +{ + "plugins": [["transform-react-jsx", { "useBuiltIns": true }]] +} diff --git a/packages/babel-plugin-transform-strict-mode/package.json b/packages/babel-plugin-transform-strict-mode/package.json index 8557c3161726..ae8b97bd9bab 100644 --- a/packages/babel-plugin-transform-strict-mode/package.json +++ b/packages/babel-plugin-transform-strict-mode/package.json @@ -1,7 +1,7 @@ { "name": "babel-plugin-transform-strict-mode", "version": "6.11.3", - "description": "TODO", + "description": "This plugin places a 'use strict'; directive at the top of all files to enable strict mode", "repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-strict-mode", "license": "MIT", "main": "lib/index.js", diff --git a/packages/babel-preset-es2015/src/index.js b/packages/babel-preset-es2015/src/index.js index 67b055982ae7..57d96082d120 100644 --- a/packages/babel-preset-es2015/src/index.js +++ b/packages/babel-preset-es2015/src/index.js @@ -52,7 +52,7 @@ function preset(context, opts = {}) { // be DRY const optsLoose = { loose }; - + return { plugins: [ [transformES2015TemplateLiterals, { loose, spec }], diff --git a/packages/babel-preset-es2015/test/index.js b/packages/babel-preset-es2015/test/index.js index f4b8b084f9dc..7653dbb6f97e 100644 --- a/packages/babel-preset-es2015/test/index.js +++ b/packages/babel-preset-es2015/test/index.js @@ -1,40 +1,39 @@ -var es2015 = require("../lib"); -var assert = require("assert"); -var expect = require("chai").expect; +let es2015 = require("../lib"); +let expect = require("chai").expect; -suite("es2015 preset", function () { - test("exposes an object", function () { +describe("es2015 preset", function () { + it("exposes an object", function () { // Changing this will break compatibility with babel-core < 6.13.x. expect(typeof es2015).to.equal("object"); }); - test("exposes a separate list of plugins", function () { + it("exposes a separate list of plugins", function () { expect(Array.isArray(es2015.plugins)).to.equal(true); }); - test("doesn't throw with no options passed", function () { + it("doesn't throw with no options passed", function () { expect(function () { es2015.buildPreset(null); }).not.to.throw(); - }) + }); - suite("options", function () { - suite("loose", function () { - test("throws on non-boolean value", function () { + describe("options", function () { + describe("loose", function () { + it("throws on non-boolean value", function () { expect(function () { es2015.buildPreset(null, { loose: 1}); }).to.throw(/must be a boolean/); }); }); - suite("modules", function () { - test("doesn't throw when passing one false", function () { + describe("modules", function () { + it("doesn't throw when passing one false", function () { expect(function () { es2015.buildPreset(null, { modules: false }); }).not.to.throw(); }); - test("doesn't throw when passing one of: 'commonjs', 'amd', 'umd', 'systemjs", function () { + it("doesn't throw when passing one of: 'commonjs', 'amd', 'umd', 'systemjs", function () { expect(function () { es2015.buildPreset(null, { modules: "commonjs" }); }).not.to.throw(); diff --git a/packages/babel-preset-es2015/test/traceur.js b/packages/babel-preset-es2015/test/traceur.js index dd3fd5f70a71..a4bfd87c3f1a 100644 --- a/packages/babel-preset-es2015/test/traceur.js +++ b/packages/babel-preset-es2015/test/traceur.js @@ -1,5 +1,4 @@ -var fs = require("fs"); -var _ = require("lodash"); +let _ = require("lodash"); require("babel-helper-transform-fixture-test-runner")(__dirname + "/fixtures/traceur", "traceur", { ignoreSuites: [ diff --git a/packages/babel-preset-stage-2/package.json b/packages/babel-preset-stage-2/package.json index 625af40a7007..2540371b7d2a 100644 --- a/packages/babel-preset-stage-2/package.json +++ b/packages/babel-preset-stage-2/package.json @@ -10,6 +10,7 @@ "dependencies": { "babel-plugin-transform-class-properties": "^6.16.0", "babel-plugin-transform-decorators": "^6.13.0", + "babel-plugin-syntax-dynamic-import": "^6.13.0", "babel-preset-stage-3": "^6.17.0" } } diff --git a/packages/babel-preset-stage-2/src/index.js b/packages/babel-preset-stage-2/src/index.js index 9898fe8c4935..7e9e8a2864c7 100644 --- a/packages/babel-preset-stage-2/src/index.js +++ b/packages/babel-preset-stage-2/src/index.js @@ -2,12 +2,14 @@ import presetStage3 from "babel-preset-stage-3"; import transformClassProperties from "babel-plugin-transform-class-properties"; import transformDecorators from "babel-plugin-transform-decorators"; +import syntaxDynamicImport from "babel-plugin-syntax-dynamic-import"; export default { presets: [ presetStage3 ], plugins: [ + syntaxDynamicImport, transformClassProperties, transformDecorators ] diff --git a/packages/babel-register/package.json b/packages/babel-register/package.json index 6da8a1247131..d42f4bf9aa1f 100644 --- a/packages/babel-register/package.json +++ b/packages/babel-register/package.json @@ -11,10 +11,9 @@ "babel-core": "^6.16.0", "babel-runtime": "^6.11.6", "core-js": "^2.4.0", - "home-or-tmp": "^1.0.0", + "home-or-tmp": "^2.0.0", "lodash": "^4.2.0", "mkdirp": "^0.5.1", - "path-exists": "^1.0.0", "source-map-support": "^0.4.2" } } diff --git a/packages/babel-register/src/cache.js b/packages/babel-register/src/cache.js index 8c5177a00c3d..4b08e63ac753 100644 --- a/packages/babel-register/src/cache.js +++ b/packages/babel-register/src/cache.js @@ -2,7 +2,6 @@ import path from "path"; import fs from "fs"; import { sync as mkdirpSync } from "mkdirp"; import homeOrTmp from "home-or-tmp"; -import pathExists from "path-exists"; const FILENAME = process.env.BABEL_CACHE_PATH || path.join(homeOrTmp, ".babel.json"); let data = {}; @@ -37,7 +36,7 @@ export function load() { process.on("exit", save); process.nextTick(save); - if (!pathExists.sync(FILENAME)) return; + if (!fs.existsSync(FILENAME)) return; try { data = JSON.parse(fs.readFileSync(FILENAME)); diff --git a/packages/babel-template/test/index.js b/packages/babel-template/test/index.js index e8a95b640ea8..f64090e4a839 100644 --- a/packages/babel-template/test/index.js +++ b/packages/babel-template/test/index.js @@ -1,30 +1,30 @@ -var generator = require('../../babel-generator').default; -var template = require("../lib"); -var chai = require("chai"); +let generator = require("../../babel-generator").default; +let template = require("../lib"); +let chai = require("chai"); -var comments = "// Sum two numbers\nconst add = (a, b) => a + b;"; +let comments = "// Sum two numbers\nconst add = (a, b) => a + b;"; -suite("templating", function () { - test("import statement will cause parser to throw by default", function () { +describe("templating", function () { + it("import statement will cause parser to throw by default", function () { chai.expect(function () { template("import foo from 'foo'")({}); }).to.throw(); }); - test("import statements are allowed with sourceType: module", function () { + it("import statements are allowed with sourceType: module", function () { chai.expect(function () { - template("import foo from 'foo'", {sourceType: 'module'})({}); + template("import foo from 'foo'", {sourceType: "module"})({}); }).not.to.throw(); }); - test("should strip comments by default", function () { - var code = "const add = (a, b) => a + b;" - var output = template(comments)(); + it("should strip comments by default", function () { + let code = "const add = (a, b) => a + b;"; + let output = template(comments)(); chai.expect(generator(output).code).to.be.equal(code); }); - test("should preserve comments with a flag", function () { - var output = template(comments, {preserveComments: true})(); + it("should preserve comments with a flag", function () { + let output = template(comments, {preserveComments: true})(); chai.expect(generator(output).code).to.be.equal(comments); }); }); diff --git a/packages/babel-traverse/package.json b/packages/babel-traverse/package.json index 2b4902e483f1..fd2bf35e9cb5 100644 --- a/packages/babel-traverse/package.json +++ b/packages/babel-traverse/package.json @@ -1,7 +1,7 @@ { "name": "babel-traverse", "version": "6.16.0", - "description": "", + "description": "The Babel Traverse module maintains the overall tree state, and is responsible for replacing, removing, and adding nodes", "author": "Sebastian McKenzie ", "homepage": "https://babeljs.io/", "license": "MIT", diff --git a/packages/babel-traverse/src/path/evaluation.js b/packages/babel-traverse/src/path/evaluation.js index 6dcc3f747f7e..ef478103b1fb 100644 --- a/packages/babel-traverse/src/path/evaluation.js +++ b/packages/babel-traverse/src/path/evaluation.js @@ -231,7 +231,34 @@ export function evaluate(): { confident: boolean; value: any } { } if (path.isObjectExpression()) { - // todo + let obj = {}; + let props: Array = path.get("properties"); + for (let prop of props) { + if (prop.isObjectMethod() || prop.isSpreadProperty()) { + return deopt(prop); + } + const keyPath = prop.get("key"); + let key = keyPath; + if (prop.node.computed) { + key = key.evaluate(); + if (!key.confident) { + return deopt(keyPath); + } + key = key.value; + } else if (key.isIdentifier()) { + key = key.node.name; + } else { + key = key.node.value; + } + const valuePath = prop.get("value"); + let value = valuePath.evaluate(); + if (!value.confident) { + return deopt(valuePath); + } + value = value.value; + obj[key] = value; + } + return obj; } if (path.isLogicalExpression()) { diff --git a/packages/babel-traverse/src/path/inference/index.js b/packages/babel-traverse/src/path/inference/index.js index d6b9c878f337..55a52911a655 100644 --- a/packages/babel-traverse/src/path/inference/index.js +++ b/packages/babel-traverse/src/path/inference/index.js @@ -73,6 +73,8 @@ function _isBaseType(baseName: string, type?, soft?): boolean { return t.isAnyTypeAnnotation(type); } else if (baseName === "mixed") { return t.isMixedTypeAnnotation(type); + } else if (baseName === "empty") { + return t.isEmptyTypeAnnotation(type); } else if (baseName === "void") { return t.isVoidTypeAnnotation(type); } else { diff --git a/packages/babel-traverse/src/path/inference/inferers.js b/packages/babel-traverse/src/path/inference/inferers.js index 7a2c86f7dab8..ec372f6825d7 100644 --- a/packages/babel-traverse/src/path/inference/inferers.js +++ b/packages/babel-traverse/src/path/inference/inferers.js @@ -137,7 +137,13 @@ function Func() { return t.genericTypeAnnotation(t.identifier("Function")); } -export { Func as Function, Func as Class }; +export { + Func as FunctionExpression, + Func as ArrowFunctionExpression, + Func as FunctionDeclaration, + Func as ClassExpression, + Func as ClassDeclaration +}; export function CallExpression() { return resolveCall(this.get("callee")); diff --git a/packages/babel-traverse/src/scope/index.js b/packages/babel-traverse/src/scope/index.js index 4a5022d46ab9..5c5395877291 100644 --- a/packages/babel-traverse/src/scope/index.js +++ b/packages/babel-traverse/src/scope/index.js @@ -161,6 +161,8 @@ export default class Scope { this.parentBlock = path.parent; this.block = path.node; this.path = path; + + this.labels = new Map(); } /** @@ -218,7 +220,7 @@ export default class Scope { do { uid = this._generateUid(name, i); i++; - } while (this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); + } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); let program = this.getProgramParent(); program.references[uid] = true; @@ -426,9 +428,21 @@ export default class Scope { return t.callExpression(file.addHelper(helperName), args); } + hasLabel(name: string) { + return !!this.getLabel(name); + } + + getLabel(name: string) { + return this.labels.get(name); + } + + registerLabel(path: NodePath) { + this.labels.set(path.node.label.name, path); + } + registerDeclaration(path: NodePath) { if (path.isLabeledStatement()) { - this.registerBinding("label", path); + this.registerLabel(path); } else if (path.isFunctionDeclaration()) { this.registerBinding("hoisted", path.get("id"), path); } else if (path.isVariableDeclaration()) { diff --git a/packages/babel-traverse/test/evaluation.js b/packages/babel-traverse/test/evaluation.js index 84db801024a9..97dc0c3df9dd 100644 --- a/packages/babel-traverse/test/evaluation.js +++ b/packages/babel-traverse/test/evaluation.js @@ -1,10 +1,10 @@ -var traverse = require("../lib").default; -var assert = require("assert"); -var parse = require("babylon").parse; +let traverse = require("../lib").default; +let assert = require("assert"); +let parse = require("babylon").parse; function getPath(code) { - var ast = parse(code); - var path; + let ast = parse(code); + let path; traverse(ast, { Program: function (_path) { path = _path; @@ -14,16 +14,16 @@ function getPath(code) { return path; } -suite("evaluation", function () { - suite("evaluateTruthy", function () { - test("it should work with null", function () { +describe("evaluation", function () { + describe("evaluateTruthy", function () { + it("it should work with null", function () { assert.strictEqual( getPath("false || a.length === 0;").get("body")[0].evaluateTruthy(), undefined ); }); - test("it should not mistake lack of confidence for falsy", function () { + it("it should not mistake lack of confidence for falsy", function () { assert.strictEqual( getPath("foo || 'bar'").get("body")[0].evaluate().value, undefined @@ -31,35 +31,35 @@ suite("evaluation", function () { }); }); - test("should bail out on recursive evaluation", function () { + it("should bail out on recursive evaluation", function () { assert.strictEqual( getPath("function fn(a) { var g = a ? 1 : 2, a = g * this.foo; }").get("body.0.body.body.0.declarations.1.init").evaluate().confident, false ); }); - test("should work with repeated, indeterminate identifiers", function () { + it("should work with repeated, indeterminate identifiers", function () { assert.strictEqual( getPath("var num = foo(); (num > 0 && num < 100);").get("body")[1].evaluateTruthy(), undefined ); }); - test("should work with repeated, determinate identifiers", function () { + it("should work with repeated, determinate identifiers", function () { assert.strictEqual( getPath("var num = 5; (num > 0 && num < 100);").get("body")[1].evaluateTruthy(), true ); }); - test("should deopt when var is redeclared in the same scope", function () { + it("should deopt when var is redeclared in the same scope", function () { assert.strictEqual( getPath("var x = 2; var y = x + 2; { var x = 3 }").get("body.1.declarations.0.init").evaluate().confident, false ); }); - test("it should not deopt vars in different scope", function () { + it("it should not deopt vars in different scope", function () { const input = "var a = 5; function x() { var a = 5; var b = a + 1; } var b = a + 2"; assert.strictEqual( getPath(input).get("body.1.body.body.1.declarations.0.init").evaluate().value, @@ -71,7 +71,7 @@ suite("evaluation", function () { ); }); - test("it should not deopt let/const inside blocks", function () { + it("it should not deopt let/const inside blocks", function () { assert.strictEqual( getPath("let x = 5; { let x = 1; } let y = x + 5").get("body.2.declarations.0.init").evaluate().value, 10 diff --git a/packages/babel-traverse/test/inference.js b/packages/babel-traverse/test/inference.js index a8e8adc3745a..5819cd1b06d0 100644 --- a/packages/babel-traverse/test/inference.js +++ b/packages/babel-traverse/test/inference.js @@ -1,10 +1,11 @@ -var traverse = require("../lib").default; -var assert = require("assert"); -var parse = require("babylon").parse; +import traverse from "../lib"; +import assert from "assert"; +import { parse } from "babylon"; +import * as t from "babel-types"; function getPath(code) { - var ast = parse(code); - var path; + const ast = parse(code, {plugins: ["flow", "asyncGenerators"]}); + let path; traverse(ast, { Program: function (_path) { path = _path; @@ -14,43 +15,163 @@ function getPath(code) { return path; } -suite("inference", function () { - suite("baseTypeStrictlyMatches", function () { - test("it should work with null", function () { - var path = getPath("var x = null; x === null").get("body")[1].get("expression"); - var left = path.get("left"); - var right = path.get("right"); - var strictMatch = left.baseTypeStrictlyMatches(right); +describe("inference", function () { + describe("baseTypeStrictlyMatches", function () { + it("it should work with null", function () { + const path = getPath("var x = null; x === null").get("body")[1].get("expression"); + const left = path.get("left"); + const right = path.get("right"); + const strictMatch = left.baseTypeStrictlyMatches(right); assert.ok(strictMatch, "null should be equal to null"); }); - test("it should work with numbers", function () { - var path = getPath("var x = 1; x === 2").get("body")[1].get("expression"); - var left = path.get("left"); - var right = path.get("right"); - var strictMatch = left.baseTypeStrictlyMatches(right); + it("it should work with numbers", function () { + const path = getPath("var x = 1; x === 2").get("body")[1].get("expression"); + const left = path.get("left"); + const right = path.get("right"); + const strictMatch = left.baseTypeStrictlyMatches(right); - assert.ok(strictMatch, "null should be equal to null"); + assert.ok(strictMatch, "number should be equal to number"); }); - test("it should bail when type changes", function () { - var path = getPath("var x = 1; if (foo) x = null;else x = 3; x === 2").get("body")[2].get("expression"); - var left = path.get("left"); - var right = path.get("right"); + it("it should bail when type changes", function () { + const path = getPath("var x = 1; if (foo) x = null;else x = 3; x === 2").get("body")[2].get("expression"); + const left = path.get("left"); + const right = path.get("right"); - var strictMatch = left.baseTypeStrictlyMatches(right); + const strictMatch = left.baseTypeStrictlyMatches(right); assert.ok(!strictMatch, "type might change in if statement"); }); - test("it should differentiate between null and undefined", function () { - var path = getPath("var x; x === null").get("body")[1].get("expression"); - var left = path.get("left"); - var right = path.get("right"); - var strictMatch = left.baseTypeStrictlyMatches(right); + it("it should differentiate between null and undefined", function () { + const path = getPath("var x; x === null").get("body")[1].get("expression"); + const left = path.get("left"); + const right = path.get("right"); + const strictMatch = left.baseTypeStrictlyMatches(right); assert.ok(!strictMatch, "null should not match undefined"); }); }); + describe("getTypeAnnotation", function () { + it("should infer from type cast", function () { + const path = getPath("(x: number)").get("body")[0].get("expression"); + assert.ok(t.isNumberTypeAnnotation(path.getTypeAnnotation()), "should be number"); + + }); + it("should infer string from template literal", function () { + const path = getPath("`hey`").get("body")[0].get("expression"); + assert.ok(t.isStringTypeAnnotation(path.getTypeAnnotation()), "should be string"); + }); + it("should infer number from +x", function () { + const path = getPath("+x").get("body")[0].get("expression"); + assert.ok(t.isNumberTypeAnnotation(path.getTypeAnnotation()), "should be number"); + }); + it("should infer T from new T", function () { + const path = getPath("new T").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "T", "should be T"); + }); + it("should infer number from ++x", function () { + const path = getPath("++x").get("body")[0].get("expression"); + assert.ok(t.isNumberTypeAnnotation(path.getTypeAnnotation()), "should be number"); + }); + it("should infer number from --x", function () { + const path = getPath("--x").get("body")[0].get("expression"); + assert.ok(t.isNumberTypeAnnotation(path.getTypeAnnotation()), "should be number"); + }); + it("should infer void from void x", function () { + const path = getPath("void x").get("body")[0].get("expression"); + assert.ok(t.isVoidTypeAnnotation(path.getTypeAnnotation()), "should be void"); + }); + it("should infer string from typeof x", function () { + const path = getPath("typeof x").get("body")[0].get("expression"); + assert.ok(t.isStringTypeAnnotation(path.getTypeAnnotation()), "should be string"); + }); + it("should infer boolean from !x", function () { + const path = getPath("!x").get("body")[0].get("expression"); + assert.ok(t.isBooleanTypeAnnotation(path.getTypeAnnotation()), "should be boolean"); + }); + it("should infer type of sequence expression", function () { + const path = getPath("a,1").get("body")[0].get("expression"); + assert.ok(t.isNumberTypeAnnotation(path.getTypeAnnotation()), "should be number"); + }); + it("should infer type of logical expression", function () { + const path = getPath("'a' && 1").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isUnionTypeAnnotation(type), "should be a union"); + assert.ok(t.isStringTypeAnnotation(type.types[0]), "first type in union should be string"); + assert.ok(t.isNumberTypeAnnotation(type.types[1]), "second type in union should be number"); + }); + it("should infer type of conditional expression", function () { + const path = getPath("q ? true : 0").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isUnionTypeAnnotation(type), "should be a union"); + assert.ok(t.isBooleanTypeAnnotation(type.types[0]), "first type in union should be boolean"); + assert.ok(t.isNumberTypeAnnotation(type.types[1]), "second type in union should be number"); + }); + it("should infer RegExp from RegExp literal", function () { + const path = getPath("/.+/").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "RegExp", "should be RegExp"); + }); + it("should infer Object from object expression", function () { + const path = getPath("({ a: 5 })").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "Object", "should be Object"); + }); + it("should infer Array from array expression", function () { + const path = getPath("[ 5 ]").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "Array", "should be Array"); + }); + it("should infer Function from function", function () { + const path = getPath("(function (): string {})").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "Function", "should be Function"); + }); + it("should infer call return type using function", function () { + const path = getPath("(function (): string {})()").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isStringTypeAnnotation(type), "should be string"); + }); + it("should infer call return type using async function", function () { + const path = getPath("(async function (): string {})()").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "Promise", "should be Promise"); + }); + it("should infer call return type using async generator function", function () { + const path = getPath("(async function * (): string {})()").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "AsyncIterator", "should be AsyncIterator"); + }); + it("should infer number from x/y", function () { + const path = getPath("x/y").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isNumberTypeAnnotation(type), "should be number"); + }); + it("should infer boolean from x instanceof y", function () { + const path = getPath("x instanceof y").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isBooleanTypeAnnotation(type), "should be boolean"); + }); + it("should infer number from 1 + 2", function () { + const path = getPath("1 + 2").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isNumberTypeAnnotation(type), "should be number"); + }); + it("should infer string|number from x + y", function () { + const path = getPath("x + y").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isUnionTypeAnnotation(type), "should be a union"); + assert.ok(t.isStringTypeAnnotation(type.types[0]), "first type in union should be string"); + assert.ok(t.isNumberTypeAnnotation(type.types[1]), "second type in union should be number"); + }); + it("should infer type of tagged template literal", function () { + const path = getPath("(function (): RegExp {}) `hey`").get("body")[0].get("expression"); + const type = path.getTypeAnnotation(); + assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "RegExp", "should be RegExp"); + }); + }); }); diff --git a/packages/babel-traverse/test/scope.js b/packages/babel-traverse/test/scope.js index c119d6f5acc4..332a3eabd9b9 100644 --- a/packages/babel-traverse/test/scope.js +++ b/packages/babel-traverse/test/scope.js @@ -1,10 +1,10 @@ -var traverse = require("../lib").default; -var assert = require("assert"); -var parse = require("babylon").parse; +let traverse = require("../lib").default; +let assert = require("assert"); +let parse = require("babylon").parse; function getPath(code) { - var ast = parse(code); - var path; + let ast = parse(code); + let path; traverse(ast, { Program: function (_path) { path = _path; @@ -14,29 +14,51 @@ function getPath(code) { return path; } -suite("scope", function () { - suite("binding paths", function () { - test("function declaration id", function () { +describe("scope", function () { + describe("binding paths", function () { + it("function declaration id", function () { assert.ok(getPath("function foo() {}").scope.getBinding("foo").path.type === "FunctionDeclaration"); }); - test("function expression id", function () { + it("function expression id", function () { assert.ok(getPath("(function foo() {})").get("body")[0].get("expression").scope.getBinding("foo").path.type === "FunctionExpression"); }); - test("function param", function () { + it("function param", function () { assert.ok(getPath("(function (foo) {})").get("body")[0].get("expression").scope.getBinding("foo").path.type === "Identifier"); }); - test("variable declaration", function () { + it("variable declaration", function () { assert.ok(getPath("var foo = null;").scope.getBinding("foo").path.type === "VariableDeclarator"); assert.ok(getPath("var { foo } = null;").scope.getBinding("foo").path.type === "VariableDeclarator"); assert.ok(getPath("var [ foo ] = null;").scope.getBinding("foo").path.type === "VariableDeclarator"); assert.ok(getPath("var { bar: [ foo ] } = null;").scope.getBinding("foo").path.type === "VariableDeclarator"); }); - test("purity", function () { + it("purity", function () { assert.ok(getPath("({ x: 1 })").get("body")[0].get("expression").isPure()); }); + + test("label", function () { + assert.strictEqual(getPath("foo: { }").scope.getBinding("foo"), undefined); + assert.strictEqual(getPath("foo: { }").scope.getLabel("foo").type, "LabeledStatement"); + assert.strictEqual(getPath("foo: { }").scope.getLabel("toString"), undefined); + + assert.strictEqual(getPath(` + foo: { } + `).scope.generateUid("foo"), "_foo"); + }); + + test("generateUid collision check with labels", function () { + assert.strictEqual(getPath(` + _foo: { } + `).scope.generateUid("foo"), "_foo2"); + + assert.strictEqual(getPath(` + _foo: { } + _foo1: { } + _foo2: { } + `).scope.generateUid("foo"), "_foo3"); + }); }); }); diff --git a/packages/babel-traverse/test/traverse.js b/packages/babel-traverse/test/traverse.js index 1e4f59b1f883..f8446a11aeb4 100644 --- a/packages/babel-traverse/test/traverse.js +++ b/packages/babel-traverse/test/traverse.js @@ -1,9 +1,9 @@ -var traverse = require("../lib").default; -var assert = require("assert"); -var _ = require("lodash"); +let traverse = require("../lib").default; +let assert = require("assert"); +let _ = require("lodash"); -suite("traverse", function () { - var ast = { +describe("traverse", function () { + let ast = { type: "Program", body: [ { @@ -50,14 +50,14 @@ suite("traverse", function () { ] }; - var body = ast.body; + let body = ast.body; - test("traverse replace", function () { - var replacement = { + it("traverse replace", function () { + let replacement = { type: "StringLiteral", value: "foo" }; - var ast2 = _.cloneDeep(ast); + let ast2 = _.cloneDeep(ast); traverse(ast2, { enter: function (path) { @@ -68,13 +68,13 @@ suite("traverse", function () { assert.equal(ast2.body[1].expression.left.object, replacement); }); - test("traverse", function () { - var expect = [ + it("traverse", function () { + let expect = [ body[0], body[0].declarations[0], body[0].declarations[0].id, body[0].declarations[0].init, body[1], body[1].expression, body[1].expression.left, body[1].expression.left.object, body[1].expression.left.property, body[1].expression.right ]; - var actual = []; + let actual = []; traverse(ast, { enter: function (path) { @@ -85,7 +85,7 @@ suite("traverse", function () { assert.deepEqual(actual, expect); }); - test("traverse falsy parent", function () { + it("traverse falsy parent", function () { traverse(null, { enter: function () { throw new Error("should not be ran"); @@ -93,13 +93,13 @@ suite("traverse", function () { }); }); - test("traverse blacklistTypes", function () { - var expect = [ + it("traverse blacklistTypes", function () { + let expect = [ body[0], body[0].declarations[0], body[0].declarations[0].id, body[0].declarations[0].init, body[1], body[1].expression, body[1].expression.right ]; - var actual = []; + let actual = []; traverse(ast, { blacklist: ["MemberExpression"], @@ -111,7 +111,7 @@ suite("traverse", function () { assert.deepEqual(actual, expect); }); - test("hasType", function () { + it("hasType", function () { assert.ok(traverse.hasType(ast, null, "ThisExpression")); assert.ok(!traverse.hasType(ast, null, "ThisExpression", ["AssignmentExpression"])); @@ -124,8 +124,8 @@ suite("traverse", function () { assert.ok(!traverse.hasType(ast, null, "ArrowFunctionExpression")); }); - test("clearCache", function () { - var paths = []; + it("clearCache", function () { + let paths = []; traverse(ast, { enter: function (path) { paths.push(path); @@ -134,7 +134,7 @@ suite("traverse", function () { traverse.clearCache(); - var paths2 = []; + let paths2 = []; traverse(ast, { enter: function (path) { paths2.push(path); diff --git a/packages/babel-types/README.md b/packages/babel-types/README.md index a8dc4f272805..884aae17d6ea 100644 --- a/packages/babel-types/README.md +++ b/packages/babel-types/README.md @@ -755,6 +755,11 @@ See also `t.isMixedTypeAnnotation(node, opts)` and `t.assertMixedTypeAnnotation( Aliases: `Flow`, `FlowBaseAnnotation` +### t.emptyTypeAnnotation() + +See also `t.isEmptyTypeAnnotation(node, opts)` and `t.assertEmptyTypeAnnotation(node, opts)`. + +Aliases: `Flow`, `FlowBaseAnnotation` ### t.newExpression(callee, arguments) diff --git a/packages/babel-types/package.json b/packages/babel-types/package.json index 5475529d7db9..4a8cc7d63a63 100644 --- a/packages/babel-types/package.json +++ b/packages/babel-types/package.json @@ -1,7 +1,7 @@ { "name": "babel-types", "version": "6.16.0", - "description": "", + "description": "Babel Types is a Lodash-esque utility library for AST nodes", "author": "Sebastian McKenzie ", "homepage": "https://babeljs.io/", "license": "MIT", diff --git a/packages/babel-types/src/definitions/flow.js b/packages/babel-types/src/definitions/flow.js index 9b5d20dff54d..208382420cbd 100644 --- a/packages/babel-types/src/definitions/flow.js +++ b/packages/babel-types/src/definitions/flow.js @@ -167,6 +167,10 @@ defineType("MixedTypeAnnotation", { aliases: ["Flow", "FlowBaseAnnotation"] }); +defineType("EmptyTypeAnnotation", { + aliases: ["Flow", "FlowBaseAnnotation"] +}); + defineType("NullableTypeAnnotation", { visitor: ["typeAnnotation"], aliases: ["Flow"], diff --git a/packages/babel-types/test/converters.js b/packages/babel-types/test/converters.js new file mode 100644 index 000000000000..56dabf658604 --- /dev/null +++ b/packages/babel-types/test/converters.js @@ -0,0 +1,147 @@ +import * as t from "../lib"; +import { assert } from "chai"; + +describe("converters", function () { + describe("valueToNode", function () { + it("number", function () { + assert.deepEqual(t.valueToNode(Math.PI), t.numericLiteral(Math.PI)); + assert.deepEqual(t.valueToNode(-Infinity), t.numericLiteral(-Infinity)); + assert.deepEqual(t.valueToNode(NaN), t.numericLiteral(NaN)); + }); + it("string", function () { + assert.deepEqual(t.valueToNode("This is a \"string\""), t.stringLiteral("This is a \"string\"")); + }); + it("boolean", function () { + assert.deepEqual(t.valueToNode(true), t.booleanLiteral(true)); + assert.deepEqual(t.valueToNode(false), t.booleanLiteral(false)); + }); + it("null", function () { + assert.deepEqual(t.valueToNode(null), t.nullLiteral()); + }); + it("undefined", function () { + assert.deepEqual(t.valueToNode(undefined), t.identifier("undefined")); + }); + it("RegExp", function () { + assert.deepEqual(t.valueToNode(/abc.+/gm), t.regExpLiteral("abc.+", "gm")); + }); + it("array", function () { + assert.deepEqual(t.valueToNode([1, "a"]), t.arrayExpression([t.numericLiteral(1), t.stringLiteral("a")])); + }); + it("object", function () { + assert.deepEqual(t.valueToNode({ + a: 1, + "b c": 2 + }), t.objectExpression([ + t.objectProperty(t.identifier("a"), t.numericLiteral(1)), + t.objectProperty(t.stringLiteral("b c"), t.numericLiteral(2)) + ])); + }); + it("throws if cannot convert", function () { + assert.throws(function () { + t.valueToNode(Object); + }); + assert.throws(function () { + t.valueToNode(Symbol()); + }); + }); + }); + describe("toKeyAlias", function () { + beforeEach(function () { + // make tests deterministic + t.toKeyAlias.uid = 0; + }); + it("doesn't change string literals", function () { + assert.equal(t.toKeyAlias(t.objectProperty(t.stringLiteral("a"), t.nullLiteral())), "\"a\""); + }); + it("wraps around at Number.MAX_SAFE_INTEGER", function () { + assert.equal(t.toKeyAlias(t.objectMethod("method", t.identifier("a"), [], t.blockStatement([]))), "0"); + }); + }); + describe("toStatement", function () { + it("noop on statements", function () { + const node = t.emptyStatement(); + assert.equal(t.toStatement(node), node); + t.assertEmptyStatement(node); + }); + it("mutate class expression to declaration", function () { + const node = t.classExpression(t.identifier("A"), null, t.classBody([]), []); + t.toStatement(node); + t.assertClassDeclaration(node); + }); + it("fail if class expression has no id", function () { + const node = t.classExpression(null, null, t.classBody([]), []); + assert.throws(function() { + t.toStatement(node); + }); + assert.strictEqual(t.toStatement(node, /* ignore = */ true), false); + t.assertClassExpression(node); + }); + it("mutate function expression to declaration", function () { + const node = t.functionExpression(t.identifier("A"), [], t.blockStatement([])); + t.toStatement(node); + t.assertFunctionDeclaration(node); + }); + it("fail if function expression has no id", function () { + const node = t.functionExpression(null, [], t.blockStatement([])); + assert.throws(function() { + t.toStatement(node); + }); + assert.strictEqual(t.toStatement(node, /* ignore = */ true), false); + t.assertFunctionExpression(node); + }); + it("assignment expression", function () { + const node = t.assignmentExpression("+=", t.identifier("x"), t.numericLiteral(1)); + t.assertExpressionStatement(t.toStatement(node)); + t.assertAssignmentExpression(node); + }); + it("fail if cannot convert node type", function () { + const node = t.yieldExpression(t.identifier("foo")); + assert.throws(function() { + t.toStatement(node); + }); + assert.strictEqual(t.toStatement(node, /* ignore = */ true), false); + t.assertYieldExpression(node); + }); + }); + describe("toExpression", function () { + it("noop on expressions", function () { + const node = t.identifier("a"); + assert.equal(t.toExpression(node), node); + t.assertIdentifier(node); + }); + it("mutate class declaration to expression", function () { + const node = t.classDeclaration(t.identifier("A"), null, t.classBody([]), []); + t.toExpression(node); + t.assertClassExpression(node); + }); + it("mutate function declaration to expression", function () { + const node = t.functionDeclaration(t.identifier("A"), [], t.blockStatement([])); + t.toExpression(node); + t.assertFunctionExpression(node); + }); + it("mutate object method to expression", function () { + const node = t.objectMethod("method", t.identifier("A"), [], t.blockStatement([])); + t.toExpression(node); + t.assertFunctionExpression(node); + }); + it("mutate class method to expression", function () { + const node = t.classMethod("constructor", t.identifier("A"), [], t.blockStatement([])); + t.toExpression(node); + t.assertFunctionExpression(node); + }); + it("expression statement", function () { + const inner = t.yieldExpression(t.identifier("foo")); + const node = t.expressionStatement(inner); + t.assertYieldExpression(t.toExpression(node)); + assert.equal(t.toExpression(node), inner); + t.assertExpressionStatement(node); + }); + it("fail if cannot convert node type", function () { + const node = t.program([]); + assert.throws(function() { + t.toExpression(node); + }); + t.assertProgram(node); + }); + }); +}); diff --git a/scripts/babel-register.js b/scripts/babel-register.js new file mode 100644 index 000000000000..aae4caa1b49b --- /dev/null +++ b/scripts/babel-register.js @@ -0,0 +1,23 @@ +var babel = require("../package.json").babel; +var register = require("babel-register"); +var path = require("path"); + +if (babel.plugins) { + // correct path of relative plugins + babel.plugins = babel.plugins.map(function (plugin) { + if (plugin.charAt(0) === '.') { + return plugin.replace(/^\./, path.join(__dirname, '..')); + } + + return plugin; + }); +} + +register(babel); +register({ + extensions: [".js"], + // Only js files in the test folder but not in the subfolder fixtures. + only: /packages\/.+\/test\/(?!fixtures\/).+\.js$/, + babelrc: false, + compact: true, +}); diff --git a/test/mocha.opts b/test/mocha.opts index 2267a63e6897..b4b84465b271 100644 --- a/test/mocha.opts +++ b/test/mocha.opts @@ -1 +1 @@ ---reporter dot --ui tdd --timeout 10000 +--reporter dot --ui tdd --timeout 10000 --compilers js:./scripts/babel-register