Run new lint rules (#5413)

This commit is contained in:
Brian Ng 2017-03-04 09:46:01 -06:00 committed by Henry Zhu
parent f7e2d88f6c
commit 8a82cc060a
181 changed files with 1459 additions and 1454 deletions

View File

@ -1,6 +1,11 @@
{ {
"extends": "babel", "extends": "babel",
"rules": { "rules": {
"comma-dangle": ["error", "always-multiline"],
"curly": ["error", "multi-line"],
"func-call-spacing": "error",
"key-spacing": "error",
"no-multi-spaces": "error"
}, },
"env": { "env": {
"node": true, "node": true,

View File

@ -29,10 +29,10 @@ program.parse(process.argv);
register({ register({
extensions: program.extensions, extensions: program.extensions,
ignore: program.ignore, ignore: program.ignore,
only: program.only, only: program.only,
plugins: program.plugins, plugins: program.plugins,
presets: program.presets, presets: program.presets,
}); });
// //
@ -55,8 +55,8 @@ const replPlugin = ({ types: t }) => ({
// If the executed code doesn't evaluate to a value, // If the executed code doesn't evaluate to a value,
// prevent implicit strict mode from printing 'use strict'. // prevent implicit strict mode from printing 'use strict'.
path.pushContainer("body", t.expressionStatement(t.identifier("undefined"))); path.pushContainer("body", t.expressionStatement(t.identifier("undefined")));
} },
} },
}); });
// //
@ -68,11 +68,11 @@ const _eval = function (code, filename) {
code = babel.transform(code, { code = babel.transform(code, {
filename: filename, filename: filename,
presets: program.presets, presets: program.presets,
plugins: (program.plugins || []).concat([replPlugin]) plugins: (program.plugins || []).concat([replPlugin]),
}).code; }).code;
return vm.runInThisContext(code, { return vm.runInThisContext(code, {
filename: filename filename: filename,
}); });
}; };
@ -85,10 +85,10 @@ if (program.eval || program.print) {
const module = new Module(global.__filename); const module = new Module(global.__filename);
module.filename = global.__filename; module.filename = global.__filename;
module.paths = Module._nodeModulePaths(global.__dirname); module.paths = Module._nodeModulePaths(global.__dirname);
global.exports = module.exports; global.exports = module.exports;
global.module = module; global.module = module;
global.require = module.require.bind(module); global.require = module.require.bind(module);
const result = _eval(code, global.__filename); const result = _eval(code, global.__filename);
@ -141,7 +141,7 @@ function replStart() {
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
eval: replEval, eval: replEval,
useGlobal: true useGlobal: true,
}); });
} }

View File

@ -14,7 +14,7 @@ let userArgs;
// separate node arguments from script arguments // separate node arguments from script arguments
const argSeparator = babelArgs.indexOf("--"); const argSeparator = babelArgs.indexOf("--");
if (argSeparator > -1) { if (argSeparator > -1) {
userArgs = babelArgs.slice(argSeparator); // including the -- userArgs = babelArgs.slice(argSeparator); // including the --
babelArgs = babelArgs.slice(0, argSeparator); babelArgs = babelArgs.slice(0, argSeparator);
} }

View File

@ -14,7 +14,7 @@ export default function (commander, filenames) {
const data = util.compile(src, { const data = util.compile(src, {
sourceFileName: slash(path.relative(dest + "/..", src)), sourceFileName: slash(path.relative(dest + "/..", src)),
sourceMapTarget: path.basename(relative) sourceMapTarget: path.basename(relative),
}); });
if (!commander.copyFiles && data.ignored) return; if (!commander.copyFiles && data.ignored) return;
@ -74,7 +74,7 @@ export default function (commander, filenames) {
awaitWriteFinish: { awaitWriteFinish: {
stabilityThreshold: 50, stabilityThreshold: 50,
pollInterval: 10, pollInterval: 10,
} },
}); });
["add", "change"].forEach(function (type) { ["add", "change"].forEach(function (type) {

View File

@ -1,5 +1,5 @@
import convertSourceMap from "convert-source-map"; import convertSourceMap from "convert-source-map";
import sourceMap from "source-map"; import sourceMap from "source-map";
import slash from "slash"; import slash from "slash";
import path from "path"; import path from "path";
import fs from "fs"; import fs from "fs";
@ -16,7 +16,7 @@ export default function (commander, filenames, opts) {
const buildResult = function () { const buildResult = function () {
const map = new sourceMap.SourceMapGenerator({ const map = new sourceMap.SourceMapGenerator({
file: path.basename(commander.outFile || "") || "stdout", file: path.basename(commander.outFile || "") || "stdout",
sourceRoot: opts.sourceRoot sourceRoot: opts.sourceRoot,
}); });
let code = ""; let code = "";
@ -64,7 +64,7 @@ export default function (commander, filenames, opts) {
return { return {
map: map, map: map,
code: code code: code,
}; };
}; };
@ -156,7 +156,7 @@ export default function (commander, filenames, opts) {
awaitWriteFinish: { awaitWriteFinish: {
stabilityThreshold: 50, stabilityThreshold: 50,
pollInterval: 10, pollInterval: 10,
} },
}).on("all", function (type, filename) { }).on("all", function (type, filename) {
if (util.shouldIgnore(filename) || !util.canCompile(filename, commander.extensions)) return; if (util.shouldIgnore(filename) || !util.canCompile(filename, commander.extensions)) return;

View File

@ -1,11 +1,11 @@
#!/usr/bin/env node #!/usr/bin/env node
import fs from "fs"; import fs from "fs";
import commander from "commander"; import commander from "commander";
import kebabCase from "lodash/kebabCase"; import kebabCase from "lodash/kebabCase";
import { options, util, version } from "babel-core"; import { options, util, version } from "babel-core";
import uniq from "lodash/uniq"; import uniq from "lodash/uniq";
import glob from "glob"; import glob from "glob";
import dirCommand from "./dir"; import dirCommand from "./dir";
import fileCommand from "./file"; import fileCommand from "./file";

View File

@ -1,21 +1,21 @@
const includes = require("lodash/includes"); const includes = require("lodash/includes");
const readdir = require("fs-readdir-recursive"); const readdir = require("fs-readdir-recursive");
const helper = require("babel-helper-fixtures"); const helper = require("babel-helper-fixtures");
const assert = require("assert"); const assert = require("assert");
const rimraf = require("rimraf"); const rimraf = require("rimraf");
const outputFileSync = require("output-file-sync"); const outputFileSync = require("output-file-sync");
const child = require("child_process"); const child = require("child_process");
const merge = require("lodash/merge"); const merge = require("lodash/merge");
const path = require("path"); const path = require("path");
const chai = require("chai"); const chai = require("chai");
const fs = require("fs"); const fs = require("fs");
const fixtureLoc = path.join(__dirname, "fixtures"); const fixtureLoc = path.join(__dirname, "fixtures");
const tmpLoc = path.join(__dirname, "tmp"); const tmpLoc = path.join(__dirname, "tmp");
const presetLocs = [ const presetLocs = [
path.join(__dirname, "../../babel-preset-es2015"), path.join(__dirname, "../../babel-preset-es2015"),
path.join(__dirname, "../../babel-preset-react") path.join(__dirname, "../../babel-preset-react"),
].join(","); ].join(",");
const pluginLocs = [ const pluginLocs = [
@ -150,7 +150,7 @@ fs.readdirSync(fixtureLoc).forEach(function (binName) {
const testLoc = path.join(suiteLoc, testName); const testLoc = path.join(suiteLoc, testName);
const opts = { const opts = {
args: [] args: [],
}; };
const optionsLoc = path.join(testLoc, "options.json"); const optionsLoc = path.join(testLoc, "options.json");
@ -166,7 +166,7 @@ fs.readdirSync(fixtureLoc).forEach(function (binName) {
}); });
opts.outFiles = readDir(path.join(testLoc, "out-files")); opts.outFiles = readDir(path.join(testLoc, "out-files"));
opts.inFiles = readDir(path.join(testLoc, "in-files")); opts.inFiles = readDir(path.join(testLoc, "in-files"));
const babelrcLoc = path.join(testLoc, ".babelrc"); const babelrcLoc = path.join(testLoc, ".babelrc");
if (fs.existsSync(babelrcLoc)) { if (fs.existsSync(babelrcLoc)) {

View File

@ -8,18 +8,18 @@ import Chalk from "chalk";
function getDefs(chalk) { function getDefs(chalk) {
return { return {
keyword: chalk.cyan, keyword: chalk.cyan,
capitalized: chalk.yellow, capitalized: chalk.yellow,
jsx_tag: chalk.yellow, jsx_tag: chalk.yellow,
punctuator: chalk.yellow, punctuator: chalk.yellow,
// bracket: intentionally omitted. // bracket: intentionally omitted.
number: chalk.magenta, number: chalk.magenta,
string: chalk.green, string: chalk.green,
regex: chalk.magenta, regex: chalk.magenta,
comment: chalk.grey, comment: chalk.grey,
invalid: chalk.white.bgRed.bold, invalid: chalk.white.bgRed.bold,
gutter: chalk.grey, gutter: chalk.grey,
marker: chalk.red.bold, marker: chalk.red.bold,
}; };
} }
@ -117,7 +117,7 @@ export default function (
const lines = rawLines.split(NEWLINE); const lines = rawLines.split(NEWLINE);
let start = Math.max(lineNumber - (linesAbove + 1), 0); let start = Math.max(lineNumber - (linesAbove + 1), 0);
let end = Math.min(lines.length, lineNumber + linesBelow); let end = Math.min(lines.length, lineNumber + linesBelow);
if (!lineNumber && !colNumber) { if (!lineNumber && !colNumber) {
start = 0; start = 0;
@ -138,14 +138,14 @@ export default function (
"\n ", "\n ",
maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")),
markerSpacing, markerSpacing,
maybeHighlight(defs.marker, "^") maybeHighlight(defs.marker, "^"),
].join(""); ].join("");
} }
return [ return [
maybeHighlight(defs.marker, ">"), maybeHighlight(defs.marker, ">"),
maybeHighlight(defs.gutter, gutter), maybeHighlight(defs.gutter, gutter),
line, line,
markerLine markerLine,
].join(""); ].join("");
} else { } else {
return ` ${maybeHighlight(defs.gutter, gutter)}${line}`; return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;

View File

@ -55,7 +55,7 @@ describe("babel-code-frame", function () {
"", "",
"function sum(a, b) {", "function sum(a, b) {",
" return a + b", " return a + b",
"}" "}",
].join("\n"); ].join("\n");
assert.equal(codeFrame(rawLines, 7, 2), [ assert.equal(codeFrame(rawLines, 7, 2), [
" 5 | * @param b Number", " 5 | * @param b Number",
@ -80,7 +80,7 @@ describe("babel-code-frame", function () {
"", "",
"function sum(a, b) {", "function sum(a, b) {",
" return a + b", " return a + b",
"}" "}",
].join("\n"); ].join("\n");
assert.equal(codeFrame(rawLines, 6, 2), [ assert.equal(codeFrame(rawLines, 6, 2), [
" 4 | * @param a Number", " 4 | * @param a Number",
@ -130,7 +130,7 @@ describe("babel-code-frame", function () {
"", "",
"function sum(a, b) {", "function sum(a, b) {",
" return a + b", " return a + b",
"}" "}",
].join("\n"); ].join("\n");
assert.equal(codeFrame(rawLines, 7, 2, { linesAbove: 1 }), [ assert.equal(codeFrame(rawLines, 7, 2, { linesAbove: 1 }), [
" 6 | * @returns Number", " 6 | * @returns Number",
@ -154,14 +154,14 @@ describe("babel-code-frame", function () {
"", "",
"function sum(a, b) {", "function sum(a, b) {",
" return a + b", " return a + b",
"}" "}",
].join("\n"); ].join("\n");
assert.equal(codeFrame(rawLines, 7, 2, { linesBelow: 1 }), [ assert.equal(codeFrame(rawLines, 7, 2, { linesBelow: 1 }), [
" 5 | * @param b Number", " 5 | * @param b Number",
" 6 | * @returns Number", " 6 | * @returns Number",
"> 7 | */", "> 7 | */",
" | ^", " | ^",
" 8 | " " 8 | ",
].join("\n")); ].join("\n"));
}); });
@ -177,13 +177,13 @@ describe("babel-code-frame", function () {
"", "",
"function sum(a, b) {", "function sum(a, b) {",
" return a + b", " return a + b",
"}" "}",
].join("\n"); ].join("\n");
assert.equal(codeFrame(rawLines, 7, 2, { linesAbove: 1, linesBelow: 1 }), [ assert.equal(codeFrame(rawLines, 7, 2, { linesAbove: 1, linesBelow: 1 }), [
" 6 | * @returns Number", " 6 | * @returns Number",
"> 7 | */", "> 7 | */",
" | ^", " | ^",
" 8 | " " 8 | ",
].join("\n")); ].join("\n"));
}); });
@ -195,13 +195,13 @@ describe("babel-code-frame", function () {
"", "",
"", "",
"", "",
"" "",
].join("\n"); ].join("\n");
assert.equal(codeFrame(rawLines, 3, null, { linesAbove: 1, linesBelow: 1, forceColor: true }), assert.equal(codeFrame(rawLines, 3, null, { linesAbove: 1, linesBelow: 1, forceColor: true }),
chalk.reset([ chalk.reset([
" " + gutter(" 2 | "), " " + gutter(" 2 | "),
marker(">") + gutter(" 3 | "), marker(">") + gutter(" 3 | "),
" " + gutter(" 4 | ") " " + gutter(" 4 | "),
].join("\n")) ].join("\n"))
); );
}); });

View File

@ -17,7 +17,7 @@ export default class Store {
return this._map.get(key); return this._map.get(key);
} else { } else {
if (Object.prototype.hasOwnProperty.call(this._map.dynamicData, key)) { if (Object.prototype.hasOwnProperty.call(this._map.dynamicData, key)) {
const val = this._map.dynamicData[key](); const val = this._map.dynamicData[key]();
this._map.set(key, val); this._map.set(key, val);
return val; return val;
} }

View File

@ -19,9 +19,9 @@ const buildUmdWrapper = template(`
`); `);
function buildGlobal(namespace, builder) { function buildGlobal(namespace, builder) {
const body = []; const body = [];
const container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body)); const container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
const tree = t.program([ const tree = t.program([
t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]); t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]);
body.push(t.variableDeclaration("var", [ body.push(t.variableDeclaration("var", [
@ -29,7 +29,7 @@ function buildGlobal(namespace, builder) {
namespace, namespace,
t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace),
t.objectExpression([])) t.objectExpression([]))
) ),
])); ]));
builder(body); builder(body);
@ -40,7 +40,7 @@ function buildGlobal(namespace, builder) {
function buildUmd(namespace, builder) { function buildUmd(namespace, builder) {
const body = []; const body = [];
body.push(t.variableDeclaration("var", [ body.push(t.variableDeclaration("var", [
t.variableDeclarator(namespace, t.identifier("global")) t.variableDeclarator(namespace, t.identifier("global")),
])); ]));
builder(body); builder(body);
@ -48,23 +48,23 @@ function buildUmd(namespace, builder) {
return t.program([ return t.program([
buildUmdWrapper({ buildUmdWrapper({
FACTORY_PARAMETERS: t.identifier("global"), FACTORY_PARAMETERS: t.identifier("global"),
BROWSER_ARGUMENTS: t.assignmentExpression( BROWSER_ARGUMENTS: t.assignmentExpression(
"=", "=",
t.memberExpression(t.identifier("root"), namespace), t.memberExpression(t.identifier("root"), namespace),
t.objectExpression([]) t.objectExpression([])
), ),
COMMON_ARGUMENTS: t.identifier("exports"), COMMON_ARGUMENTS: t.identifier("exports"),
AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]), AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]),
FACTORY_BODY: body, FACTORY_BODY: body,
UMD_ROOT: t.identifier("this") UMD_ROOT: t.identifier("this"),
}) }),
]); ]);
} }
function buildVar(namespace, builder) { function buildVar(namespace, builder) {
const body = []; const body = [];
body.push(t.variableDeclaration("var", [ body.push(t.variableDeclaration("var", [
t.variableDeclarator(namespace, t.objectExpression([])) t.variableDeclarator(namespace, t.objectExpression([])),
])); ]));
builder(body); builder(body);
body.push(t.expressionStatement(namespace)); body.push(t.expressionStatement(namespace));
@ -95,8 +95,8 @@ export default function (
const build = { const build = {
global: buildGlobal, global: buildGlobal,
umd: buildUmd, umd: buildUmd,
var: buildVar, var: buildVar,
}[outputType]; }[outputType];
if (build) { if (build) {

View File

@ -14,7 +14,7 @@ import traverse from "babel-traverse";
import Logger from "./logger"; import Logger from "./logger";
import Store from "../../store"; import Store from "../../store";
import { parse } from "babylon"; import { parse } from "babylon";
import * as util from "../../util"; import * as util from "../../util";
import path from "path"; import path from "path";
import * as t from "babel-types"; import * as t from "babel-types";
@ -27,7 +27,7 @@ const shebangRegex = /^#!.*/;
const INTERNAL_PLUGINS = [ const INTERNAL_PLUGINS = [
[blockHoistPlugin], [blockHoistPlugin],
[shadowFunctionsPlugin] [shadowFunctionsPlugin],
]; ];
const errorVisitor = { const errorVisitor = {
@ -37,20 +37,20 @@ const errorVisitor = {
state.loc = loc; state.loc = loc;
path.stop(); path.stop();
} }
} },
}; };
export default class File extends Store { export default class File extends Store {
constructor(opts: Object = {}) { constructor(opts: Object = {}) {
super(); super();
this.log = new Logger(this, opts.filename || "unknown"); this.log = new Logger(this, opts.filename || "unknown");
this.opts = this.initOptions(opts); this.opts = this.initOptions(opts);
this.parserOpts = { this.parserOpts = {
sourceType: this.opts.sourceType, sourceType: this.opts.sourceType,
sourceFileName: this.opts.filename, sourceFileName: this.opts.filename,
plugins: [] plugins: [],
}; };
this.pluginVisitors = []; this.pluginVisitors = [];
@ -78,21 +78,21 @@ export default class File extends Store {
imports: [], imports: [],
exports: { exports: {
exported: [], exported: [],
specifiers: [] specifiers: [],
} },
} },
}; };
this.dynamicImportTypes = {}; this.dynamicImportTypes = {};
this.dynamicImportIds = {}; this.dynamicImportIds = {};
this.dynamicImports = []; this.dynamicImports = [];
this.declarations = {}; this.declarations = {};
this.usedHelpers = {}; this.usedHelpers = {};
this.path = null; this.path = null;
this.ast = {}; this.ast = {};
this.code = ""; this.code = "";
this.shebang = ""; this.shebang = "";
this.hub = new Hub(this); this.hub = new Hub(this);
@ -149,22 +149,22 @@ export default class File extends Store {
if (opts.only) opts.only = util.arrayify(opts.only, util.regexify); if (opts.only) opts.only = util.arrayify(opts.only, util.regexify);
defaults(opts, { defaults(opts, {
moduleRoot: opts.sourceRoot moduleRoot: opts.sourceRoot,
}); });
defaults(opts, { defaults(opts, {
sourceRoot: opts.moduleRoot sourceRoot: opts.moduleRoot,
}); });
defaults(opts, { defaults(opts, {
filenameRelative: opts.filename filenameRelative: opts.filename,
}); });
const basenameRelative = path.basename(opts.filenameRelative); const basenameRelative = path.basename(opts.filenameRelative);
defaults(opts, { defaults(opts, {
sourceFileName: basenameRelative, sourceFileName: basenameRelative,
sourceMapTarget: basenameRelative sourceMapTarget: basenameRelative,
}); });
return opts; return opts;
@ -282,7 +282,7 @@ export default class File extends Store {
} }
const generator = this.get("helperGenerator"); const generator = this.get("helperGenerator");
const runtime = this.get("helpersNamespace"); const runtime = this.get("helpersNamespace");
if (generator) { if (generator) {
const res = generator(name); const res = generator(name);
if (res) return res; if (res) return res;
@ -304,7 +304,7 @@ export default class File extends Store {
this.scope.push({ this.scope.push({
id: uid, id: uid,
init: ref, init: ref,
unique: true unique: true,
}); });
} }
@ -334,7 +334,7 @@ export default class File extends Store {
this.scope.push({ this.scope.push({
id: uid, id: uid,
init: init, init: init,
_blockHoist: 1.9 // This ensures that we don't fail if not using function expression helpers _blockHoist: 1.9, // This ensures that we don't fail if not using function expression helpers
}); });
return uid; return uid;
} }
@ -365,12 +365,12 @@ export default class File extends Store {
const inputMap = this.opts.inputSourceMap; const inputMap = this.opts.inputSourceMap;
if (inputMap) { if (inputMap) {
const inputMapConsumer = new sourceMap.SourceMapConsumer(inputMap); const inputMapConsumer = new sourceMap.SourceMapConsumer(inputMap);
const outputMapConsumer = new sourceMap.SourceMapConsumer(map); const outputMapConsumer = new sourceMap.SourceMapConsumer(map);
const mergedGenerator = new sourceMap.SourceMapGenerator({ const mergedGenerator = new sourceMap.SourceMapGenerator({
file: inputMapConsumer.file, file: inputMapConsumer.file,
sourceRoot: inputMapConsumer.sourceRoot sourceRoot: inputMapConsumer.sourceRoot,
}); });
// This assumes the output map always has a single source, since Babel always compiles a // This assumes the output map always has a single source, since Babel always compiles a
@ -381,7 +381,7 @@ export default class File extends Store {
const generatedPosition = outputMapConsumer.generatedPositionFor({ const generatedPosition = outputMapConsumer.generatedPositionFor({
line: mapping.generatedLine, line: mapping.generatedLine,
column: mapping.generatedColumn, column: mapping.generatedColumn,
source: source source: source,
}); });
if (generatedPosition.column != null) { if (generatedPosition.column != null) {
mergedGenerator.addMapping({ mergedGenerator.addMapping({
@ -389,10 +389,10 @@ export default class File extends Store {
original: mapping.source == null ? null : { original: mapping.source == null ? null : {
line: mapping.originalLine, line: mapping.originalLine,
column: mapping.originalColumn column: mapping.originalColumn,
}, },
generated: generatedPosition generated: generatedPosition,
}); });
} }
}); });
@ -429,7 +429,7 @@ export default class File extends Store {
parserOpts.parser = { parserOpts.parser = {
parse(source) { parse(source) {
return parse(source, parserOpts); return parse(source, parserOpts);
} },
}; };
} }
} }
@ -446,10 +446,10 @@ export default class File extends Store {
parentPath: null, parentPath: null,
parent: ast, parent: ast,
container: ast, container: ast,
key: "program" key: "program",
}).setContext(); }).setContext();
this.scope = this.path.scope; this.scope = this.path.scope;
this.ast = ast; this.ast = ast;
this.getMetadata(); this.getMetadata();
} }
@ -568,11 +568,11 @@ export default class File extends Store {
makeResult({ code, map, ast, ignored }: BabelFileResult): BabelFileResult { makeResult({ code, map, ast, ignored }: BabelFileResult): BabelFileResult {
const result = { const result = {
metadata: null, metadata: null,
options: this.opts, options: this.opts,
ignored: !!ignored, ignored: !!ignored,
code: null, code: null,
ast: null, ast: null,
map: map || null map: map || null,
}; };
if (this.opts.code) { if (this.opts.code) {
@ -592,7 +592,7 @@ export default class File extends Store {
generate(): BabelFileResult { generate(): BabelFileResult {
const opts = this.opts; const opts = this.opts;
const ast = this.ast; const ast = this.ast;
const result: BabelFileResult = { ast }; const result: BabelFileResult = { ast };
if (!opts.code) return this.makeResult(result); if (!opts.code) return this.makeResult(result);
@ -618,7 +618,7 @@ export default class File extends Store {
const _result = gen(ast, opts.generatorOpts ? Object.assign(opts, opts.generatorOpts) : opts, const _result = gen(ast, opts.generatorOpts ? Object.assign(opts, opts.generatorOpts) : opts,
this.code); this.code);
result.code = _result.code; result.code = _result.code;
result.map = _result.map; result.map = _result.map;
this.log.debug("Generation end"); this.log.debug("Generation end");

View File

@ -9,7 +9,7 @@ const seenDeprecatedMessages = [];
export default class Logger { export default class Logger {
constructor(file: File, filename: string) { constructor(file: File, filename: string) {
this.filename = filename; this.filename = filename;
this.file = file; this.file = file;
} }
filename: string; filename: string;

View File

@ -6,7 +6,7 @@ export const ModuleDeclaration = {
if (node.source) { if (node.source) {
node.source.value = file.resolveModuleSource(node.source.value); node.source.value = file.resolveModuleSource(node.source.value);
} }
} },
}; };
export const ImportDeclaration = { export const ImportDeclaration = {
@ -18,7 +18,7 @@ export const ImportDeclaration = {
file.metadata.modules.imports.push({ file.metadata.modules.imports.push({
source: node.source.value, source: node.source.value,
imported, imported,
specifiers specifiers,
}); });
for (const specifier of (path.get("specifiers"): Array<Object>)) { for (const specifier of (path.get("specifiers"): Array<Object>)) {
@ -29,7 +29,7 @@ export const ImportDeclaration = {
specifiers.push({ specifiers.push({
kind: "named", kind: "named",
imported: "default", imported: "default",
local local,
}); });
} }
@ -39,7 +39,7 @@ export const ImportDeclaration = {
specifiers.push({ specifiers.push({
kind: "named", kind: "named",
imported: importedName, imported: importedName,
local local,
}); });
} }
@ -47,11 +47,11 @@ export const ImportDeclaration = {
imported.push("*"); imported.push("*");
specifiers.push({ specifiers.push({
kind: "namespace", kind: "namespace",
local local,
}); });
} }
} }
} },
}; };
export function ExportDeclaration(path, file) { export function ExportDeclaration(path, file) {
@ -71,7 +71,7 @@ export function ExportDeclaration(path, file) {
exports.specifiers.push({ exports.specifiers.push({
kind: "local", kind: "local",
local: name, local: name,
exported: path.isExportDefaultDeclaration() ? "default" : name exported: path.isExportDefaultDeclaration() ? "default" : name,
}); });
} }
} }
@ -87,7 +87,7 @@ export function ExportDeclaration(path, file) {
kind: "external", kind: "external",
local: exported, local: exported,
exported, exported,
source source,
}); });
} }
@ -96,7 +96,7 @@ export function ExportDeclaration(path, file) {
exports.specifiers.push({ exports.specifiers.push({
kind: "external-namespace", kind: "external-namespace",
exported, exported,
source source,
}); });
} }
@ -110,7 +110,7 @@ export function ExportDeclaration(path, file) {
kind: "external", kind: "external",
local: local.name, local: local.name,
exported, exported,
source source,
}); });
} }
@ -120,7 +120,7 @@ export function ExportDeclaration(path, file) {
exports.specifiers.push({ exports.specifiers.push({
kind: "local", kind: "local",
local: local.name, local: local.name,
exported exported,
}); });
} }
} }
@ -130,7 +130,7 @@ export function ExportDeclaration(path, file) {
if (path.isExportAllDeclaration()) { if (path.isExportAllDeclaration()) {
exports.specifiers.push({ exports.specifiers.push({
kind: "external-all", kind: "external-all",
source source,
}); });
} }
} }

View File

@ -6,11 +6,11 @@ import path from "path";
import fs from "fs"; import fs from "fs";
const existsCache = {}; const existsCache = {};
const jsonCache = {}; const jsonCache = {};
const BABELIGNORE_FILENAME = ".babelignore"; const BABELIGNORE_FILENAME = ".babelignore";
const BABELRC_FILENAME = ".babelrc"; const BABELRC_FILENAME = ".babelrc";
const PACKAGE_FILENAME = "package.json"; const PACKAGE_FILENAME = "package.json";
function exists(filename) { function exists(filename) {
const cached = existsCache[filename]; const cached = existsCache[filename];
@ -33,7 +33,7 @@ export default function buildConfigChain(opts: Object = {}, log?: Logger) {
builder.mergeConfig({ builder.mergeConfig({
options: opts, options: opts,
alias: "base", alias: "base",
dirname: filename && path.dirname(filename) dirname: filename && path.dirname(filename),
}); });
return builder.configs; return builder.configs;
@ -83,7 +83,7 @@ class ConfigChainBuilder {
} }
addIgnoreConfig(loc) { addIgnoreConfig(loc) {
const file = fs.readFileSync(loc, "utf8"); const file = fs.readFileSync(loc, "utf8");
let lines = file.split("\n"); let lines = file.split("\n");
lines = lines lines = lines
@ -94,7 +94,7 @@ class ConfigChainBuilder {
this.mergeConfig({ this.mergeConfig({
options: { ignore: lines }, options: { ignore: lines },
alias: loc, alias: loc,
dirname: path.dirname(loc) dirname: path.dirname(loc),
}); });
} }
} }
@ -120,7 +120,7 @@ class ConfigChainBuilder {
this.mergeConfig({ this.mergeConfig({
options, options,
alias: loc, alias: loc,
dirname: path.dirname(loc) dirname: path.dirname(loc),
}); });
return !!options; return !!options;
@ -130,7 +130,7 @@ class ConfigChainBuilder {
options, options,
alias, alias,
loc, loc,
dirname dirname,
}) { }) {
if (!options) { if (!options) {
return false; return false;
@ -156,7 +156,7 @@ class ConfigChainBuilder {
options, options,
alias, alias,
loc, loc,
dirname dirname,
}); });
// env // env
@ -170,7 +170,7 @@ class ConfigChainBuilder {
this.mergeConfig({ this.mergeConfig({
options: envOpts, options: envOpts,
alias: `${alias}.env.${envKey}`, alias: `${alias}.env.${envKey}`,
dirname: dirname dirname: dirname,
}); });
} }
} }

View File

@ -5,191 +5,191 @@ export default {
type: "filename", type: "filename",
description: "filename to use when reading from stdin - this will be used in source-maps, errors etc", description: "filename to use when reading from stdin - this will be used in source-maps, errors etc",
default: "unknown", default: "unknown",
shorthand: "f" shorthand: "f",
}, },
filenameRelative: { filenameRelative: {
hidden: true, hidden: true,
type: "string" type: "string",
}, },
inputSourceMap: { inputSourceMap: {
hidden: true hidden: true,
}, },
env: { env: {
hidden: true, hidden: true,
default: {} default: {},
}, },
mode: { mode: {
description: "", description: "",
hidden: true hidden: true,
}, },
retainLines: { retainLines: {
type: "boolean", type: "boolean",
default: false, default: false,
description: "retain line numbers - will result in really ugly code" description: "retain line numbers - will result in really ugly code",
}, },
highlightCode: { highlightCode: {
description: "enable/disable ANSI syntax highlighting of code frames (on by default)", description: "enable/disable ANSI syntax highlighting of code frames (on by default)",
type: "boolean", type: "boolean",
default: true default: true,
}, },
suppressDeprecationMessages: { suppressDeprecationMessages: {
type: "boolean", type: "boolean",
default: false, default: false,
hidden: true hidden: true,
}, },
presets: { presets: {
type: "list", type: "list",
description: "", description: "",
default: [] default: [],
}, },
plugins: { plugins: {
type: "list", type: "list",
default: [], default: [],
description: "" description: "",
}, },
ignore: { ignore: {
type: "list", type: "list",
description: "list of glob paths to **not** compile", description: "list of glob paths to **not** compile",
default: [] default: [],
}, },
only: { only: {
type: "list", type: "list",
description: "list of glob paths to **only** compile" description: "list of glob paths to **only** compile",
}, },
code: { code: {
hidden: true, hidden: true,
default: true, default: true,
type: "boolean" type: "boolean",
}, },
metadata: { metadata: {
hidden: true, hidden: true,
default: true, default: true,
type: "boolean" type: "boolean",
}, },
ast: { ast: {
hidden: true, hidden: true,
default: true, default: true,
type: "boolean" type: "boolean",
}, },
extends: { extends: {
type: "string", type: "string",
hidden: true hidden: true,
}, },
comments: { comments: {
type: "boolean", type: "boolean",
default: true, default: true,
description: "write comments to generated output (true by default)" description: "write comments to generated output (true by default)",
}, },
shouldPrintComment: { shouldPrintComment: {
hidden: true, hidden: true,
description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored" description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored",
}, },
wrapPluginVisitorMethod: { wrapPluginVisitorMethod: {
hidden: true, hidden: true,
description: "optional callback to wrap all visitor methods" description: "optional callback to wrap all visitor methods",
}, },
compact: { compact: {
type: "booleanString", type: "booleanString",
default: "auto", default: "auto",
description: "do not include superfluous whitespace characters and line terminators [true|false|auto]" description: "do not include superfluous whitespace characters and line terminators [true|false|auto]",
}, },
minified: { minified: {
type: "boolean", type: "boolean",
default: false, default: false,
description: "save as much bytes when printing [true|false]" description: "save as much bytes when printing [true|false]",
}, },
sourceMap: { sourceMap: {
alias: "sourceMaps", alias: "sourceMaps",
hidden: true hidden: true,
}, },
sourceMaps: { sourceMaps: {
type: "booleanString", type: "booleanString",
description: "[true|false|inline]", description: "[true|false|inline]",
default: false, default: false,
shorthand: "s" shorthand: "s",
}, },
sourceMapTarget: { sourceMapTarget: {
type: "string", type: "string",
description: "set `file` on returned source map" description: "set `file` on returned source map",
}, },
sourceFileName: { sourceFileName: {
type: "string", type: "string",
description: "set `sources[0]` on returned source map" description: "set `sources[0]` on returned source map",
}, },
sourceRoot: { sourceRoot: {
type: "filename", type: "filename",
description: "the root from which all sources are relative" description: "the root from which all sources are relative",
}, },
babelrc: { babelrc: {
description: "Whether or not to look up .babelrc and .babelignore files", description: "Whether or not to look up .babelrc and .babelignore files",
type: "boolean", type: "boolean",
default: true default: true,
}, },
sourceType: { sourceType: {
description: "", description: "",
default: "module" default: "module",
}, },
auxiliaryCommentBefore: { auxiliaryCommentBefore: {
type: "string", type: "string",
description: "print a comment before any injected non-user code" description: "print a comment before any injected non-user code",
}, },
auxiliaryCommentAfter: { auxiliaryCommentAfter: {
type: "string", type: "string",
description: "print a comment after any injected non-user code" description: "print a comment after any injected non-user code",
}, },
resolveModuleSource: { resolveModuleSource: {
hidden: true hidden: true,
}, },
getModuleId: { getModuleId: {
hidden: true hidden: true,
}, },
moduleRoot: { moduleRoot: {
type: "filename", type: "filename",
description: "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions" description: "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions",
}, },
moduleIds: { moduleIds: {
type: "boolean", type: "boolean",
default: false, default: false,
shorthand: "M", shorthand: "M",
description: "insert an explicit id for modules" description: "insert an explicit id for modules",
}, },
moduleId: { moduleId: {
description: "specify a custom name for module ids", description: "specify a custom name for module ids",
type: "string" type: "string",
}, },
passPerPreset: { passPerPreset: {
@ -202,12 +202,12 @@ export default {
// Deprecate top level parserOpts // Deprecate top level parserOpts
parserOpts: { parserOpts: {
description: "Options to pass into the parser, or to change parsers (parserOpts.parser)", description: "Options to pass into the parser, or to change parsers (parserOpts.parser)",
default: false default: false,
}, },
// Deprecate top level generatorOpts // Deprecate top level generatorOpts
generatorOpts: { generatorOpts: {
description: "Options to pass into the generator, or to change generators (generatorOpts.generator)", description: "Options to pass into the generator, or to change generators (generatorOpts.generator)",
default: false default: false,
} },
}; };

View File

@ -67,7 +67,7 @@ export default class OptionManager {
const plugin = new Plugin(obj, alias); const plugin = new Plugin(obj, alias);
OptionManager.memoisedPlugins.push({ OptionManager.memoisedPlugins.push({
container: fn, container: fn,
plugin: plugin plugin: plugin,
}); });
return plugin; return plugin;
} else { } else {
@ -151,7 +151,7 @@ export default class OptionManager {
extending: extendingOpts, extending: extendingOpts,
alias, alias,
loc, loc,
dirname dirname,
}: MergeOptions) { }: MergeOptions) {
alias = alias || "foreign"; alias = alias || "foreign";
if (!rawOpts) return; if (!rawOpts) return;
@ -208,7 +208,7 @@ export default class OptionManager {
extending: preset, extending: preset,
alias: presetLoc, alias: presetLoc,
loc: presetLoc, loc: presetLoc,
dirname: dirname dirname: dirname,
}); });
}); });
} else { } else {
@ -238,7 +238,7 @@ export default class OptionManager {
options: presetOpts, options: presetOpts,
alias: presetLoc, alias: presetLoc,
loc: presetLoc, loc: presetLoc,
dirname: path.dirname(presetLoc || "") dirname: path.dirname(presetLoc || ""),
}); });
}); });
} }
@ -318,7 +318,7 @@ export default class OptionManager {
for (const key in config) { for (const key in config) {
const option = config[key]; const option = config[key];
const val = opts[key]; const val = opts[key];
// optional // optional
if (!val && option.optional) continue; if (!val && option.optional) continue;

View File

@ -2,34 +2,34 @@
export default { export default {
"auxiliaryComment": { "auxiliaryComment": {
"message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" "message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`",
}, },
"blacklist": { "blacklist": {
"message": "Put the specific transforms you want in the `plugins` option" "message": "Put the specific transforms you want in the `plugins` option",
}, },
"breakConfig": { "breakConfig": {
"message": "This is not a necessary option in Babel 6" "message": "This is not a necessary option in Babel 6",
}, },
"experimental": { "experimental": {
"message": "Put the specific transforms you want in the `plugins` option" "message": "Put the specific transforms you want in the `plugins` option",
}, },
"externalHelpers": { "externalHelpers": {
"message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/" "message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/",
}, },
"extra": { "extra": {
"message": "" "message": "",
}, },
"jsxPragma": { "jsxPragma": {
"message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/" "message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/",
}, },
// "keepModuleIdExtensions": { // "keepModuleIdExtensions": {
// "message": "" // "message": ""
// }, // },
"loose": { "loose": {
"message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option." "message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option.",
}, },
"metadataUsedHelpers": { "metadataUsedHelpers": {
"message": "Not required anymore as this is enabled by default" "message": "Not required anymore as this is enabled by default",
}, },
"modules": { "modules": {
"message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules", "message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules",
@ -38,15 +38,15 @@ export default {
"message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/", "message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/",
}, },
"optional": { "optional": {
"message": "Put the specific transforms you want in the `plugins` option" "message": "Put the specific transforms you want in the `plugins` option",
}, },
"sourceMapName": { "sourceMapName": {
"message": "Use the `sourceMapTarget` option" "message": "Use the `sourceMapTarget` option",
}, },
"stage": { "stage": {
"message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" "message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets",
}, },
"whitelist": { "whitelist": {
"message": "Put the specific transforms you want in the `plugins` option" "message": "Put the specific transforms you want in the `plugins` option",
} },
}; };

View File

@ -36,7 +36,7 @@ export default new Plugin({
// Higher priorities should move toward the top. // Higher priorities should move toward the top.
return -1 * priority; return -1 * priority;
}); });
} },
} },
} },
}); });

View File

@ -12,7 +12,7 @@ const superVisitor = {
node[SUPER_THIS_BOUND] = true; node[SUPER_THIS_BOUND] = true;
path.replaceWith(t.assignmentExpression("=", this.id, node)); path.replaceWith(t.assignmentExpression("=", this.id, node));
} },
}; };
export default new Plugin({ export default new Plugin({
@ -27,8 +27,8 @@ export default new Plugin({
if (path.node.name === "arguments") { if (path.node.name === "arguments") {
remap(path, "arguments"); remap(path, "arguments");
} }
} },
} },
}); });
function shouldShadow(path, shadowPath) { function shouldShadow(path, shadowPath) {
@ -94,7 +94,7 @@ function remap(path, key) {
const cached = fnPath.getData(key); const cached = fnPath.getData(key);
if (cached) return path.replaceWith(cached); if (cached) return path.replaceWith(cached);
const id = path.scope.generateUidIdentifier(key); const id = path.scope.generateUidIdentifier(key);
fnPath.setData(key, id); fnPath.setData(key, id);

View File

@ -6,9 +6,9 @@ export default class PluginPass extends Store {
constructor(file: File, plugin: Plugin, options: Object = {}) { constructor(file: File, plugin: Plugin, options: Object = {}) {
super(); super();
this.plugin = plugin; this.plugin = plugin;
this.key = plugin.key; this.key = plugin.key;
this.file = file; this.file = file;
this.opts = options; this.opts = options;
} }
key: string; key: string;

View File

@ -11,13 +11,13 @@ export default class Plugin extends Store {
super(); super();
this.initialized = false; this.initialized = false;
this.raw = Object.assign({}, plugin); this.raw = Object.assign({}, plugin);
this.key = this.take("name") || key; this.key = this.take("name") || key;
this.manipulateOptions = this.take("manipulateOptions"); this.manipulateOptions = this.take("manipulateOptions");
this.post = this.take("post"); this.post = this.take("post");
this.pre = this.take("pre"); this.pre = this.take("pre");
this.visitor = this.normaliseVisitor(clone(this.take("visitor")) || {}); this.visitor = this.normaliseVisitor(clone(this.take("visitor")) || {});
} }
initialized: boolean; initialized: boolean;

View File

@ -18,7 +18,7 @@ function transformAsync(code, opts) {
return { return {
then: function (resolve) { then: function (resolve) {
resolve(babel.transform(code, opts)); resolve(babel.transform(code, opts));
} },
}; };
} }
@ -29,7 +29,7 @@ describe("parser and generator options", function() {
}, },
print: function(ast) { print: function(ast) {
return generator(ast); return generator(ast);
} },
}; };
function newTransform(string) { function newTransform(string) {
@ -37,11 +37,11 @@ describe("parser and generator options", function() {
parserOpts: { parserOpts: {
parser: recast.parse, parser: recast.parse,
plugins: ["flow"], plugins: ["flow"],
allowImportExportEverywhere: true allowImportExportEverywhere: true,
}, },
generatorOpts: { generatorOpts: {
generator: recast.print generator: recast.print,
} },
}); });
} }
@ -56,8 +56,8 @@ describe("parser and generator options", function() {
assert.deepEqual(newTransform(experimental).ast, babel.transform(experimental, { assert.deepEqual(newTransform(experimental).ast, babel.transform(experimental, {
parserOpts: { parserOpts: {
plugins: ["flow"] plugins: ["flow"],
} },
}).ast); }).ast);
assert.equal(newTransform(experimental).code, experimental); assert.equal(newTransform(experimental).code, experimental);
@ -65,18 +65,18 @@ describe("parser and generator options", function() {
return babel.transform(string, { return babel.transform(string, {
plugins: [__dirname + "/../../babel-plugin-syntax-flow"], plugins: [__dirname + "/../../babel-plugin-syntax-flow"],
parserOpts: { parserOpts: {
parser: recast.parse parser: recast.parse,
}, },
generatorOpts: { generatorOpts: {
generator: recast.print generator: recast.print,
} },
}); });
} }
assert.deepEqual(newTransformWithPlugins(experimental).ast, babel.transform(experimental, { assert.deepEqual(newTransformWithPlugins(experimental).ast, babel.transform(experimental, {
parserOpts: { parserOpts: {
plugins: ["flow"] plugins: ["flow"],
} },
}).ast); }).ast);
assert.equal(newTransformWithPlugins(experimental).code, experimental); assert.equal(newTransformWithPlugins(experimental).code, experimental);
}); });
@ -86,8 +86,8 @@ describe("parser and generator options", function() {
assert.notEqual(newTransform(experimental).ast, babel.transform(experimental, { assert.notEqual(newTransform(experimental).ast, babel.transform(experimental, {
parserOpts: { parserOpts: {
allowImportExportEverywhere: true allowImportExportEverywhere: true,
} },
}).ast); }).ast);
assert.equal(newTransform(experimental).code, experimental); assert.equal(newTransform(experimental).code, experimental);
}); });
@ -102,15 +102,15 @@ describe("api", function () {
visitor: { visitor: {
Program: function (path) { Program: function (path) {
path.mark("category", "foobar"); path.mark("category", "foobar");
} },
} },
})] })],
}).marked[0].message, "foobar"); }).marked[0].message, "foobar");
assert.equal(babel.analyse("foobar;", {}, { assert.equal(babel.analyse("foobar;", {}, {
Program: function (path) { Program: function (path) {
path.mark("category", "foobar"); path.mark("category", "foobar");
} },
}).marked[0].message, "foobar"); }).marked[0].message, "foobar");
}); });
@ -138,7 +138,7 @@ describe("api", function () {
return assert.throws( return assert.throws(
function () { function () {
babel.transform("", { babel.transform("", {
plugins: [__dirname + "/../../babel-plugin-syntax-jsx", false] plugins: [__dirname + "/../../babel-plugin-syntax-jsx", false],
}); });
}, },
/TypeError: Falsy value found in plugins/ /TypeError: Falsy value found in plugins/
@ -148,7 +148,7 @@ describe("api", function () {
it("options merge backwards", function () { it("options merge backwards", function () {
return transformAsync("", { return transformAsync("", {
presets: [__dirname + "/../../babel-preset-es2015"], presets: [__dirname + "/../../babel-preset-es2015"],
plugins: [__dirname + "/../../babel-plugin-syntax-jsx"] plugins: [__dirname + "/../../babel-plugin-syntax-jsx"],
}).then(function (result) { }).then(function (result) {
assert.ok(result.options.plugins[0][0].manipulateOptions.toString().indexOf("jsx") >= 0); assert.ok(result.options.plugins[0][0].manipulateOptions.toString().indexOf("jsx") >= 0);
}); });
@ -177,9 +177,9 @@ describe("api", function () {
visitor: { visitor: {
"Program|Identifier": function () { "Program|Identifier": function () {
calledRaw++; calledRaw++;
} },
} },
})] })],
}); });
assert.equal(calledRaw, 4); assert.equal(calledRaw, 4);
@ -212,10 +212,10 @@ describe("api", function () {
// In case of `passPerPreset` being `true`, the // In case of `passPerPreset` being `true`, the
// alias node should still exist. // alias node should still exist.
aliasBaseType = alias.right.type; // NumberTypeAnnotation aliasBaseType = alias.right.type; // NumberTypeAnnotation
} },
} },
}) }),
] ],
}; };
}, },
@ -228,9 +228,9 @@ describe("api", function () {
plugins: [ plugins: [
require(__dirname + "/../../babel-plugin-syntax-flow"), require(__dirname + "/../../babel-plugin-syntax-flow"),
require(__dirname + "/../../babel-plugin-transform-flow-strip-types"), require(__dirname + "/../../babel-plugin-transform-flow-strip-types"),
] ],
}; };
} },
], ],
}); });
} }
@ -246,7 +246,7 @@ describe("api", function () {
"", "",
"var x = function x(y) {", "var x = function x(y) {",
" return y;", " return y;",
"};" "};",
].join("\n"), result.code); ].join("\n"), result.code);
// 2. passPerPreset: false // 2. passPerPreset: false
@ -262,7 +262,7 @@ describe("api", function () {
"", "",
"var x = function x(y) {", "var x = function x(y) {",
" return y;", " return y;",
"};" "};",
].join("\n"), result.code); ].join("\n"), result.code);
}); });
@ -276,10 +276,10 @@ describe("api", function () {
" _classCallCheck(this, Foo);", " _classCallCheck(this, Foo);",
"};", "};",
"", "",
"//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZG91dCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztJQUFNLEdBQUcsWUFBSCxHQUFHO3dCQUFILEdBQUciLCJmaWxlIjoidW5kZWZpbmVkIiwic291cmNlc0NvbnRlbnQiOlsiY2xhc3MgRm9vIHt9XG4iXX0=" "//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZG91dCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztJQUFNLEdBQUcsWUFBSCxHQUFHO3dCQUFILEdBQUciLCJmaWxlIjoidW5kZWZpbmVkIiwic291cmNlc0NvbnRlbnQiOlsiY2xhc3MgRm9vIHt9XG4iXX0=",
/* eslint-enable max-len */ /* eslint-enable max-len */
].join("\n"), { ].join("\n"), {
sourceMap: true sourceMap: true,
}); });
assert.deepEqual([ assert.deepEqual([
@ -291,19 +291,19 @@ describe("api", function () {
"", "",
"let Foo = function Foo() {", "let Foo = function Foo() {",
" _classCallCheck(this, Foo);", " _classCallCheck(this, Foo);",
"};" "};",
].join("\n"), result.code); ].join("\n"), result.code);
const consumer = new sourceMap.SourceMapConsumer(result.map); const consumer = new sourceMap.SourceMapConsumer(result.map);
assert.deepEqual(consumer.originalPositionFor({ assert.deepEqual(consumer.originalPositionFor({
line: 7, line: 7,
column: 4 column: 4,
}), { }), {
name: null, name: null,
source: "stdout", source: "stdout",
line: 1, line: 1,
column: 6 column: 6,
}); });
}); });
@ -330,10 +330,10 @@ describe("api", function () {
Program: function (path) { Program: function (path) {
path.unshiftContainer("body", t.expressionStatement(t.identifier("start"))); path.unshiftContainer("body", t.expressionStatement(t.identifier("start")));
path.pushContainer("body", t.expressionStatement(t.identifier("end"))); path.pushContainer("body", t.expressionStatement(t.identifier("end")));
} },
} },
}; };
}] }],
}).then(function (result) { }).then(function (result) {
assert.equal(result.code, assert.equal(result.code,
"/*before*/start;\n/*after*/class Foo {}\n/*before*/end;\n/*after*/"); "/*before*/start;\n/*after*/class Foo {}\n/*before*/end;\n/*after*/");
@ -350,8 +350,8 @@ describe("api", function () {
specifiers: [{ specifiers: [{
kind: "named", kind: "named",
imported: "externalName", imported: "externalName",
local: "localName" local: "localName",
}] }],
}); });
}), }),
@ -361,8 +361,8 @@ describe("api", function () {
imported: ["*"], imported: ["*"],
specifiers: [{ specifiers: [{
kind: "namespace", kind: "namespace",
local: "localName2" local: "localName2",
}] }],
}); });
}), }),
@ -373,15 +373,15 @@ describe("api", function () {
specifiers: [{ specifiers: [{
kind: "named", kind: "named",
imported: "default", imported: "default",
local: "localName3" local: "localName3",
}] }],
}); });
}), }),
transformAsync("import localName from \"./array\";", { transformAsync("import localName from \"./array\";", {
resolveModuleSource: function() { resolveModuleSource: function() {
return "override-source"; return "override-source";
} },
}).then(function (result) { }).then(function (result) {
assert.deepEqual(result.metadata.modules.imports, [ assert.deepEqual(result.metadata.modules.imports, [
{ {
@ -391,15 +391,15 @@ describe("api", function () {
{ {
"kind": "named", "kind": "named",
"imported": "default", "imported": "default",
"local": "localName" "local": "localName",
} },
] ],
} },
]); ]);
}), }),
transformAsync("export * as externalName1 from \"external\";", { transformAsync("export * as externalName1 from \"external\";", {
plugins: [require("../../babel-plugin-syntax-export-extensions")] plugins: [require("../../babel-plugin-syntax-export-extensions")],
}).then(function (result) { }).then(function (result) {
assert.deepEqual(result.metadata.modules.exports, { assert.deepEqual(result.metadata.modules.exports, {
exported: ["externalName1"], exported: ["externalName1"],
@ -407,12 +407,12 @@ describe("api", function () {
kind: "external-namespace", kind: "external-namespace",
exported: "externalName1", exported: "externalName1",
source: "external", source: "external",
}] }],
}); });
}), }),
transformAsync("export externalName2 from \"external\";", { transformAsync("export externalName2 from \"external\";", {
plugins: [require("../../babel-plugin-syntax-export-extensions")] plugins: [require("../../babel-plugin-syntax-export-extensions")],
}).then(function (result) { }).then(function (result) {
assert.deepEqual(result.metadata.modules.exports, { assert.deepEqual(result.metadata.modules.exports, {
exported: ["externalName2"], exported: ["externalName2"],
@ -420,8 +420,8 @@ describe("api", function () {
kind: "external", kind: "external",
local: "externalName2", local: "externalName2",
exported: "externalName2", exported: "externalName2",
source: "external" source: "external",
}] }],
}); });
}), }),
@ -431,8 +431,8 @@ describe("api", function () {
specifiers: [{ specifiers: [{
kind: "local", kind: "local",
local: "namedFunction", local: "namedFunction",
exported: "namedFunction" exported: "namedFunction",
}] }],
}); });
}), }),
@ -442,8 +442,8 @@ describe("api", function () {
specifiers: [{ specifiers: [{
kind: "local", kind: "local",
local: "foo", local: "foo",
exported: "foo" exported: "foo",
}] }],
}); });
}), }),
@ -453,8 +453,8 @@ describe("api", function () {
specifiers: [{ specifiers: [{
kind: "local", kind: "local",
local: "localName", local: "localName",
exported: "externalName3" exported: "externalName3",
}] }],
}); });
}), }),
@ -465,8 +465,8 @@ describe("api", function () {
kind: "external", kind: "external",
local: "externalName4", local: "externalName4",
exported: "externalName4", exported: "externalName4",
source: "external" source: "external",
}] }],
}); });
}), }),
@ -475,8 +475,8 @@ describe("api", function () {
exported: [], exported: [],
specifiers: [{ specifiers: [{
kind: "external-all", kind: "external-all",
source: "external" source: "external",
}] }],
}); });
}), }),
@ -486,10 +486,10 @@ describe("api", function () {
specifiers: [{ specifiers: [{
kind: "local", kind: "local",
local: "defaultFunction", local: "defaultFunction",
exported: "default" exported: "default",
}] }],
}); });
}) }),
]); ]);
}); });
@ -497,18 +497,18 @@ describe("api", function () {
return Promise.all([ return Promise.all([
transformAsync("", { transformAsync("", {
ignore: "node_modules", ignore: "node_modules",
filename: "/foo/node_modules/bar" filename: "/foo/node_modules/bar",
}).then(assertIgnored), }).then(assertIgnored),
transformAsync("", { transformAsync("", {
ignore: "foo/node_modules", ignore: "foo/node_modules",
filename: "/foo/node_modules/bar" filename: "/foo/node_modules/bar",
}).then(assertIgnored), }).then(assertIgnored),
transformAsync("", { transformAsync("", {
ignore: "foo/node_modules/*.bar", ignore: "foo/node_modules/*.bar",
filename: "/foo/node_modules/foo.bar" filename: "/foo/node_modules/foo.bar",
}).then(assertIgnored) }).then(assertIgnored),
]); ]);
}); });
@ -516,33 +516,33 @@ describe("api", function () {
return Promise.all([ return Promise.all([
transformAsync("", { transformAsync("", {
only: "node_modules", only: "node_modules",
filename: "/foo/node_modules/bar" filename: "/foo/node_modules/bar",
}).then(assertNotIgnored), }).then(assertNotIgnored),
transformAsync("", { transformAsync("", {
only: "foo/node_modules", only: "foo/node_modules",
filename: "/foo/node_modules/bar" filename: "/foo/node_modules/bar",
}).then(assertNotIgnored), }).then(assertNotIgnored),
transformAsync("", { transformAsync("", {
only: "foo/node_modules/*.bar", only: "foo/node_modules/*.bar",
filename: "/foo/node_modules/foo.bar" filename: "/foo/node_modules/foo.bar",
}).then(assertNotIgnored), }).then(assertNotIgnored),
transformAsync("", { transformAsync("", {
only: "node_modules", only: "node_modules",
filename: "/foo/node_module/bar" filename: "/foo/node_module/bar",
}).then(assertIgnored), }).then(assertIgnored),
transformAsync("", { transformAsync("", {
only: "foo/node_modules", only: "foo/node_modules",
filename: "/bar/node_modules/foo" filename: "/bar/node_modules/foo",
}).then(assertIgnored), }).then(assertIgnored),
transformAsync("", { transformAsync("", {
only: "foo/node_modules/*.bar", only: "foo/node_modules/*.bar",
filename: "/foo/node_modules/bar.foo" filename: "/foo/node_modules/bar.foo",
}).then(assertIgnored) }).then(assertIgnored),
]); ]);
}); });
@ -565,8 +565,8 @@ describe("api", function () {
it("default", function () { it("default", function () {
const result = babel.transform("foo;", { const result = babel.transform("foo;", {
env: { env: {
development: { code: false } development: { code: false },
} },
}); });
assert.equal(result.code, undefined); assert.equal(result.code, undefined);
@ -576,8 +576,8 @@ describe("api", function () {
process.env.BABEL_ENV = "foo"; process.env.BABEL_ENV = "foo";
const result = babel.transform("foo;", { const result = babel.transform("foo;", {
env: { env: {
foo: { code: false } foo: { code: false },
} },
}); });
assert.equal(result.code, undefined); assert.equal(result.code, undefined);
}); });
@ -586,8 +586,8 @@ describe("api", function () {
process.env.NODE_ENV = "foo"; process.env.NODE_ENV = "foo";
const result = babel.transform("foo;", { const result = babel.transform("foo;", {
env: { env: {
foo: { code: false } foo: { code: false },
} },
}); });
assert.equal(result.code, undefined); assert.equal(result.code, undefined);
}); });
@ -602,7 +602,7 @@ describe("api", function () {
return transformAsync(actual, { return transformAsync(actual, {
resolveModuleSource: function (originalSource) { resolveModuleSource: function (originalSource) {
return "resolved/" + originalSource; return "resolved/" + originalSource;
} },
}).then(function (result) { }).then(function (result) {
assert.equal(result.code.trim(), expected); assert.equal(result.code.trim(), expected);
}); });

View File

@ -29,48 +29,48 @@ describe("buildConfigChain", function () {
it("dir1", function () { it("dir1", function () {
const chain = buildConfigChain({ const chain = buildConfigChain({
filename: fixture("dir1", "src.js") filename: fixture("dir1", "src.js"),
}); });
const expected = [ const expected = [
{ {
options: { options: {
plugins: [ plugins: [
"extended" "extended",
] ],
}, },
alias: fixture("extended.babelrc.json"), alias: fixture("extended.babelrc.json"),
loc: fixture("extended.babelrc.json"), loc: fixture("extended.babelrc.json"),
dirname: fixture() dirname: fixture(),
}, },
{ {
options: { options: {
plugins: [ plugins: [
"root" "root",
] ],
}, },
alias: fixture(".babelrc"), alias: fixture(".babelrc"),
loc: fixture(".babelrc"), loc: fixture(".babelrc"),
dirname: fixture() dirname: fixture(),
}, },
{ {
options: { options: {
ignore: [ ignore: [
"root-ignore" "root-ignore",
] ],
}, },
alias: fixture(".babelignore"), alias: fixture(".babelignore"),
loc: fixture(".babelignore"), loc: fixture(".babelignore"),
dirname: fixture() dirname: fixture(),
}, },
{ {
options: { options: {
filename: fixture("dir1", "src.js") filename: fixture("dir1", "src.js"),
}, },
alias: "base", alias: "base",
loc: "base", loc: "base",
dirname: fixture("dir1") dirname: fixture("dir1"),
} },
]; ];
assert.deepEqual(chain, expected); assert.deepEqual(chain, expected);
@ -78,38 +78,38 @@ describe("buildConfigChain", function () {
it("dir2", function () { it("dir2", function () {
const chain = buildConfigChain({ const chain = buildConfigChain({
filename: fixture("dir2", "src.js") filename: fixture("dir2", "src.js"),
}); });
const expected = [ const expected = [
{ {
options: { options: {
plugins: [ plugins: [
"dir2" "dir2",
] ],
}, },
alias: fixture("dir2", ".babelrc"), alias: fixture("dir2", ".babelrc"),
loc: fixture("dir2", ".babelrc"), loc: fixture("dir2", ".babelrc"),
dirname: fixture("dir2") dirname: fixture("dir2"),
}, },
{ {
options: { options: {
ignore: [ ignore: [
"root-ignore" "root-ignore",
] ],
}, },
alias: fixture(".babelignore"), alias: fixture(".babelignore"),
loc: fixture(".babelignore"), loc: fixture(".babelignore"),
dirname: fixture() dirname: fixture(),
}, },
{ {
options: { options: {
filename: fixture("dir2", "src.js") filename: fixture("dir2", "src.js"),
}, },
alias: "base", alias: "base",
loc: "base", loc: "base",
dirname: fixture("dir2") dirname: fixture("dir2"),
} },
]; ];
assert.deepEqual(chain, expected); assert.deepEqual(chain, expected);
@ -117,38 +117,38 @@ describe("buildConfigChain", function () {
it("env - base", function () { it("env - base", function () {
const chain = buildConfigChain({ const chain = buildConfigChain({
filename: fixture("env", "src.js") filename: fixture("env", "src.js"),
}); });
const expected = [ const expected = [
{ {
options: { options: {
plugins: [ plugins: [
"env-base" "env-base",
] ],
}, },
alias: fixture("env", ".babelrc"), alias: fixture("env", ".babelrc"),
loc: fixture("env", ".babelrc"), loc: fixture("env", ".babelrc"),
dirname: fixture("env") dirname: fixture("env"),
}, },
{ {
options: { options: {
ignore: [ ignore: [
"root-ignore" "root-ignore",
] ],
}, },
alias: fixture(".babelignore"), alias: fixture(".babelignore"),
loc: fixture(".babelignore"), loc: fixture(".babelignore"),
dirname: fixture() dirname: fixture(),
}, },
{ {
options: { options: {
filename: fixture("env", "src.js") filename: fixture("env", "src.js"),
}, },
alias: "base", alias: "base",
loc: "base", loc: "base",
dirname: fixture("env") dirname: fixture("env"),
} },
]; ];
assert.deepEqual(chain, expected); assert.deepEqual(chain, expected);
@ -158,48 +158,48 @@ describe("buildConfigChain", function () {
process.env.NODE_ENV = "foo"; process.env.NODE_ENV = "foo";
const chain = buildConfigChain({ const chain = buildConfigChain({
filename: fixture("env", "src.js") filename: fixture("env", "src.js"),
}); });
const expected = [ const expected = [
{ {
options: { options: {
plugins: [ plugins: [
"env-base" "env-base",
] ],
}, },
alias: fixture("env", ".babelrc"), alias: fixture("env", ".babelrc"),
loc: fixture("env", ".babelrc"), loc: fixture("env", ".babelrc"),
dirname: fixture("env") dirname: fixture("env"),
}, },
{ {
options: { options: {
plugins: [ plugins: [
"env-foo" "env-foo",
] ],
}, },
alias: fixture("env", ".babelrc.env.foo"), alias: fixture("env", ".babelrc.env.foo"),
loc: fixture("env", ".babelrc.env.foo"), loc: fixture("env", ".babelrc.env.foo"),
dirname: fixture("env") dirname: fixture("env"),
}, },
{ {
options: { options: {
ignore: [ ignore: [
"root-ignore" "root-ignore",
] ],
}, },
alias: fixture(".babelignore"), alias: fixture(".babelignore"),
loc: fixture(".babelignore"), loc: fixture(".babelignore"),
dirname: fixture() dirname: fixture(),
}, },
{ {
options: { options: {
filename: fixture("env", "src.js") filename: fixture("env", "src.js"),
}, },
alias: "base", alias: "base",
loc: "base", loc: "base",
dirname: fixture("env") dirname: fixture("env"),
} },
]; ];
assert.deepEqual(chain, expected); assert.deepEqual(chain, expected);
@ -210,48 +210,48 @@ describe("buildConfigChain", function () {
process.env.NODE_ENV = "bar"; process.env.NODE_ENV = "bar";
const chain = buildConfigChain({ const chain = buildConfigChain({
filename: fixture("env", "src.js") filename: fixture("env", "src.js"),
}); });
const expected = [ const expected = [
{ {
options: { options: {
plugins: [ plugins: [
"env-base" "env-base",
] ],
}, },
alias: fixture("env", ".babelrc"), alias: fixture("env", ".babelrc"),
loc: fixture("env", ".babelrc"), loc: fixture("env", ".babelrc"),
dirname: fixture("env") dirname: fixture("env"),
}, },
{ {
options: { options: {
plugins: [ plugins: [
"env-bar" "env-bar",
] ],
}, },
alias: fixture("env", ".babelrc.env.bar"), alias: fixture("env", ".babelrc.env.bar"),
loc: fixture("env", ".babelrc.env.bar"), loc: fixture("env", ".babelrc.env.bar"),
dirname: fixture("env") dirname: fixture("env"),
}, },
{ {
options: { options: {
ignore: [ ignore: [
"root-ignore" "root-ignore",
] ],
}, },
alias: fixture(".babelignore"), alias: fixture(".babelignore"),
loc: fixture(".babelignore"), loc: fixture(".babelignore"),
dirname: fixture() dirname: fixture(),
}, },
{ {
options: { options: {
filename: fixture("env", "src.js") filename: fixture("env", "src.js"),
}, },
alias: "base", alias: "base",
loc: "base", loc: "base",
dirname: fixture("env") dirname: fixture("env"),
} },
]; ];
assert.deepEqual(chain, expected); assert.deepEqual(chain, expected);
@ -262,34 +262,34 @@ describe("buildConfigChain", function () {
process.env.NODE_ENV = "foo"; process.env.NODE_ENV = "foo";
const chain = buildConfigChain({ const chain = buildConfigChain({
filename: fixture("pkg", "src.js") filename: fixture("pkg", "src.js"),
}); });
const expected = [ const expected = [
{ {
options: { options: {
plugins: ["pkg-plugin"] plugins: ["pkg-plugin"],
}, },
alias: fixture("pkg", "package.json"), alias: fixture("pkg", "package.json"),
loc: fixture("pkg", "package.json"), loc: fixture("pkg", "package.json"),
dirname: fixture("pkg") dirname: fixture("pkg"),
}, },
{ {
options: { options: {
ignore: ["pkg-ignore"] ignore: ["pkg-ignore"],
}, },
alias: fixture("pkg", ".babelignore"), alias: fixture("pkg", ".babelignore"),
loc: fixture("pkg", ".babelignore"), loc: fixture("pkg", ".babelignore"),
dirname: fixture("pkg") dirname: fixture("pkg"),
}, },
{ {
options: { options: {
filename: fixture("pkg", "src.js") filename: fixture("pkg", "src.js"),
}, },
alias: "base", alias: "base",
loc: "base", loc: "base",
dirname: fixture("pkg") dirname: fixture("pkg"),
} },
]; ];
assert.deepEqual(chain, expected); assert.deepEqual(chain, expected);

View File

@ -14,7 +14,7 @@ describe("evaluation", function () {
}; };
traverse(parse(code, { traverse(parse(code, {
plugins: ["*"] plugins: ["*"],
}), visitor); }), visitor);
}); });
} }

View File

@ -10,13 +10,13 @@ describe("getPossiblePresetNames", function () {
assert.deepEqual(getPossiblePresetNames("@babel/es2015"), [ assert.deepEqual(getPossiblePresetNames("@babel/es2015"), [
"babel-preset-@babel/es2015", "babel-preset-@babel/es2015",
"@babel/es2015", "@babel/es2015",
"@babel/babel-preset-es2015" "@babel/babel-preset-es2015",
]); ]);
assert.deepEqual(getPossiblePresetNames("@babel/react/optimizations"), [ assert.deepEqual(getPossiblePresetNames("@babel/react/optimizations"), [
"babel-preset-@babel/react/optimizations", "babel-preset-@babel/react/optimizations",
"@babel/react/optimizations", "@babel/react/optimizations",
"@babel/babel-preset-react/optimizations" "@babel/babel-preset-react/optimizations",
]); ]);
}); });
}); });

View File

@ -19,7 +19,7 @@ describe("option-manager", () => {
() => { () => {
const opt = new OptionManager(new Logger(null, "unknown")); const opt = new OptionManager(new Logger(null, "unknown"));
opt.init({ opt.init({
"randomOption": true "randomOption": true,
}); });
}, },
/Unknown option: base.randomOption/ /Unknown option: base.randomOption/
@ -32,7 +32,7 @@ describe("option-manager", () => {
const opt = new OptionManager(new Logger(null, "unknown")); const opt = new OptionManager(new Logger(null, "unknown"));
opt.init({ opt.init({
"auxiliaryComment": true, "auxiliaryComment": true,
"blacklist": true "blacklist": true,
}); });
}, },
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
@ -45,7 +45,7 @@ describe("option-manager", () => {
() => { () => {
const opt = new OptionManager(new Logger(null, "unknown")); const opt = new OptionManager(new Logger(null, "unknown"));
opt.init({ 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/ /While processing preset: .*option-manager(?:\/|\\\\)not-a-preset\.js/
@ -58,7 +58,7 @@ describe("option-manager", () => {
it(name, function () { it(name, function () {
const opt = new OptionManager(new Logger(null, "unknown")); const opt = new OptionManager(new Logger(null, "unknown"));
const options = opt.init({ const options = opt.init({
"presets": [path.join(__dirname, "fixtures/option-manager/presets", name)] "presets": [path.join(__dirname, "fixtures/option-manager/presets", name)],
}); });
assert.equal(true, Array.isArray(options.plugins)); assert.equal(true, Array.isArray(options.plugins));
@ -70,7 +70,7 @@ describe("option-manager", () => {
it(name, function () { it(name, function () {
const opt = new OptionManager(new Logger(null, "unknown")); const opt = new OptionManager(new Logger(null, "unknown"));
assert.throws(() => opt.init({ assert.throws(() => opt.init({
"presets": [path.join(__dirname, "fixtures/option-manager/presets", name)] "presets": [path.join(__dirname, "fixtures/option-manager/presets", name)],
}), msg); }), msg);
}); });
} }

View File

@ -11,9 +11,9 @@ describe("traversal path", function () {
visitor: { visitor: {
FunctionDeclaration: function (path) { FunctionDeclaration: function (path) {
path.replaceWithSourceString("console.whatever()"); path.replaceWithSourceString("console.whatever()");
} },
} },
})] })],
}).code; }).code;
chai.expect(actualCode).to.be.equal("console.whatever();"); chai.expect(actualCode).to.be.equal("console.whatever();");
@ -32,13 +32,13 @@ describe("traversal path", function () {
type: "ReturnStatement", type: "ReturnStatement",
argument: { argument: {
type: "BooleanLiteral", type: "BooleanLiteral",
value: true value: true,
} },
}] }],
}); });
} },
} },
})] })],
}).code; }).code;
chai.expect(actualCode).to.be.equal("var fn = () => {\n return true;\n};"); chai.expect(actualCode).to.be.equal("var fn = () => {\n return true;\n};");
@ -53,11 +53,11 @@ describe("traversal path", function () {
ArrowFunctionExpression: function (path) { ArrowFunctionExpression: function (path) {
path.get("body").replaceWith({ path.get("body").replaceWith({
type: "BooleanLiteral", type: "BooleanLiteral",
value: true value: true,
}); });
} },
} },
})] })],
}).code; }).code;
chai.expect(actualCode).to.be.equal("var fn = () => true;"); chai.expect(actualCode).to.be.equal("var fn = () => true;");
@ -77,13 +77,13 @@ describe("traversal path", function () {
type: "VariableDeclarator", type: "VariableDeclarator",
id: { id: {
type: "Identifier", type: "Identifier",
name: "KEY" name: "KEY",
} },
}] }],
}); });
} },
} },
})] })],
}).code; }).code;
chai.expect(actualCode).to.be.equal("for (var KEY in right);"); chai.expect(actualCode).to.be.equal("for (var KEY in right);");
@ -98,11 +98,11 @@ describe("traversal path", function () {
ForInStatement: function (path) { ForInStatement: function (path) {
path.get("left").replaceWith({ path.get("left").replaceWith({
type: "Identifier", type: "Identifier",
name: "KEY" name: "KEY",
}); });
} },
} },
})] })],
}).code; }).code;
chai.expect(actualCode).to.be.equal("for (KEY in right);"); chai.expect(actualCode).to.be.equal("for (KEY in right);");
@ -122,13 +122,13 @@ describe("traversal path", function () {
type: "VariableDeclarator", type: "VariableDeclarator",
id: { id: {
type: "Identifier", type: "Identifier",
name: "KEY" name: "KEY",
} },
}] }],
}); });
} },
} },
})] })],
}).code; }).code;
chai.expect(actualCode).to.be.equal("for (var KEY;;);"); chai.expect(actualCode).to.be.equal("for (var KEY;;);");
@ -143,11 +143,11 @@ describe("traversal path", function () {
ForStatement: function (path) { ForStatement: function (path) {
path.get("init").replaceWith({ path.get("init").replaceWith({
type: "Identifier", type: "Identifier",
name: "KEY" name: "KEY",
}); });
} },
} },
})] })],
}).code; }).code;
chai.expect(actualCode).to.be.equal("for (KEY;;);"); chai.expect(actualCode).to.be.equal("for (KEY;;);");

View File

@ -188,7 +188,7 @@ export function BindExpression(node: Object) {
export { export {
AssignmentExpression as BinaryExpression, AssignmentExpression as BinaryExpression,
AssignmentExpression as LogicalExpression AssignmentExpression as LogicalExpression,
}; };
export function MemberExpression(node: Object) { export function MemberExpression(node: Object) {

View File

@ -280,7 +280,7 @@ export function ObjectTypeAnnotation(node: Object) {
this.token(","); this.token(",");
this.space(); this.space();
} }
} },
}); });
this.space(); this.space();

View File

@ -7,7 +7,7 @@ export function _params(node: Object) {
iterator: (node) => { iterator: (node) => {
if (node.optional) this.token("?"); if (node.optional) this.token("?");
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation, node);
} },
}); });
this.token(")"); this.token(")");
@ -18,7 +18,7 @@ export function _params(node: Object) {
export function _method(node: Object) { export function _method(node: Object) {
const kind = node.kind; const kind = node.kind;
const key = node.key; const key = node.key;
if (kind === "method" || kind === "init") { if (kind === "method" || kind === "init") {
if (node.generator) { if (node.generator) {

View File

@ -133,9 +133,9 @@ function buildLabelStatement(prefix, key = "label") {
} }
export const ContinueStatement = buildLabelStatement("continue"); export const ContinueStatement = buildLabelStatement("continue");
export const ReturnStatement = buildLabelStatement("return", "argument"); export const ReturnStatement = buildLabelStatement("return", "argument");
export const BreakStatement = buildLabelStatement("break"); export const BreakStatement = buildLabelStatement("break");
export const ThrowStatement = buildLabelStatement("throw", "argument"); export const ThrowStatement = buildLabelStatement("throw", "argument");
export function LabeledStatement(node: Object) { export function LabeledStatement(node: Object) {
this.print(node.label, node); this.print(node.label, node);
@ -190,7 +190,7 @@ export function SwitchStatement(node: Object) {
indent: true, indent: true,
addNewlines(leading, cas) { addNewlines(leading, cas) {
if (!leading && node.cases[node.cases.length - 1] === cas) return -1; if (!leading && node.cases[node.cases.length - 1] === cas) return -1;
} },
}); });
this.token("}"); this.token("}");

View File

@ -69,7 +69,7 @@ export function ObjectProperty(node: Object) {
export function ArrayExpression(node: Object) { export function ArrayExpression(node: Object) {
const elems = node.elements; const elems = node.elements;
const len = elems.length; const len = elems.length;
this.token("["); this.token("[");
this.printInnerComments(node); this.printInnerComments(node);
@ -129,7 +129,7 @@ export function StringLiteral(node: Object, parent: Object) {
// ensure the output is ASCII-safe // ensure the output is ASCII-safe
const opts = { const opts = {
quotes: t.isJSX(parent) ? "double" : this.format.quotes, quotes: t.isJSX(parent) ? "double" : this.format.quotes,
wrap: true wrap: true,
}; };
if (this.format.jsonCompatibleStrings) { if (this.format.jsonCompatibleStrings) {
opts.json = true; opts.json = true;

View File

@ -63,8 +63,8 @@ function normalizeOptions(code, opts, tokens): Format {
indent: { indent: {
adjustMultilineComment: true, adjustMultilineComment: true,
style: style, style: style,
base: 0 base: 0,
} },
}; };
if (format.minified) { if (format.minified) {
@ -102,7 +102,7 @@ function findCommonStringDelimiter(code, tokens) {
const occurences = { const occurences = {
single: 0, single: 0,
double: 0 double: 0,
}; };
let checked = 0; let checked = 0;

View File

@ -24,7 +24,7 @@ const PRECEDENCE = {
"*": 9, "*": 9,
"/": 9, "/": 9,
"%": 9, "%": 9,
"**": 10 "**": 10,
}; };
export function NullableTypeAnnotation(node: Object, parent: Object): boolean { export function NullableTypeAnnotation(node: Object, parent: Object): boolean {
@ -64,7 +64,7 @@ export function Binary(node: Object, parent: Object): boolean {
} }
if (t.isBinary(parent)) { if (t.isBinary(parent)) {
const parentOp = parent.operator; const parentOp = parent.operator;
const parentPos = PRECEDENCE[parentOp]; const parentPos = PRECEDENCE[parentOp];
const nodeOp = node.operator; const nodeOp = node.operator;
@ -220,7 +220,7 @@ export function AssignmentExpression(node: Object): boolean {
// in statement. // in statement.
function isFirstInStatement(printStack: Array<Object>, { function isFirstInStatement(printStack: Array<Object>, {
considerArrow = false, considerArrow = false,
considerDefaultExports = false considerDefaultExports = false,
} = {}): boolean { } = {}): boolean {
let i = printStack.length - 1; let i = printStack.length - 1;
let node = printStack[i]; let node = printStack[i];

View File

@ -71,7 +71,7 @@ export const nodes = {
if ((state.hasCall && state.hasHelper) || state.hasFunction) { if ((state.hasCall && state.hasHelper) || state.hasFunction) {
return { return {
before: state.hasFunction, before: state.hasFunction,
after: true after: true,
}; };
} }
}, },
@ -82,7 +82,7 @@ export const nodes = {
SwitchCase(node: Object, parent: Object): ?WhitespaceObject { SwitchCase(node: Object, parent: Object): ?WhitespaceObject {
return { return {
before: node.consequent.length || parent.cases[0] === node before: node.consequent.length || parent.cases[0] === node,
}; };
}, },
@ -93,7 +93,7 @@ export const nodes = {
LogicalExpression(node: Object): ?WhitespaceObject { LogicalExpression(node: Object): ?WhitespaceObject {
if (t.isFunction(node.left) || t.isFunction(node.right)) { if (t.isFunction(node.left) || t.isFunction(node.right)) {
return { return {
after: true after: true,
}; };
} }
}, },
@ -105,7 +105,7 @@ export const nodes = {
Literal(node: Object): ?WhitespaceObject { Literal(node: Object): ?WhitespaceObject {
if (node.value === "use strict") { if (node.value === "use strict") {
return { return {
after: true after: true,
}; };
} }
}, },
@ -118,7 +118,7 @@ export const nodes = {
if (t.isFunction(node.callee) || isHelper(node)) { if (t.isFunction(node.callee) || isHelper(node)) {
return { return {
before: true, before: true,
after: true after: true,
}; };
} }
}, },
@ -140,7 +140,7 @@ export const nodes = {
if (enabled) { if (enabled) {
return { return {
before: true, before: true,
after: true after: true,
}; };
} }
} }
@ -154,10 +154,10 @@ export const nodes = {
if (t.isBlockStatement(node.consequent)) { if (t.isBlockStatement(node.consequent)) {
return { return {
before: true, before: true,
after: true after: true,
}; };
} }
} },
}; };
/** /**
@ -169,7 +169,7 @@ nodes.ObjectTypeProperty =
nodes.ObjectMethod = function (node: Object, parent): ?WhitespaceObject { nodes.ObjectMethod = function (node: Object, parent): ?WhitespaceObject {
if (parent.properties[0] === node) { if (parent.properties[0] === node) {
return { return {
before: true before: true,
}; };
} }
}; };
@ -202,7 +202,7 @@ export const list = {
ObjectExpression(node: Object): Array<Object> { ObjectExpression(node: Object): Array<Object> {
return node.properties; return node.properties;
} },
}; };
/** /**
@ -215,7 +215,7 @@ export const list = {
["Loop", true], ["Loop", true],
["LabeledStatement", true], ["LabeledStatement", true],
["SwitchStatement", true], ["SwitchStatement", true],
["TryStatement", true] ["TryStatement", true],
].forEach(function ([type, amounts]) { ].forEach(function ([type, amounts]) {
if (typeof amounts === "boolean") { if (typeof amounts === "boolean") {
amounts = { after: amounts, before: amounts }; amounts = { after: amounts, before: amounts };

View File

@ -295,7 +295,7 @@ export default class Printer {
startTerminatorless(): Object { startTerminatorless(): Object {
return this._parenPushNewlineState = { return this._parenPushNewlineState = {
printed: false printed: false,
}; };
} }
@ -370,7 +370,7 @@ export default class Printer {
if (comment) { if (comment) {
this._printComment({ this._printComment({
type: "CommentBlock", type: "CommentBlock",
value: comment value: comment,
}); });
} }
} }
@ -383,7 +383,7 @@ export default class Printer {
if (comment) { if (comment) {
this._printComment({ this._printComment({
type: "CommentBlock", type: "CommentBlock",
value: comment value: comment,
}); });
} }
} }

View File

@ -5,7 +5,7 @@
export default class Whitespace { export default class Whitespace {
constructor(tokens) { constructor(tokens) {
this.tokens = tokens; this.tokens = tokens;
this.used = {}; this.used = {};
} }
/** /**
@ -59,7 +59,7 @@ export default class Whitespace {
if (!endToken || !endToken.loc) return 0; if (!endToken || !endToken.loc) return 0;
const start = startToken ? startToken.loc.end.line : 1; const start = startToken ? startToken.loc.end.line : 1;
const end = endToken.loc.start.line; const end = endToken.loc.start.line;
let lines = 0; let lines = 0;
for (let line = start; line < end; line++) { for (let line = start; line < end; line++) {

View File

@ -24,7 +24,7 @@ describe("generation", function () {
it("multiple sources", function () { it("multiple sources", function () {
const sources = { const sources = {
"a.js": "function hi (msg) { console.log(msg); }\n", "a.js": "function hi (msg) { console.log(msg); }\n",
"b.js": "hi('hello');\n" "b.js": "hi('hello');\n",
}; };
const parsed = Object.keys(sources).reduce(function (_parsed, filename) { const parsed = Object.keys(sources).reduce(function (_parsed, filename) {
_parsed[filename] = parse(sources[filename], { sourceFilename: filename }); _parsed[filename] = parse(sources[filename], { sourceFilename: filename });
@ -36,8 +36,8 @@ describe("generation", function () {
"program": { "program": {
"type": "Program", "type": "Program",
"sourceType": "module", "sourceType": "module",
"body": [].concat(parsed["a.js"].program.body, parsed["b.js"].program.body) "body": [].concat(parsed["a.js"].program.body, parsed["b.js"].program.body),
} },
}; };
const generated = generate(combinedAst, { sourceMaps: true }, sources); const generated = generate(combinedAst, { sourceMaps: true }, sources);
@ -54,8 +54,8 @@ describe("generation", function () {
], ],
sourcesContent: [ sourcesContent: [
"function hi (msg) { console.log(msg); }\n", "function hi (msg) { console.log(msg); }\n",
"hi('hello');\n" "hi('hello');\n",
] ],
}, "sourcemap was incorrectly generated"); }, "sourcemap was incorrectly generated");
chai.expect(generated.rawMappings).to.deep.equal([ chai.expect(generated.rawMappings).to.deep.equal([
@ -144,7 +144,7 @@ describe("generation", function () {
const generated = generate(ast, { const generated = generate(ast, {
filename: "inline", filename: "inline",
sourceFileName: "inline", sourceFileName: "inline",
sourceMaps: true sourceMaps: true,
}, code); }, code);
chai.expect(generated.map).to.deep.equal({ chai.expect(generated.map).to.deep.equal({
@ -152,7 +152,7 @@ describe("generation", function () {
sources: ["inline"], sources: ["inline"],
names: ["foo", "bar" ], names: ["foo", "bar" ],
mappings: "AAAA,SAASA,IAAT,GAAe;AAAEC;AAAM", mappings: "AAAA,SAASA,IAAT,GAAe;AAAEC;AAAM",
sourcesContent: [ "function foo() { bar; }\n" ] sourcesContent: [ "function foo() { bar; }\n" ],
}, "sourcemap was incorrectly generated"); }, "sourcemap was incorrectly generated");
chai.expect(generated.rawMappings).to.deep.equal([ chai.expect(generated.rawMappings).to.deep.equal([
@ -240,7 +240,7 @@ describe("programmatic generation", function() {
assert.equal(output, [ assert.equal(output, [
"{", "{",
" \"use strict\";", " \"use strict\";",
"}" "}",
].join("\n")); ].join("\n"));
}); });

View File

@ -22,7 +22,7 @@ export default function (opts: {
const expr = path.node.expression; const expr = path.node.expression;
if (!isAssignment(expr)) return; if (!isAssignment(expr)) return;
const nodes = []; const nodes = [];
const exploded = explode(expr.left, nodes, file, path.scope, true); const exploded = explode(expr.left, nodes, file, path.scope, true);
nodes.push(t.expressionStatement( nodes.push(t.expressionStatement(
@ -36,7 +36,7 @@ export default function (opts: {
const { node, scope } = path; const { node, scope } = path;
if (!isAssignment(node)) return; if (!isAssignment(node)) return;
const nodes = []; const nodes = [];
const exploded = explode(node.left, nodes, file, scope); const exploded = explode(node.left, nodes, file, scope);
nodes.push(buildAssignment(exploded.ref, opts.build(exploded.uid, node.right))); nodes.push(buildAssignment(exploded.ref, opts.build(exploded.uid, node.right)));
path.replaceWithMultiple(nodes); path.replaceWithMultiple(nodes);

View File

@ -35,7 +35,7 @@ export default function (
const node = path.node; const node = path.node;
if (!opts.is(node, file)) return; if (!opts.is(node, file)) return;
const nodes = []; const nodes = [];
const exploded = explode(node.left, nodes, file, path.scope); const exploded = explode(node.left, nodes, file, path.scope);
nodes.push(t.logicalExpression( nodes.push(t.logicalExpression(

View File

@ -28,7 +28,7 @@ export default function (opts) {
} }
path.replaceWith(t.inherits(callExpr, path.node)); path.replaceWith(t.inherits(callExpr, path.node));
} },
}; };
return visitor; return visitor;
@ -92,7 +92,7 @@ export default function (opts) {
const state: ElementState = { const state: ElementState = {
tagExpr: tagExpr, tagExpr: tagExpr,
tagName: tagName, tagName: tagName,
args: args args: args,
}; };
if (opts.pre) { if (opts.pre) {

View File

@ -15,7 +15,7 @@ const visitor = {
Function(path) { Function(path) {
path.skip(); path.skip();
} },
}; };
export default function (path: NodePath, scope = path.scope) { export default function (path: NodePath, scope = path.scope) {
@ -23,14 +23,14 @@ export default function (path: NodePath, scope = path.scope) {
const container = t.functionExpression(null, [], node.body, node.generator, node.async); const container = t.functionExpression(null, [], node.body, node.generator, node.async);
let callee = container; let callee = container;
let args = []; let args = [];
// todo: only hoist if necessary // todo: only hoist if necessary
hoistVariables(path, (id) => scope.push({ id })); hoistVariables(path, (id) => scope.push({ id }));
const state = { const state = {
foundThis: false, foundThis: false,
foundArguments: false foundArguments: false,
}; };
path.traverse(visitor, state); path.traverse(visitor, state);

View File

@ -33,7 +33,7 @@ function getObjRef(node, nodes, file, scope) {
const temp = scope.generateUidIdentifierBasedOnNode(ref); const temp = scope.generateUidIdentifierBasedOnNode(ref);
nodes.push(t.variableDeclaration("var", [ nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(temp, ref) t.variableDeclarator(temp, ref),
])); ]));
return temp; return temp;
} }
@ -45,7 +45,7 @@ function getPropRef(node, nodes, file, scope) {
const temp = scope.generateUidIdentifierBasedOnNode(prop); const temp = scope.generateUidIdentifierBasedOnNode(prop);
nodes.push(t.variableDeclaration("var", [ nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(temp, prop) t.variableDeclarator(temp, prop),
])); ]));
return temp; return temp;
} }
@ -80,6 +80,6 @@ export default function (
return { return {
uid: uid, uid: uid,
ref: ref ref: ref,
}; };
} }

View File

@ -64,7 +64,7 @@ export default function get(entryLoc): Array<Suite> {
options: clone(rootOpts), options: clone(rootOpts),
tests: [], tests: [],
title: humanize(suiteName), title: humanize(suiteName),
filename: entryLoc + "/" + suiteName filename: entryLoc + "/" + suiteName,
}; };
assertDirectory(suite.filename); assertDirectory(suite.filename);
@ -80,11 +80,11 @@ export default function get(entryLoc): Array<Suite> {
function push(taskName, taskDir) { function push(taskName, taskDir) {
const actualLocAlias = suiteName + "/" + taskName + "/actual.js"; const actualLocAlias = suiteName + "/" + taskName + "/actual.js";
let expectLocAlias = suiteName + "/" + taskName + "/expected.js"; let expectLocAlias = suiteName + "/" + taskName + "/expected.js";
const execLocAlias = suiteName + "/" + taskName + "/exec.js"; const execLocAlias = suiteName + "/" + taskName + "/exec.js";
const actualLoc = taskDir + "/actual.js"; const actualLoc = taskDir + "/actual.js";
let expectLoc = taskDir + "/expected.js"; let expectLoc = taskDir + "/expected.js";
let execLoc = taskDir + "/exec.js"; let execLoc = taskDir + "/exec.js";
if (fs.statSync(taskDir).isFile()) { if (fs.statSync(taskDir).isFile()) {
const ext = path.extname(taskDir); const ext = path.extname(taskDir);
@ -121,8 +121,8 @@ export default function get(entryLoc): Array<Suite> {
expect: { expect: {
loc: expectLoc, loc: expectLoc,
code: readFile(expectLoc), code: readFile(expectLoc),
filename: expectLocAlias filename: expectLocAlias,
} },
}; };
// traceur checks // traceur checks

View File

@ -42,7 +42,7 @@ const visitor = {
state.selfReference = true; state.selfReference = true;
path.stop(); path.stop();
} },
}; };
function wrap(state, method, id, scope) { function wrap(state, method, id, scope) {
@ -60,7 +60,7 @@ function wrap(state, method, id, scope) {
const template = build({ const template = build({
FUNCTION: method, FUNCTION: method,
FUNCTION_ID: id, FUNCTION_ID: id,
FUNCTION_KEY: scope.generateUidIdentifier(id.name) FUNCTION_KEY: scope.generateUidIdentifier(id.name),
}).expression; }).expression;
template.callee._skipModulesRemap = true; template.callee._skipModulesRemap = true;
@ -82,10 +82,10 @@ function wrap(state, method, id, scope) {
function visit(node, name, scope) { function visit(node, name, scope) {
const state = { const state = {
selfAssignment: false, selfAssignment: false,
selfReference: false, selfReference: false,
outerDeclar: scope.getBindingIdentifier(name), outerDeclar: scope.getBindingIdentifier(name),
references: [], references: [],
name: name name: name,
}; };
// check to see if we have a local binding of the id we're setting inside of // check to see if we have a local binding of the id we're setting inside of

View File

@ -37,7 +37,7 @@ const visitor = {
} else { } else {
path.replaceWithMultiple(nodes); path.replaceWithMultiple(nodes);
} }
} },
}; };
export default function (path, emit: Function, kind: "var" | "let" = "var") { export default function (path, emit: Function, kind: "var" | "let" = "var") {

View File

@ -51,7 +51,7 @@ const forAwaitVisitor = {
if (t.isIdentifier(callee) && callee.name === "AWAIT" && !replacements.AWAIT) { if (t.isIdentifier(callee) && callee.name === "AWAIT" && !replacements.AWAIT) {
path.replaceWith(path.node.arguments[0]); path.replaceWith(path.node.arguments[0]);
} }
} },
}; };
export default function (path, helpers) { export default function (path, helpers) {
@ -68,7 +68,7 @@ export default function (path, helpers) {
} else if (t.isVariableDeclaration(left)) { } else if (t.isVariableDeclaration(left)) {
// for await (let i of test) // for await (let i of test)
declar = t.variableDeclaration(left.kind, [ declar = t.variableDeclaration(left.kind, [
t.variableDeclarator(left.declarations[0].id, stepValue) t.variableDeclarator(left.declarations[0].id, stepValue),
]); ]);
} }
@ -83,7 +83,7 @@ export default function (path, helpers) {
OBJECT: node.right, OBJECT: node.right,
STEP_VALUE: stepValue, STEP_VALUE: stepValue,
STEP_KEY: stepKey, STEP_KEY: stepKey,
AWAIT: helpers.wrapAwait AWAIT: helpers.wrapAwait,
}); });
// remove generator function wrapper // remove generator function wrapper
@ -101,6 +101,6 @@ export default function (path, helpers) {
replaceParent: isLabeledParent, replaceParent: isLabeledParent,
node: template, node: template,
declar, declar,
loop loop,
}; };
} }

View File

@ -47,7 +47,7 @@ const awaitVisitor = {
const build = rewriteForAwait(path, { const build = rewriteForAwait(path, {
getAsyncIterator: file.addHelper("asyncIterator"), getAsyncIterator: file.addHelper("asyncIterator"),
wrapAwait wrapAwait,
}); });
const { declar, loop } = build; const { declar, loop } = build;
@ -73,7 +73,7 @@ const awaitVisitor = {
} else { } else {
path.replaceWithMultiple(build.node); path.replaceWithMultiple(build.node);
} }
} },
}; };
@ -89,7 +89,7 @@ function classOrObjectMethod(path: NodePath, callId: Object) {
t.returnStatement(t.callExpression( t.returnStatement(t.callExpression(
t.callExpression(callId, [container]), t.callExpression(callId, [container]),
[] []
)) )),
]; ];
// Regardless of whether or not the wrapped function is a an async method // Regardless of whether or not the wrapped function is a an async method
@ -142,7 +142,7 @@ function plainFunction(path: NodePath, callId: Object) {
t.variableDeclarator( t.variableDeclarator(
t.identifier(asyncFnId.name), t.identifier(asyncFnId.name),
t.callExpression(container, []) t.callExpression(container, [])
) ),
]); ]);
declar._blockHoist = true; declar._blockHoist = true;
@ -156,7 +156,7 @@ function plainFunction(path: NodePath, callId: Object) {
t.exportSpecifier( t.exportSpecifier(
t.identifier(asyncFnId.name), t.identifier(asyncFnId.name),
t.identifier("default") t.identifier("default")
) ),
] ]
) )
); );
@ -170,7 +170,7 @@ function plainFunction(path: NodePath, callId: Object) {
nameFunction({ nameFunction({
node: retFunction, node: retFunction,
parent: path.parent, parent: path.parent,
scope: path.scope scope: path.scope,
}); });
} }
@ -192,7 +192,7 @@ export default function (path: NodePath, file: Object, helpers: Object) {
} }
path.traverse(awaitVisitor, { path.traverse(awaitVisitor, {
file, file,
wrapAwait: helpers.wrapAwait wrapAwait: helpers.wrapAwait,
}); });
if (path.isClassMethod() || path.isObjectMethod()) { if (path.isClassMethod() || path.isObjectMethod()) {

View File

@ -38,7 +38,7 @@ function getPrototypeOfExpression(objectRef, isStatic) {
t.callExpression( t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
[ [
targetRef targetRef,
] ]
), ),
); );
@ -90,26 +90,26 @@ const visitor = {
path.replaceWith(result); path.replaceWith(result);
} }
} }
} },
}; };
export default class ReplaceSupers { export default class ReplaceSupers {
constructor(opts: Object, inClass?: boolean = false) { constructor(opts: Object, inClass?: boolean = false) {
this.forceSuperMemoisation = opts.forceSuperMemoisation; this.forceSuperMemoisation = opts.forceSuperMemoisation;
this.methodPath = opts.methodPath; this.methodPath = opts.methodPath;
this.methodNode = opts.methodNode; this.methodNode = opts.methodNode;
this.superRef = opts.superRef; this.superRef = opts.superRef;
this.isStatic = opts.isStatic; this.isStatic = opts.isStatic;
this.hasSuper = false; this.hasSuper = false;
this.inClass = inClass; this.inClass = inClass;
this.isLoose = opts.isLoose; this.isLoose = opts.isLoose;
this.scope = this.methodPath.scope; this.scope = this.methodPath.scope;
this.file = opts.file; this.file = opts.file;
this.opts = opts; this.opts = opts;
this.bareSupers = []; this.bareSupers = [];
this.returns = []; this.returns = [];
this.thises = []; this.thises = [];
} }
forceSuperMemoisation: boolean; forceSuperMemoisation: boolean;
@ -154,7 +154,7 @@ export default class ReplaceSupers {
getPrototypeOfExpression(this.getObjectRef(), this.isStatic), getPrototypeOfExpression(this.getObjectRef(), this.isStatic),
isComputed ? property : t.stringLiteral(property.name), isComputed ? property : t.stringLiteral(property.name),
value, value,
t.thisExpression() t.thisExpression(),
] ]
); );
} }
@ -174,7 +174,7 @@ export default class ReplaceSupers {
[ [
getPrototypeOfExpression(this.getObjectRef(), this.isStatic), getPrototypeOfExpression(this.getObjectRef(), this.isStatic),
isComputed ? property : t.stringLiteral(property.name), isComputed ? property : t.stringLiteral(property.name),
t.thisExpression() t.thisExpression(),
] ]
); );
} }
@ -185,7 +185,7 @@ export default class ReplaceSupers {
getLooseSuperProperty(id: Object, parent: Object) { getLooseSuperProperty(id: Object, parent: Object) {
const methodNode = this.methodNode; const methodNode = this.methodNode;
const superRef = this.superRef || t.identifier("Function"); const superRef = this.superRef || t.identifier("Function");
if (parent.property === id) { if (parent.property === id) {
return; return;
@ -224,10 +224,10 @@ export default class ReplaceSupers {
ref = ref || path.scope.generateUidIdentifier("ref"); ref = ref || path.scope.generateUidIdentifier("ref");
return [ return [
t.variableDeclaration("var", [ t.variableDeclaration("var", [
t.variableDeclarator(ref, node.left) t.variableDeclarator(ref, node.left),
]), ]),
t.expressionStatement(t.assignmentExpression("=", node.left, t.expressionStatement(t.assignmentExpression("=", node.left,
t.binaryExpression(node.operator[0], ref, node.right))) t.binaryExpression(node.operator[0], ref, node.right))),
]; ];
} }
} }

View File

@ -118,8 +118,8 @@ function wrapPackagesArray(type, names, optionsDir) {
function run(task) { function run(task) {
const actual = task.actual; const actual = task.actual;
const expect = task.expect; const expect = task.expect;
const exec = task.exec; const exec = task.exec;
const opts = task.options; const opts = task.options;
const optionsDir = task.optionsDir; const optionsDir = task.optionsDir;
function getOpts(self) { function getOpts(self) {
@ -218,8 +218,8 @@ export default function (
defaults(task.options, { defaults(task.options, {
filenameRelative: task.expect.filename, filenameRelative: task.expect.filename,
sourceFileName: task.actual.filename, sourceFileName: task.actual.filename,
sourceMapTarget: task.expect.filename, sourceMapTarget: task.expect.filename,
suppressDeprecationMessages: true, suppressDeprecationMessages: true,
babelrc: false, babelrc: false,
sourceMap: !!(task.sourceMappings || task.sourceMap), sourceMap: !!(task.sourceMappings || task.sourceMap),

View File

@ -40,7 +40,7 @@ export const MESSAGES = {
pluginNotObject: "Plugin $2 specified in $1 was expected to return an object when invoked but returned $3", pluginNotObject: "Plugin $2 specified in $1 was expected to return an object when invoked but returned $3",
pluginNotFunction: "Plugin $2 specified in $1 was expected to return a function but returned $3", pluginNotFunction: "Plugin $2 specified in $1 was expected to return a function but returned $3",
pluginUnknown: "Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4", pluginUnknown: "Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4",
pluginInvalidProperty: "Plugin $2 specified in $1 provided an invalid property of $3" pluginInvalidProperty: "Plugin $2 specified in $1 provided an invalid property of $3",
}; };
/** /**

View File

@ -11,6 +11,6 @@ export default function ({ messages }) {
} }
} }
}, },
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function ({ types: t }) {
return { return {
pre(file) { pre(file) {
file.set("helpersNamespace", t.identifier("babelHelpers")); file.set("helpersNamespace", t.identifier("babelHelpers"));
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("asyncFunctions"); parserOpts.plugins.push("asyncFunctions");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("asyncGenerators"); parserOpts.plugins.push("asyncGenerators");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("classProperties"); parserOpts.plugins.push("classProperties");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("decorators"); parserOpts.plugins.push("decorators");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("doExpressions"); parserOpts.plugins.push("doExpressions");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("dynamicImport"); parserOpts.plugins.push("dynamicImport");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("exponentiationOperator"); parserOpts.plugins.push("exponentiationOperator");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("exportExtensions"); parserOpts.plugins.push("exportExtensions");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("flow"); parserOpts.plugins.push("flow");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("functionBind"); parserOpts.plugins.push("functionBind");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("functionSent"); parserOpts.plugins.push("functionSent");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("jsx"); parserOpts.plugins.push("jsx");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("objectRestSpread"); parserOpts.plugins.push("objectRestSpread");
} },
}; };
} }

View File

@ -2,6 +2,6 @@ export default function () {
return { return {
manipulateOptions(opts, parserOpts) { manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("trailingFunctionCommas"); parserOpts.plugins.push("trailingFunctionCommas");
} },
}; };
} }

View File

@ -12,9 +12,9 @@ export default function ({ types: t }) {
const callee = state.addHelper("asyncGeneratorDelegate"); const callee = state.addHelper("asyncGeneratorDelegate");
node.argument = t.callExpression(callee, [ node.argument = t.callExpression(callee, [
t.callExpression(state.addHelper("asyncIterator"), [node.argument]), t.callExpression(state.addHelper("asyncIterator"), [node.argument]),
t.memberExpression(state.addHelper("asyncGenerator"), t.identifier("await")) t.memberExpression(state.addHelper("asyncGenerator"), t.identifier("await")),
]); ]);
} },
}; };
return { return {
@ -29,9 +29,9 @@ export default function ({ types: t }) {
wrapAsync: t.memberExpression( wrapAsync: t.memberExpression(
state.addHelper("asyncGenerator"), t.identifier("wrap")), state.addHelper("asyncGenerator"), t.identifier("wrap")),
wrapAwait: t.memberExpression( wrapAwait: t.memberExpression(
state.addHelper("asyncGenerator"), t.identifier("await")) state.addHelper("asyncGenerator"), t.identifier("await")),
}); });
} },
} },
}; };
} }

View File

@ -10,9 +10,9 @@ export default function () {
if (!path.node.async || path.node.generator) return; if (!path.node.async || path.node.generator) return;
remapAsyncToGenerator(path, state.file, { remapAsyncToGenerator(path, state.file, {
wrapAsync: state.addHelper("asyncToGenerator") wrapAsync: state.addHelper("asyncToGenerator"),
}); });
} },
} },
}; };
} }

View File

@ -10,9 +10,9 @@ export default function () {
if (!path.node.async || path.node.generator) return; if (!path.node.async || path.node.generator) return;
remapAsyncToGenerator(path, state.file, { remapAsyncToGenerator(path, state.file, {
wrapAsync: state.addImport(state.opts.module, state.opts.method) wrapAsync: state.addImport(state.opts.module, state.opts.method),
}); });
} },
} },
}; };
} }

View File

@ -8,7 +8,7 @@ export default function ({ types: t }) {
if (path.parentPath.isCallExpression({ callee: path.node })) { if (path.parentPath.isCallExpression({ callee: path.node })) {
this.push(path.parentPath); this.push(path.parentPath);
} }
} },
}; };
const referenceVisitor = { const referenceVisitor = {
@ -17,7 +17,7 @@ export default function ({ types: t }) {
this.collision = true; this.collision = true;
path.skip(); path.skip();
} }
} },
}; };
const buildObjectDefineProperty = template(` const buildObjectDefineProperty = template(`
@ -32,7 +32,7 @@ export default function ({ types: t }) {
const buildClassPropertySpec = (ref, { key, value, computed }) => buildObjectDefineProperty({ const buildClassPropertySpec = (ref, { key, value, computed }) => buildObjectDefineProperty({
REF: ref, REF: ref,
KEY: (t.isIdentifier(key) && !computed) ? t.stringLiteral(key.name) : key, KEY: (t.isIdentifier(key) && !computed) ? t.stringLiteral(key.name) : key,
VALUE: value ? value : t.identifier("undefined") VALUE: value ? value : t.identifier("undefined"),
}); });
const buildClassPropertyNonSpec = (ref, { key, value, computed }) => t.expressionStatement( const buildClassPropertyNonSpec = (ref, { key, value, computed }) => t.expressionStatement(
@ -111,7 +111,7 @@ export default function ({ types: t }) {
const collisionState = { const collisionState = {
collision: false, collision: false,
scope: constructor.scope scope: constructor.scope,
}; };
for (const prop of props) { for (const prop of props) {
@ -126,14 +126,14 @@ export default function ({ types: t }) {
t.variableDeclarator( t.variableDeclarator(
initialisePropsRef, initialisePropsRef,
t.functionExpression(null, [], t.blockStatement(instanceBody)) t.functionExpression(null, [], t.blockStatement(instanceBody))
) ),
])); ]));
instanceBody = [ instanceBody = [
t.expressionStatement( t.expressionStatement(
t.callExpression(t.memberExpression(initialisePropsRef, t.identifier("call")), [ t.callExpression(t.memberExpression(initialisePropsRef, t.identifier("call")), [
t.thisExpression()]) t.thisExpression()])
) ),
]; ];
} }
@ -180,7 +180,7 @@ export default function ({ types: t }) {
if (members.some((member) => member.isClassProperty())) { if (members.some((member) => member.isClassProperty())) {
path.ensureBlock(); path.ensureBlock();
} }
} },
} },
}; };
} }

View File

@ -302,7 +302,7 @@ export default function({ types: t }) {
const ref = node.id || path.scope.generateUidIdentifier("class"); const ref = node.id || path.scope.generateUidIdentifier("class");
path.replaceWith(t.variableDeclaration("let", [ path.replaceWith(t.variableDeclaration("let", [
t.variableDeclarator(ref, t.toExpression(node)) t.variableDeclarator(ref, t.toExpression(node)),
])); ]));
}, },
ClassExpression(path, state) { ClassExpression(path, state) {
@ -337,6 +337,6 @@ export default function({ types: t }) {
path.get("right.arguments")[1].node, path.get("right.arguments")[1].node,
])); ]));
}, },
} },
}; };
} }

View File

@ -12,7 +12,7 @@ export default function () {
} else { } else {
path.replaceWith(path.scope.buildUndefinedNode()); path.replaceWith(path.scope.buildUndefinedNode());
} }
} },
} },
}; };
} }

View File

@ -18,7 +18,7 @@ export default function ({ types: t }) {
"body", "body",
t.expressionStatement(t.callExpression(state.addHelper("newArrowCheck"), [ t.expressionStatement(t.callExpression(state.addHelper("newArrowCheck"), [
t.thisExpression(), t.thisExpression(),
boundThis boundThis,
])) ]))
); );
@ -29,7 +29,7 @@ export default function ({ types: t }) {
} else { } else {
path.arrowFunctionToShadowed(); path.arrowFunctionToShadowed();
} }
} },
} },
}; };
} }

View File

@ -7,7 +7,7 @@ export default function ({ types: t }) {
if (!path.isFunctionDeclaration()) continue; if (!path.isFunctionDeclaration()) continue;
const declar = t.variableDeclaration("let", [ const declar = t.variableDeclaration("let", [
t.variableDeclarator(func.id, t.toExpression(func)) t.variableDeclarator(func.id, t.toExpression(func)),
]); ]);
// hoist it up above everything else // hoist it up above everything else
@ -24,7 +24,7 @@ export default function ({ types: t }) {
visitor: { visitor: {
BlockStatement(path) { BlockStatement(path) {
const { node, parent } = path; const { node, parent } = path;
if (t.isFunction(parent, { body: node }) || t.isExportDeclaration(parent)) { if (t.isFunction(parent, { body: node }) || t.isExportDeclaration(parent)) {
return; return;
} }
@ -33,7 +33,7 @@ export default function ({ types: t }) {
SwitchCase(path) { SwitchCase(path) {
statementList("consequent", path); statementList("consequent", path);
} },
} },
}; };
} }

View File

@ -60,8 +60,8 @@ export default function () {
const blockScoping = new BlockScoping(null, path, path.parent, path.scope, file); const blockScoping = new BlockScoping(null, path, path.parent, path.scope, file);
blockScoping.run(); blockScoping.run();
} }
} },
} },
}; };
} }
@ -128,7 +128,7 @@ const letReferenceBlockVisitor = traverse.visitors.merge([{
path.traverse(letReferenceFunctionVisitor, state); path.traverse(letReferenceFunctionVisitor, state);
} }
return path.skip(); return path.skip();
} },
}, tdzVisitor]); }, tdzVisitor]);
const letReferenceFunctionVisitor = traverse.visitors.merge([{ const letReferenceFunctionVisitor = traverse.visitors.merge([{
@ -144,7 +144,7 @@ const letReferenceFunctionVisitor = traverse.visitors.merge([{
if (localBinding && localBinding !== ref) return; if (localBinding && localBinding !== ref) return;
state.closurify = true; state.closurify = true;
} },
}, tdzVisitor]); }, tdzVisitor]);
const hoistVarDeclarationsVisitor = { const hoistVarDeclarationsVisitor = {
@ -170,13 +170,13 @@ const hoistVarDeclarationsVisitor = {
} else if (path.isFunction()) { } else if (path.isFunction()) {
return path.skip(); return path.skip();
} }
} },
}; };
const loopLabelVisitor = { const loopLabelVisitor = {
LabeledStatement({ node }, state) { LabeledStatement({ node }, state) {
state.innerLabels.push(node.label.name); state.innerLabels.push(node.label.name);
} },
}; };
const continuationVisitor = { const continuationVisitor = {
@ -188,7 +188,7 @@ const continuationVisitor = {
state.reassignments[name] = true; state.reassignments[name] = true;
} }
} }
} },
}; };
function loopNodeTo(node) { function loopNodeTo(node) {
@ -255,7 +255,7 @@ const loopVisitor = {
if (path.isReturnStatement()) { if (path.isReturnStatement()) {
state.hasReturn = true; state.hasReturn = true;
replace = t.objectExpression([ replace = t.objectExpression([
t.objectProperty(t.identifier("v"), node.argument || scope.buildUndefinedNode()) t.objectProperty(t.identifier("v"), node.argument || scope.buildUndefinedNode()),
]); ]);
} }
@ -265,28 +265,28 @@ const loopVisitor = {
path.skip(); path.skip();
path.replaceWith(t.inherits(replace, node)); path.replaceWith(t.inherits(replace, node));
} }
} },
}; };
class BlockScoping { class BlockScoping {
constructor(loopPath?: NodePath, blockPath: NodePath, parent: Object, scope: Scope, file: File) { constructor(loopPath?: NodePath, blockPath: NodePath, parent: Object, scope: Scope, file: File) {
this.parent = parent; this.parent = parent;
this.scope = scope; this.scope = scope;
this.file = file; this.file = file;
this.blockPath = blockPath; this.blockPath = blockPath;
this.block = blockPath.node; this.block = blockPath.node;
this.outsideLetReferences = Object.create(null); this.outsideLetReferences = Object.create(null);
this.hasLetReferences = false; this.hasLetReferences = false;
this.letReferences = Object.create(null); this.letReferences = Object.create(null);
this.body = []; this.body = [];
if (loopPath) { if (loopPath) {
this.loopParent = loopPath.parent; this.loopParent = loopPath.parent;
this.loopLabel = t.isLabeledStatement(this.loopParent) && this.loopParent.label; this.loopLabel = t.isLabeledStatement(this.loopParent) && this.loopParent.label;
this.loopPath = loopPath; this.loopPath = loopPath;
this.loop = loopPath.node; this.loop = loopPath.node;
} }
} }
@ -345,8 +345,8 @@ class BlockScoping {
} }
remap() { remap() {
const letRefs = this.letReferences; const letRefs = this.letReferences;
const scope = this.scope; const scope = this.scope;
// alright, so since we aren't wrapping this block in a closure // alright, so since we aren't wrapping this block in a closure
// we have to check if any of our let variables collide with // we have to check if any of our let variables collide with
@ -364,10 +364,10 @@ class BlockScoping {
// the enclosing scope (e.g. loop or catch statement), so we should handle both // the enclosing scope (e.g. loop or catch statement), so we should handle both
// individually // individually
if (scope.hasOwnBinding(key)) if (scope.hasOwnBinding(key))
scope.rename(ref.name); {scope.rename(ref.name);}
if (this.blockPath.scope.hasOwnBinding(key)) if (this.blockPath.scope.hasOwnBinding(key))
this.blockPath.scope.rename(ref.name); {this.blockPath.scope.rename(ref.name);}
} }
} }
} }
@ -409,7 +409,7 @@ class BlockScoping {
// turn outsideLetReferences into an array // turn outsideLetReferences into an array
const params = values(outsideRefs); const params = values(outsideRefs);
const args = values(outsideRefs); const args = values(outsideRefs);
const isSwitch = this.blockPath.isSwitchStatement(); const isSwitch = this.blockPath.isSwitchStatement();
@ -426,13 +426,13 @@ class BlockScoping {
if (this.loop) { if (this.loop) {
ref = this.scope.generateUidIdentifier("loop"); ref = this.scope.generateUidIdentifier("loop");
this.loopPath.insertBefore(t.variableDeclaration("var", [ this.loopPath.insertBefore(t.variableDeclaration("var", [
t.variableDeclarator(ref, fn) t.variableDeclarator(ref, fn),
])); ]));
} }
// build a call and a unique id that we can assign the return value to // build a call and a unique id that we can assign the return value to
let call = t.callExpression(ref, args); let call = t.callExpression(ref, args);
const ret = this.scope.generateUidIdentifier("ret"); const ret = this.scope.generateUidIdentifier("ret");
// handle generators // handle generators
const hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); const hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES);
@ -479,7 +479,7 @@ class BlockScoping {
addContinuations(fn) { addContinuations(fn) {
const state = { const state = {
reassignments: {}, reassignments: {},
outsideReferences: this.outsideLetReferences outsideReferences: this.outsideLetReferences,
}; };
this.scope.traverse(fn, continuationVisitor, state); this.scope.traverse(fn, continuationVisitor, state);
@ -561,9 +561,9 @@ class BlockScoping {
const state = { const state = {
letReferences: this.letReferences, letReferences: this.letReferences,
closurify: false, closurify: false,
file: this.file, file: this.file,
loopDepth: 0, loopDepth: 0,
}; };
const loopOrFunctionParent = this.blockPath.find( const loopOrFunctionParent = this.blockPath.find(
@ -592,13 +592,13 @@ class BlockScoping {
checkLoop(): Object { checkLoop(): Object {
const state = { const state = {
hasBreakContinue: false, hasBreakContinue: false,
ignoreLabeless: false, ignoreLabeless: false,
inSwitchCase: false, inSwitchCase: false,
innerLabels: [], innerLabels: [],
hasReturn: false, hasReturn: false,
isLoop: !!this.loop, isLoop: !!this.loop,
map: {}, map: {},
LOOP_IGNORE: Symbol() LOOP_IGNORE: Symbol(),
}; };
this.blockPath.traverse(loopLabelVisitor, state); this.blockPath.traverse(loopLabelVisitor, state);
@ -647,7 +647,7 @@ class BlockScoping {
const body = this.body; const body = this.body;
body.push(t.variableDeclaration("var", [ body.push(t.variableDeclaration("var", [
t.variableDeclarator(ret, call) t.variableDeclarator(ret, call),
])); ]));
let retCheck; let retCheck;
@ -657,7 +657,7 @@ class BlockScoping {
if (has.hasReturn) { if (has.hasReturn) {
// typeof ret === "object" // typeof ret === "object"
retCheck = buildRetCheck({ retCheck = buildRetCheck({
RETURN: ret RETURN: ret,
}); });
} }

View File

@ -58,7 +58,7 @@ export const visitor = {
} else if (status === "outside") { } else if (status === "outside") {
path.replaceWith(t.throwStatement(t.inherits( path.replaceWith(t.throwStatement(t.inherits(
t.newExpression(t.identifier("ReferenceError"), [ t.newExpression(t.identifier("ReferenceError"), [
t.stringLiteral(`${node.name} is not defined - temporal dead zone`) t.stringLiteral(`${node.name} is not defined - temporal dead zone`),
]), ]),
node node
))); )));
@ -88,6 +88,6 @@ export const visitor = {
nodes.push(node); nodes.push(node);
path.replaceWithMultiple(nodes.map(t.expressionStatement)); path.replaceWithMultiple(nodes.map(t.expressionStatement));
} }
} },
} },
}; };

View File

@ -26,7 +26,7 @@ export default function ({ types: t }) {
const ref = node.id || path.scope.generateUidIdentifier("class"); const ref = node.id || path.scope.generateUidIdentifier("class");
path.replaceWith(t.variableDeclaration("let", [ path.replaceWith(t.variableDeclaration("let", [
t.variableDeclarator(ref, t.toExpression(node)) t.variableDeclarator(ref, t.toExpression(node)),
])); ]));
}, },
@ -43,7 +43,7 @@ export default function ({ types: t }) {
if (state.opts.loose) Constructor = LooseTransformer; if (state.opts.loose) Constructor = LooseTransformer;
path.replaceWith(new Constructor(path, state.file).run()); path.replaceWith(new Constructor(path, state.file).run());
} },
} },
}; };
} }

View File

@ -23,7 +23,7 @@ export default class LooseClassTransformer extends VanillaTransformer {
func = nameFunction({ func = nameFunction({
node: func, node: func,
id: key, id: key,
scope scope,
}); });
} }

View File

@ -21,7 +21,7 @@ const noMethodVisitor = {
Method(path) { Method(path) {
path.skip(); path.skip();
} },
}; };
const verifyConstructorVisitor = visitors.merge([noMethodVisitor, { const verifyConstructorVisitor = visitors.merge([noMethodVisitor, {
@ -43,7 +43,7 @@ const verifyConstructorVisitor = visitors.merge([noMethodVisitor, {
throw path.buildCodeFrameError("super() is only allowed in a derived constructor"); throw path.buildCodeFrameError("super() is only allowed in a derived constructor");
} }
} }
} },
}, },
ThisExpression(path) { ThisExpression(path) {
@ -52,36 +52,36 @@ const verifyConstructorVisitor = visitors.merge([noMethodVisitor, {
throw path.buildCodeFrameError("'this' is not allowed before super()"); throw path.buildCodeFrameError("'this' is not allowed before super()");
} }
} }
} },
}]); }]);
const findThisesVisitor = visitors.merge([noMethodVisitor, { const findThisesVisitor = visitors.merge([noMethodVisitor, {
ThisExpression(path) { ThisExpression(path) {
this.superThises.push(path); this.superThises.push(path);
} },
}]); }]);
export default class ClassTransformer { export default class ClassTransformer {
constructor(path: NodePath, file) { constructor(path: NodePath, file) {
this.parent = path.parent; this.parent = path.parent;
this.scope = path.scope; this.scope = path.scope;
this.node = path.node; this.node = path.node;
this.path = path; this.path = path;
this.file = file; this.file = file;
this.clearDescriptors(); this.clearDescriptors();
this.instancePropBody = []; this.instancePropBody = [];
this.instancePropRefs = {}; this.instancePropRefs = {};
this.staticPropBody = []; this.staticPropBody = [];
this.body = []; this.body = [];
this.bareSuperAfter = []; this.bareSuperAfter = [];
this.bareSupers = []; this.bareSupers = [];
this.pushedConstructor = false; this.pushedConstructor = false;
this.pushedInherits = false; this.pushedInherits = false;
this.isLoose = false; this.isLoose = false;
this.superThises = []; this.superThises = [];
@ -98,13 +98,13 @@ export default class ClassTransformer {
run() { run() {
let superName = this.superName; let superName = this.superName;
const file = this.file; const file = this.file;
let body = this.body; let body = this.body;
// //
const constructorBody = this.constructorBody = t.blockStatement([]); const constructorBody = this.constructorBody = t.blockStatement([]);
this.constructor = this.buildConstructor(); this.constructor = this.buildConstructor();
// //
@ -128,7 +128,7 @@ export default class ClassTransformer {
constructorBody.body.unshift(t.expressionStatement(t.callExpression( constructorBody.body.unshift(t.expressionStatement(t.callExpression(
file.addHelper("classCallCheck"), [ file.addHelper("classCallCheck"), [
t.thisExpression(), t.thisExpression(),
this.classRef this.classRef,
] ]
))); )));
@ -248,14 +248,14 @@ export default class ClassTransformer {
const replaceSupers = new ReplaceSupers({ const replaceSupers = new ReplaceSupers({
forceSuperMemoisation: isConstructor, forceSuperMemoisation: isConstructor,
methodPath: path, methodPath: path,
methodNode: node, methodNode: node,
objectRef: this.classRef, objectRef: this.classRef,
superRef: this.superName, superRef: this.superName,
isStatic: node.static, isStatic: node.static,
isLoose: this.isLoose, isLoose: this.isLoose,
scope: this.scope, scope: this.scope,
file: this.file file: this.file,
}, true); }, true);
replaceSupers.replace(); replaceSupers.replace();
@ -271,10 +271,10 @@ export default class ClassTransformer {
clearDescriptors() { clearDescriptors() {
this.hasInstanceDescriptors = false; this.hasInstanceDescriptors = false;
this.hasStaticDescriptors = false; this.hasStaticDescriptors = false;
this.instanceMutatorMap = {}; this.instanceMutatorMap = {};
this.staticMutatorMap = {}; this.staticMutatorMap = {};
} }
pushDescriptors() { pushDescriptors() {
@ -337,7 +337,7 @@ export default class ClassTransformer {
buildObjectAssignment(id) { buildObjectAssignment(id) {
return t.variableDeclaration("var", [ return t.variableDeclaration("var", [
t.variableDeclarator(id, t.objectExpression([])) t.variableDeclarator(id, t.objectExpression([])),
]); ]);
} }
@ -400,10 +400,10 @@ export default class ClassTransformer {
} else { } else {
bareSuper.replaceWithMultiple([ bareSuper.replaceWithMultiple([
t.variableDeclaration("var", [ t.variableDeclaration("var", [
t.variableDeclarator(thisRef, call) t.variableDeclarator(thisRef, call),
]), ]),
...bareSuperAfter, ...bareSuperAfter,
t.expressionStatement(thisRef) t.expressionStatement(thisRef),
]); ]);
} }
@ -462,7 +462,7 @@ export default class ClassTransformer {
const ref = returnPath.scope.generateDeclaredUidIdentifier("ret"); const ref = returnPath.scope.generateDeclaredUidIdentifier("ret");
returnPath.get("argument").replaceWithMultiple([ returnPath.get("argument").replaceWithMultiple([
t.assignmentExpression("=", ref, returnPath.node.argument), t.assignmentExpression("=", ref, returnPath.node.argument),
wrapReturn(ref) wrapReturn(ref),
]); ]);
} else { } else {
returnPath.get("argument").replaceWith(wrapReturn()); returnPath.get("argument").replaceWith(wrapReturn());
@ -504,13 +504,13 @@ export default class ClassTransformer {
const construct = this.constructor; const construct = this.constructor;
this.userConstructorPath = path; this.userConstructorPath = path;
this.userConstructor = method; this.userConstructor = method;
this.hasConstructor = true; this.hasConstructor = true;
t.inheritsComments(construct, method); t.inheritsComments(construct, method);
construct._ignoreUserWhitespace = true; construct._ignoreUserWhitespace = true;
construct.params = method.params; construct.params = method.params;
t.inherits(construct.body, method.body); t.inherits(construct.body, method.body);
construct.body.directives = method.body.directives; construct.body.directives = method.body.directives;

View File

@ -39,7 +39,7 @@ export default function ({ types: t, template }) {
MUTATOR_MAP_REF: getMutatorId(), MUTATOR_MAP_REF: getMutatorId(),
KEY: key, KEY: key,
VALUE: getValue(prop), VALUE: getValue(prop),
KIND: t.identifier(prop.kind) KIND: t.identifier(prop.kind),
})); }));
} }
@ -68,14 +68,14 @@ export default function ({ types: t, template }) {
return t.callExpression(state.addHelper("defineProperty"), [ return t.callExpression(state.addHelper("defineProperty"), [
info.initPropExpression, info.initPropExpression,
key, key,
getValue(prop) getValue(prop),
]); ]);
} else { } else {
body.push(t.expressionStatement( body.push(t.expressionStatement(
t.callExpression(state.addHelper("defineProperty"), [ t.callExpression(state.addHelper("defineProperty"), [
objId, objId,
key, key,
getValue(prop) getValue(prop),
]) ])
)); ));
} }
@ -119,7 +119,7 @@ export default function ({ types: t, template }) {
const body = []; const body = [];
body.push(t.variableDeclaration("var", [ body.push(t.variableDeclaration("var", [
t.variableDeclarator(objId, initPropExpression) t.variableDeclarator(objId, initPropExpression),
])); ]));
let callback = spec; let callback = spec;
@ -132,7 +132,7 @@ export default function ({ types: t, template }) {
mutatorRef = scope.generateUidIdentifier("mutatorMap"); mutatorRef = scope.generateUidIdentifier("mutatorMap");
body.push(t.variableDeclaration("var", [ body.push(t.variableDeclaration("var", [
t.variableDeclarator(mutatorRef, t.objectExpression([])) t.variableDeclarator(mutatorRef, t.objectExpression([])),
])); ]));
} }
@ -162,8 +162,8 @@ export default function ({ types: t, template }) {
body.push(t.expressionStatement(objId)); body.push(t.expressionStatement(objId));
path.replaceWithMultiple(body); path.replaceWithMultiple(body);
} }
} },
} },
} },
}; };
} }

View File

@ -32,18 +32,18 @@ export default function ({ types: t }) {
state.deopt = true; state.deopt = true;
path.stop(); path.stop();
} }
} },
}; };
class DestructuringTransformer { class DestructuringTransformer {
constructor(opts) { constructor(opts) {
this.blockHoist = opts.blockHoist; this.blockHoist = opts.blockHoist;
this.operator = opts.operator; this.operator = opts.operator;
this.arrays = {}; this.arrays = {};
this.nodes = opts.nodes || []; this.nodes = opts.nodes || [];
this.scope = opts.scope; this.scope = opts.scope;
this.file = opts.file; this.file = opts.file;
this.kind = opts.kind; this.kind = opts.kind;
} }
buildVariableAssignment(id, init) { buildVariableAssignment(id, init) {
@ -56,7 +56,7 @@ export default function ({ types: t }) {
node = t.expressionStatement(t.assignmentExpression(op, id, init)); node = t.expressionStatement(t.assignmentExpression(op, id, init));
} else { } else {
node = t.variableDeclaration(this.kind, [ node = t.variableDeclaration(this.kind, [
t.variableDeclarator(id, init) t.variableDeclarator(id, init),
]); ]);
} }
@ -67,7 +67,7 @@ export default function ({ types: t }) {
buildVariableDeclaration(id, init) { buildVariableDeclaration(id, init) {
const declar = t.variableDeclaration("var", [ const declar = t.variableDeclaration("var", [
t.variableDeclarator(id, init) t.variableDeclarator(id, init),
]); ]);
declar._blockHoist = this.blockHoist; declar._blockHoist = this.blockHoist;
return declar; return declar;
@ -100,7 +100,7 @@ export default function ({ types: t }) {
const tempValueRef = this.scope.generateUidIdentifierBasedOnNode(valueRef); const tempValueRef = this.scope.generateUidIdentifierBasedOnNode(valueRef);
const declar = t.variableDeclaration("var", [ const declar = t.variableDeclaration("var", [
t.variableDeclarator(tempValueRef, valueRef) t.variableDeclarator(tempValueRef, valueRef),
]); ]);
declar._blockHoist = this.blockHoist; declar._blockHoist = this.blockHoist;
this.nodes.push(declar); this.nodes.push(declar);
@ -160,7 +160,7 @@ export default function ({ types: t }) {
if (t.isLiteral(prop.key)) prop.computed = true; if (t.isLiteral(prop.key)) prop.computed = true;
const pattern = prop.value; const pattern = prop.value;
const objRef = t.memberExpression(propRef, prop.key, prop.computed); const objRef = t.memberExpression(propRef, prop.key, prop.computed);
if (t.isPattern(pattern)) { if (t.isPattern(pattern)) {
this.push(pattern, objRef); this.push(pattern, objRef);
@ -359,13 +359,13 @@ export default function ({ types: t }) {
const temp = scope.generateUidIdentifier("ref"); const temp = scope.generateUidIdentifier("ref");
node.left = t.variableDeclaration("var", [ node.left = t.variableDeclaration("var", [
t.variableDeclarator(temp) t.variableDeclarator(temp),
]); ]);
path.ensureBlock(); path.ensureBlock();
node.body.body.unshift(t.variableDeclaration("var", [ node.body.body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(left, temp) t.variableDeclarator(left, temp),
])); ]));
return; return;
@ -378,7 +378,7 @@ export default function ({ types: t }) {
const key = scope.generateUidIdentifier("ref"); const key = scope.generateUidIdentifier("ref");
node.left = t.variableDeclaration(left.kind, [ node.left = t.variableDeclaration(left.kind, [
t.variableDeclarator(key, null) t.variableDeclarator(key, null),
]); ]);
const nodes = []; const nodes = [];
@ -387,7 +387,7 @@ export default function ({ types: t }) {
kind: left.kind, kind: left.kind,
file: file, file: file,
scope: scope, scope: scope,
nodes: nodes nodes: nodes,
}); });
destructuring.init(pattern, key); destructuring.init(pattern, key);
@ -411,7 +411,7 @@ export default function ({ types: t }) {
kind: "let", kind: "let",
file: file, file: file,
scope: scope, scope: scope,
nodes: nodes nodes: nodes,
}); });
destructuring.init(pattern, ref); destructuring.init(pattern, ref);
@ -428,7 +428,7 @@ export default function ({ types: t }) {
operator: node.operator, operator: node.operator,
file: file, file: file,
scope: scope, scope: scope,
nodes: nodes nodes: nodes,
}); });
let ref; let ref;
@ -436,7 +436,7 @@ export default function ({ types: t }) {
ref = scope.generateUidIdentifierBasedOnNode(node.right, "ref"); ref = scope.generateUidIdentifierBasedOnNode(node.right, "ref");
nodes.push(t.variableDeclaration("var", [ nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(ref, node.right) t.variableDeclarator(ref, node.right),
])); ]));
if (t.isArrayExpression(node.right)) { if (t.isArrayExpression(node.right)) {
@ -466,14 +466,14 @@ export default function ({ types: t }) {
declar = node.declarations[i]; declar = node.declarations[i];
const patternId = declar.init; const patternId = declar.init;
const pattern = declar.id; const pattern = declar.id;
const destructuring = new DestructuringTransformer({ const destructuring = new DestructuringTransformer({
blockHoist: node._blockHoist, blockHoist: node._blockHoist,
nodes: nodes, nodes: nodes,
scope: scope, scope: scope,
kind: node.kind, kind: node.kind,
file: file file: file,
}); });
if (t.isPattern(pattern)) { if (t.isPattern(pattern)) {
@ -522,7 +522,7 @@ export default function ({ types: t }) {
} else { } else {
path.replaceWithMultiple(nodesOut); path.replaceWithMultiple(nodesOut);
} }
} },
} },
}; };
} }

View File

@ -56,7 +56,7 @@ export default function() {
prop.key = t.stringLiteral(name); prop.key = t.stringLiteral(name);
} }
} }
} },
} },
}; };
} }

View File

@ -53,7 +53,7 @@ export default function ({ messages, template, types: t }) {
if (!t.isIdentifier(right) || !scope.hasBinding(right.name)) { if (!t.isIdentifier(right) || !scope.hasBinding(right.name)) {
const uid = scope.generateUidIdentifier("arr"); const uid = scope.generateUidIdentifier("arr");
nodes.push(t.variableDeclaration("var", [ nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(uid, right) t.variableDeclarator(uid, right),
])); ]));
right = uid; right = uid;
} }
@ -62,8 +62,8 @@ export default function ({ messages, template, types: t }) {
let loop = buildForOfArray({ let loop = buildForOfArray({
BODY: node.body, BODY: node.body,
KEY: iterationKey, KEY: iterationKey,
ARR: right ARR: right,
}); });
t.inherits(loop, node); t.inherits(loop, node);
@ -105,10 +105,10 @@ export default function ({ messages, template, types: t }) {
if (state.opts.loose) callback = loose; if (state.opts.loose) callback = loose;
const { node } = path; const { node } = path;
const build = callback(path, state); const build = callback(path, state);
const declar = build.declar; const declar = build.declar;
const loop = build.loop; const loop = build.loop;
const block = loop.body; const block = loop.body;
// ensure that it's a block so we can take all its statements // ensure that it's a block so we can take all its statements
path.ensureBlock(); path.ensureBlock();
@ -130,8 +130,8 @@ export default function ({ messages, template, types: t }) {
} else { } else {
path.replaceWithMultiple(build.node); path.replaceWithMultiple(build.node);
} }
} },
} },
}; };
function loose(path, file) { function loose(path, file) {
@ -146,21 +146,21 @@ export default function ({ messages, template, types: t }) {
// for (let i of test) // for (let i of test)
id = scope.generateUidIdentifier("ref"); id = scope.generateUidIdentifier("ref");
declar = t.variableDeclaration(left.kind, [ declar = t.variableDeclaration(left.kind, [
t.variableDeclarator(left.declarations[0].id, id) t.variableDeclarator(left.declarations[0].id, id),
]); ]);
} else { } else {
throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type));
} }
const iteratorKey = scope.generateUidIdentifier("iterator"); const iteratorKey = scope.generateUidIdentifier("iterator");
const isArrayKey = scope.generateUidIdentifier("isArray"); const isArrayKey = scope.generateUidIdentifier("isArray");
const loop = buildForOfLoose({ const loop = buildForOfLoose({
LOOP_OBJECT: iteratorKey, LOOP_OBJECT: iteratorKey,
IS_ARRAY: isArrayKey, IS_ARRAY: isArrayKey,
OBJECT: node.right, OBJECT: node.right,
INDEX: scope.generateUidIdentifier("i"), INDEX: scope.generateUidIdentifier("i"),
ID: id ID: id,
}); });
if (!declar) { if (!declar) {
@ -179,9 +179,9 @@ export default function ({ messages, template, types: t }) {
return { return {
replaceParent: isLabeledParent, replaceParent: isLabeledParent,
declar: declar, declar: declar,
node: labeled || loop, node: labeled || loop,
loop: loop loop: loop,
}; };
} }
@ -190,7 +190,7 @@ export default function ({ messages, template, types: t }) {
const left = node.left; const left = node.left;
let declar; let declar;
const stepKey = scope.generateUidIdentifier("step"); const stepKey = scope.generateUidIdentifier("step");
const stepValue = t.memberExpression(stepKey, t.identifier("value")); const stepValue = t.memberExpression(stepKey, t.identifier("value"));
if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) {
@ -199,7 +199,7 @@ export default function ({ messages, template, types: t }) {
} else if (t.isVariableDeclaration(left)) { } else if (t.isVariableDeclaration(left)) {
// for (let i of test) // for (let i of test)
declar = t.variableDeclaration(left.kind, [ declar = t.variableDeclaration(left.kind, [
t.variableDeclarator(left.declarations[0].id, stepValue) t.variableDeclarator(left.declarations[0].id, stepValue),
]); ]);
} else { } else {
throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type));
@ -211,12 +211,12 @@ export default function ({ messages, template, types: t }) {
const template = buildForOf({ const template = buildForOf({
ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"), ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"),
ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"), ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"),
ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"), ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"),
ITERATOR_KEY: iteratorKey, ITERATOR_KEY: iteratorKey,
STEP_KEY: stepKey, STEP_KEY: stepKey,
OBJECT: node.right, OBJECT: node.right,
BODY: null BODY: null,
}); });
const isLabeledParent = t.isLabeledStatement(parent); const isLabeledParent = t.isLabeledStatement(parent);
@ -232,9 +232,9 @@ export default function ({ messages, template, types: t }) {
return { return {
replaceParent: isLabeledParent, replaceParent: isLabeledParent,
declar: declar, declar: declar,
loop: loop, loop: loop,
node: template node: template,
}; };
} }
} }

View File

@ -9,7 +9,7 @@ export default function () {
const replacement = nameFunction(path); const replacement = nameFunction(path);
if (replacement) path.replaceWith(replacement); if (replacement) path.replaceWith(replacement);
} }
} },
}, },
ObjectProperty(path) { ObjectProperty(path) {
@ -18,7 +18,7 @@ export default function () {
const newNode = nameFunction(value); const newNode = nameFunction(value);
if (newNode) value.replaceWith(newNode); if (newNode) value.replaceWith(newNode);
} }
} },
} },
}; };
} }

View File

@ -6,7 +6,7 @@ export default function ({ types: t }) {
if (node.operator === "instanceof") { if (node.operator === "instanceof") {
path.replaceWith(t.callExpression(this.addHelper("instanceof"), [node.left, node.right])); path.replaceWith(t.callExpression(this.addHelper("instanceof"), [node.left, node.right]));
} }
} },
} },
}; };
} }

View File

@ -13,7 +13,7 @@ export default function () {
if (node.extra && /\\[u]/gi.test(node.extra.raw)) { if (node.extra && /\\[u]/gi.test(node.extra.raw)) {
node.extra = undefined; node.extra = undefined;
} }
} },
} },
}; };
} }

View File

@ -55,7 +55,7 @@ export default function ({ types: t }) {
this.sources.push([id.node, source]); this.sources.push([id.node, source]);
path.remove(); path.remove();
} },
}; };
return { return {
@ -104,7 +104,7 @@ export default function ({ types: t }) {
const { node } = path; const { node } = path;
const factory = buildFactory({ const factory = buildFactory({
PARAMS: params, PARAMS: params,
BODY: node.body BODY: node.body,
}); });
factory.expression.body.directives = node.directives; factory.expression.body.directives = node.directives;
node.directives = []; node.directives = [];
@ -112,10 +112,10 @@ export default function ({ types: t }) {
node.body = [buildDefine({ node.body = [buildDefine({
MODULE_NAME: moduleName, MODULE_NAME: moduleName,
SOURCES: sources, SOURCES: sources,
FACTORY: factory FACTORY: factory,
})]; })];
} },
} },
} },
}; };
} }

View File

@ -124,7 +124,7 @@ export default function () {
nodes.push(t.binaryExpression(operator, arg.node, t.numericLiteral(1))); nodes.push(t.binaryExpression(operator, arg.node, t.numericLiteral(1)));
path.replaceWithMultiple(t.sequenceExpression(nodes)); path.replaceWithMultiple(t.sequenceExpression(nodes));
} },
}; };
return { return {
@ -182,7 +182,7 @@ export default function () {
const varDecl = t.variableDeclaration("var", [ const varDecl = t.variableDeclaration("var", [
t.variableDeclarator(ref, buildRequire( t.variableDeclarator(ref, buildRequire(
t.stringLiteral(source) t.stringLiteral(source)
).expression) ).expression),
]); ]);
// Copy location from the original import statement for sourcemap // Copy location from the original import statement for sourcemap
@ -260,7 +260,7 @@ export default function () {
addTo(exports, id.name, defNode); addTo(exports, id.name, defNode);
path.replaceWithMultiple([ path.replaceWithMultiple([
declaration.node, declaration.node,
buildExportsAssignment(defNode, id) buildExportsAssignment(defNode, id),
]); ]);
} else { } else {
path.replaceWith(buildExportsAssignment(defNode, t.toExpression(declaration.node))); path.replaceWith(buildExportsAssignment(defNode, t.toExpression(declaration.node)));
@ -291,7 +291,7 @@ export default function () {
addTo(exports, id.name, id); addTo(exports, id.name, id);
path.replaceWithMultiple([ path.replaceWithMultiple([
declaration.node, declaration.node,
buildExportsAssignment(id, id) buildExportsAssignment(id, id),
]); ]);
nonHoistedExportNames[id.name] = true; nonHoistedExportNames[id.name] = true;
} else if (declaration.isVariableDeclaration()) { } else if (declaration.isVariableDeclaration()) {
@ -353,7 +353,7 @@ export default function () {
path.replaceWithMultiple(nodes); path.replaceWithMultiple(nodes);
} else if (path.isExportAllDeclaration()) { } else if (path.isExportAllDeclaration()) {
const exportNode = buildExportAll({ const exportNode = buildExportAll({
OBJECT: addRequire(path.node.source.value, path.node._blockHoist) OBJECT: addRequire(path.node.source.value, path.node._blockHoist),
}); });
exportNode.loc = path.node.loc; exportNode.loc = path.node.loc;
topNodes.push(exportNode); topNodes.push(exportNode);
@ -381,7 +381,7 @@ export default function () {
this.addHelper("interopRequireWildcard"), this.addHelper("interopRequireWildcard"),
[uid] [uid]
) )
) ),
]); ]);
if (maxBlockHoist > 0) { if (maxBlockHoist > 0) {
@ -411,7 +411,7 @@ export default function () {
this.addHelper("interopRequireDefault"), this.addHelper("interopRequireDefault"),
[uid] [uid]
) )
) ),
]); ]);
if (maxBlockHoist > 0) { if (maxBlockHoist > 0) {
@ -480,8 +480,8 @@ export default function () {
exports, exports,
requeueInParent: (newPath) => path.requeue(newPath), requeueInParent: (newPath) => path.requeue(newPath),
}); });
} },
} },
} },
}; };
} }

View File

@ -10,7 +10,7 @@ test("Re-export doesn't overwrite __esModule flag", function () {
const context = { const context = {
module: { module: {
exports: {} exports: {},
}, },
require: function (id) { require: function (id) {
if (id === "./dep") return depStub; if (id === "./dep") return depStub;

View File

@ -50,11 +50,11 @@ export default function ({ types: t }) {
let isPostUpdateExpression = path.isUpdateExpression() && !node.prefix; let isPostUpdateExpression = path.isUpdateExpression() && !node.prefix;
if (isPostUpdateExpression) { if (isPostUpdateExpression) {
if (node.operator === "++") if (node.operator === "++")
node = t.binaryExpression("+", node.argument, t.numericLiteral(1)); {node = t.binaryExpression("+", node.argument, t.numericLiteral(1));}
else if (node.operator === "--") else if (node.operator === "--")
node = t.binaryExpression("-", node.argument, t.numericLiteral(1)); {node = t.binaryExpression("-", node.argument, t.numericLiteral(1));}
else else
isPostUpdateExpression = false; {isPostUpdateExpression = false;}
} }
for (const exportedName of exportedNames) { for (const exportedName of exportedNames) {
@ -62,10 +62,10 @@ export default function ({ types: t }) {
} }
if (isPostUpdateExpression) if (isPostUpdateExpression)
node = t.sequenceExpression([node, path.node]); {node = t.sequenceExpression([node, path.node]);}
path.replaceWith(node); path.replaceWith(node);
} },
}; };
return { return {
@ -244,7 +244,7 @@ export default function ({ types: t }) {
const exportObjRef = path.scope.generateUidIdentifier("exportObj"); const exportObjRef = path.scope.generateUidIdentifier("exportObj");
setterBody.push(t.variableDeclaration("var", [ setterBody.push(t.variableDeclaration("var", [
t.variableDeclarator(exportObjRef, t.objectExpression([])) t.variableDeclarator(exportObjRef, t.objectExpression([])),
])); ]));
for (const node of specifiers.exports) { for (const node of specifiers.exports) {
@ -252,7 +252,7 @@ export default function ({ types: t }) {
setterBody.push(buildExportAll({ setterBody.push(buildExportAll({
KEY: path.scope.generateUidIdentifier("key"), KEY: path.scope.generateUidIdentifier("key"),
EXPORT_OBJ: exportObjRef, EXPORT_OBJ: exportObjRef,
TARGET: target TARGET: target,
})); }));
} else if (t.isExportSpecifier(node)) { } else if (t.isExportSpecifier(node)) {
setterBody.push(t.expressionStatement( setterBody.push(t.expressionStatement(
@ -287,7 +287,7 @@ export default function ({ types: t }) {
path.traverse(reassignmentVisitor, { path.traverse(reassignmentVisitor, {
exports: exportNames, exports: exportNames,
buildCall: buildExportCall, buildCall: buildExportCall,
scope: path.scope scope: path.scope,
}); });
for (const path of removedPaths) { for (const path of removedPaths) {
@ -304,11 +304,11 @@ export default function ({ types: t }) {
SOURCES: sources, SOURCES: sources,
BODY: path.node.body, BODY: path.node.body,
EXPORT_IDENTIFIER: exportIdent, EXPORT_IDENTIFIER: exportIdent,
CONTEXT_IDENTIFIER: contextIdent CONTEXT_IDENTIFIER: contextIdent,
}) }),
]; ];
} },
} },
} },
}; };
} }

View File

@ -121,7 +121,7 @@ export default function ({ types: t }) {
const globalExport = buildGlobalExport({ const globalExport = buildGlobalExport({
BROWSER_ARGUMENTS: browserArgs, BROWSER_ARGUMENTS: browserArgs,
PREREQUISITE_ASSIGNMENTS: prerequisiteAssignments, PREREQUISITE_ASSIGNMENTS: prerequisiteAssignments,
GLOBAL_TO_ASSIGN: globalToAssign GLOBAL_TO_ASSIGN: globalToAssign,
}); });
last.replaceWith(buildWrapper({ last.replaceWith(buildWrapper({
@ -129,10 +129,10 @@ export default function ({ types: t }) {
AMD_ARGUMENTS: amdArgs, AMD_ARGUMENTS: amdArgs,
COMMON_ARGUMENTS: commonArgs, COMMON_ARGUMENTS: commonArgs,
GLOBAL_EXPORT: globalExport, GLOBAL_EXPORT: globalExport,
FUNC: func FUNC: func,
})); }));
} },
} },
} },
}; };
} }

View File

@ -4,11 +4,11 @@ export default function ({ types: t }) {
function Property(path, node, scope, getObjectRef, file) { function Property(path, node, scope, getObjectRef, file) {
const replaceSupers = new ReplaceSupers({ const replaceSupers = new ReplaceSupers({
getObjectRef: getObjectRef, getObjectRef: getObjectRef,
methodNode: node, methodNode: node,
methodPath: path, methodPath: path,
isStatic: true, isStatic: true,
scope: scope, scope: scope,
file: file file: file,
}); });
replaceSupers.replace(); replaceSupers.replace();
@ -40,8 +40,8 @@ export default function ({ types: t }) {
path.scope.push({ id: objectRef }); path.scope.push({ id: objectRef });
path.replaceWith(t.assignmentExpression("=", objectRef, path.node)); path.replaceWith(t.assignmentExpression("=", objectRef, path.node));
} }
} },
} },
} },
}; };
} }

View File

@ -40,7 +40,7 @@ const iifeVisitor = {
Scope(path) { Scope(path) {
// different bindings // different bindings
path.skip(); path.skip();
} },
}; };
export const visitor = { export const visitor = {
@ -53,7 +53,7 @@ export const visitor = {
const state = { const state = {
iife: false, iife: false,
scope: scope scope: scope,
}; };
const body = []; const body = [];
@ -67,8 +67,8 @@ export const visitor = {
const defNode = buildDefaultParam({ const defNode = buildDefaultParam({
VARIABLE_NAME: left, VARIABLE_NAME: left,
DEFAULT_VALUE: right, DEFAULT_VALUE: right,
ARGUMENT_KEY: t.numericLiteral(i), ARGUMENT_KEY: t.numericLiteral(i),
ARGUMENTS: argsIdentifier ARGUMENTS: argsIdentifier,
}); });
defNode._blockHoist = node.params.length - i; defNode._blockHoist = node.params.length - i;
body.push(defNode); body.push(defNode);
@ -90,7 +90,7 @@ export const visitor = {
continue; continue;
} }
const left = param.get("left"); const left = param.get("left");
const right = param.get("right"); const right = param.get("right");
// //
@ -134,5 +134,5 @@ export const visitor = {
} else { } else {
path.get("body").unshiftContainer("body", body); path.get("body").unshiftContainer("body", body);
} }
} },
}; };

View File

@ -15,7 +15,7 @@ export const visitor = {
const uid = path.scope.generateUidIdentifier("ref"); const uid = path.scope.generateUidIdentifier("ref");
const declar = t.variableDeclaration("let", [ const declar = t.variableDeclaration("let", [
t.variableDeclarator(param.node, uid) t.variableDeclarator(param.node, uid),
]); ]);
declar._blockHoist = outputParamsLength - i; declar._blockHoist = outputParamsLength - i;
@ -25,5 +25,5 @@ export const visitor = {
param.replaceWith(uid); param.replaceWith(uid);
} }
} }
} },
}; };

View File

@ -17,7 +17,7 @@ export default function () {
break; break;
} }
} }
} },
}, destructuring.visitor, rest.visitor, def.visitor]) }, destructuring.visitor, rest.visitor, def.visitor]),
}; };
} }

View File

@ -153,7 +153,7 @@ const memberExpressionOptimisationVisitor = {
if (node.name === state.name) { if (node.name === state.name) {
state.deopted = true; state.deopted = true;
} }
} },
}; };
function hasRest(node) { function hasRest(node) {
return t.isRestElement(node.params[node.params.length - 1]); return t.isRestElement(node.params[node.params.length - 1]);
@ -178,7 +178,7 @@ function optimiseIndexGetter(path, argsId, offset) {
path.parentPath.replaceWith(restIndexImpure({ path.parentPath.replaceWith(restIndexImpure({
ARGUMENTS: argsId, ARGUMENTS: argsId,
INDEX: index, INDEX: index,
REF: temp REF: temp,
})); }));
} else { } else {
path.parentPath.replaceWith(restIndex({ path.parentPath.replaceWith(restIndex({
@ -214,10 +214,10 @@ export const visitor = {
// check and optimise for extremely common cases // check and optimise for extremely common cases
const state = { const state = {
references: [], references: [],
offset: node.params.length, offset: node.params.length,
argumentsNode: argsId, argumentsNode: argsId,
outerBinding: scope.getBindingIdentifier(rest.name), outerBinding: scope.getBindingIdentifier(rest.name),
// candidate member expressions we could optimise if there are no other references // candidate member expressions we could optimise if there are no other references
candidates: [], candidates: [],
@ -295,10 +295,10 @@ export const visitor = {
ARGUMENTS: argsId, ARGUMENTS: argsId,
ARRAY_KEY: arrKey, ARRAY_KEY: arrKey,
ARRAY_LEN: arrLen, ARRAY_LEN: arrLen,
START: start, START: start,
ARRAY: rest, ARRAY: rest,
KEY: key, KEY: key,
LEN: len, LEN: len,
}); });
if (state.deopted) { if (state.deopted) {
@ -322,5 +322,5 @@ export const visitor = {
target.insertBefore(loop); target.insertBefore(loop);
} }
} },
}; };

View File

@ -21,7 +21,7 @@ export default function () {
if (node.shorthand) { if (node.shorthand) {
node.shorthand = false; node.shorthand = false;
} }
} },
} },
}; };
} }

View File

@ -136,7 +136,7 @@ export default function ({ types: t }) {
), ),
[] []
)); ));
} },
} },
}; };
} }

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