Update prettier to v2 (#11579)

Co-authored-by: Nicolò Ribaudo <nicolo.ribaudo@gmail.com>
This commit is contained in:
Bogdan Savluk 2020-06-07 22:21:33 +02:00 committed by GitHub
parent 426acf336e
commit 4108524856
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
147 changed files with 1018 additions and 1106 deletions

View File

@ -33,7 +33,7 @@ function getIndexFromPackage(name) {
} }
function compilationLogger() { function compilationLogger() {
return through.obj(function(file, enc, callback) { return through.obj(function (file, enc, callback) {
fancyLog(`Compiling '${chalk.cyan(file.relative)}'...`); fancyLog(`Compiling '${chalk.cyan(file.relative)}'...`);
callback(null, file); callback(null, file);
}); });
@ -48,7 +48,7 @@ function errorsLogger() {
} }
function rename(fn) { function rename(fn) {
return through.obj(function(file, enc, callback) { return through.obj(function (file, enc, callback) {
file.path = fn(file); file.path = fn(file);
callback(null, file); callback(null, file);
}); });

View File

@ -1,6 +1,6 @@
"use strict"; "use strict";
module.exports = function(api) { module.exports = function (api) {
const env = api.env(); const env = api.env();
const includeCoverage = process.env.BABEL_COVERAGE === "true"; const includeCoverage = process.env.BABEL_COVERAGE === "true";

View File

@ -1,6 +1,6 @@
import syntaxObjectRestSpread from "@babel/plugin-syntax-object-rest-spread"; import syntaxObjectRestSpread from "@babel/plugin-syntax-object-rest-spread";
export default function({ types: t }) { export default function ({ types: t }) {
return { return {
inherits: syntaxObjectRestSpread, inherits: syntaxObjectRestSpread,

View File

@ -1,6 +1,6 @@
import syntaxOptionalCatchBinding from "@babel/plugin-syntax-optional-catch-binding"; import syntaxOptionalCatchBinding from "@babel/plugin-syntax-optional-catch-binding";
export default function({ types: t }) { export default function ({ types: t }) {
return { return {
inherits: syntaxOptionalCatchBinding, inherits: syntaxOptionalCatchBinding,

View File

@ -237,7 +237,7 @@ class Referencer extends OriginalReferencer {
this._checkIdentifierOrVisit(name); this._checkIdentifierOrVisit(name);
} }
} }
scope.__define = function() { scope.__define = function () {
return parentScope.__define.apply(parentScope, arguments); return parentScope.__define.apply(parentScope, arguments);
}; };

View File

@ -2,7 +2,7 @@ import convertTokens from "./convertTokens";
import convertComments from "./convertComments"; import convertComments from "./convertComments";
import convertAST from "./convertAST"; import convertAST from "./convertAST";
export default function(ast, code) { export default function (ast, code) {
ast.tokens = convertTokens(ast.tokens, code); ast.tokens = convertTokens(ast.tokens, code);
convertComments(ast.comments); convertComments(ast.comments);
convertAST(ast, code); convertAST(ast, code);

View File

@ -84,7 +84,7 @@ describe("Babel and Espree", () => {
}); });
describe("compatibility", () => { describe("compatibility", () => {
it("should allow ast.analyze to be called without options", function() { it("should allow ast.analyze to be called without options", function () {
const ast = parseForESLint("`test`", { const ast = parseForESLint("`test`", {
eslintScopeManager: true, eslintScopeManager: true,
eslintVisitorKeys: true, eslintVisitorKeys: true,

View File

@ -57,13 +57,13 @@ function report(context, node, missing) {
if (!missing) { if (!missing) {
message = "Missing semicolon."; message = "Missing semicolon.";
loc = loc.end; loc = loc.end;
fix = function(fixer) { fix = function (fixer) {
return fixer.insertTextAfter(lastToken, ";"); return fixer.insertTextAfter(lastToken, ";");
}; };
} else { } else {
message = "Extra semicolon."; message = "Extra semicolon.";
loc = loc.start; loc = loc.start;
fix = function(fixer) { fix = function (fixer) {
return fixer.remove(lastToken); return fixer.remove(lastToken);
}; };
} }

View File

@ -50,8 +50,8 @@ function MODULES(pattern) {
*/ */
function extractPatterns(patterns, type) { function extractPatterns(patterns, type) {
// Clone and apply the pattern environment. // Clone and apply the pattern environment.
const patternsList = patterns.map(function(pattern) { const patternsList = patterns.map(function (pattern) {
return pattern[type].map(function(applyCondition) { return pattern[type].map(function (applyCondition) {
const thisPattern = cloneDeep(pattern); const thisPattern = cloneDeep(pattern);
applyCondition(thisPattern); applyCondition(thisPattern);

View File

@ -57,7 +57,7 @@
"lodash": "^4.17.13", "lodash": "^4.17.13",
"mergeiterator": "^1.2.5", "mergeiterator": "^1.2.5",
"output-file-sync": "^2.0.0", "output-file-sync": "^2.0.0",
"prettier": "^1.19.1", "prettier": "^2.0.5",
"pump": "^3.0.0", "pump": "^3.0.0",
"rimraf": "^2.6.3", "rimraf": "^2.6.3",
"rollup": "1.27.9", "rollup": "1.27.9",

View File

@ -22,7 +22,7 @@ function outputFileSync(filePath: string, data: string | Buffer): void {
fs.writeFileSync(filePath, data); fs.writeFileSync(filePath, data);
} }
export default async function({ export default async function ({
cliOptions, cliOptions,
babelOptions, babelOptions,
}: CmdOptions): Promise<void> { }: CmdOptions): Promise<void> {
@ -143,7 +143,7 @@ export default async function({
let startTime = null; let startTime = null;
const logSuccess = debounce( const logSuccess = debounce(
function() { function () {
if (startTime === null) { if (startTime === null) {
// This should never happen, but just in case it's better // This should never happen, but just in case it's better
// to ignore the log message rather than making @babel/cli crash. // to ignore the log message rather than making @babel/cli crash.
@ -189,7 +189,7 @@ export default async function({
if (cliOptions.watch) { if (cliOptions.watch) {
const chokidar = util.requireChokidar(); const chokidar = util.requireChokidar();
filenames.forEach(function(filenameOrDir: string): void { filenames.forEach(function (filenameOrDir: string): void {
const watcher = chokidar.watch(filenameOrDir, { const watcher = chokidar.watch(filenameOrDir, {
persistent: true, persistent: true,
ignoreInitial: true, ignoreInitial: true,
@ -203,8 +203,8 @@ export default async function({
// when we are sure that all the files have been compiled. // when we are sure that all the files have been compiled.
let processing = 0; let processing = 0;
["add", "change"].forEach(function(type: string): void { ["add", "change"].forEach(function (type: string): void {
watcher.on(type, async function(filename: string) { watcher.on(type, async function (filename: string) {
processing++; processing++;
if (startTime === null) startTime = process.hrtime(); if (startTime === null) startTime = process.hrtime();

View File

@ -16,7 +16,7 @@ type CompilationOutput = {
map: Object, map: Object,
}; };
export default async function({ export default async function ({
cliOptions, cliOptions,
babelOptions, babelOptions,
}: CmdOptions): Promise<void> { }: CmdOptions): Promise<void> {
@ -41,7 +41,7 @@ export default async function({
const consumer = new sourceMap.SourceMapConsumer(result.map); const consumer = new sourceMap.SourceMapConsumer(result.map);
const sources = new Set(); const sources = new Set();
consumer.eachMapping(function(mapping) { consumer.eachMapping(function (mapping) {
if (mapping.source != null) sources.add(mapping.source); if (mapping.source != null) sources.add(mapping.source);
map.addMapping({ map.addMapping({
@ -111,13 +111,13 @@ export default async function({
process.stdin.setEncoding("utf8"); process.stdin.setEncoding("utf8");
process.stdin.on("readable", function() { process.stdin.on("readable", function () {
const chunk = process.stdin.read(); const chunk = process.stdin.read();
// $FlowIgnore // $FlowIgnore
if (chunk !== null) code += chunk; if (chunk !== null) code += chunk;
}); });
process.stdin.on("end", function() { process.stdin.on("end", function () {
resolve(code); resolve(code);
}); });
process.stdin.on("error", reject); process.stdin.on("error", reject);
@ -144,7 +144,7 @@ export default async function({
async function walk(filenames: Array<string>): Promise<void> { async function walk(filenames: Array<string>): Promise<void> {
const _filenames = []; const _filenames = [];
filenames.forEach(function(filename) { filenames.forEach(function (filename) {
if (!fs.existsSync(filename)) return; if (!fs.existsSync(filename)) return;
const stat = fs.statSync(filename); const stat = fs.statSync(filename);
@ -157,7 +157,7 @@ export default async function({
cliOptions.includeDotfiles, cliOptions.includeDotfiles,
cliOptions.extensions, cliOptions.extensions,
) )
.forEach(function(filename) { .forEach(function (filename) {
_filenames.push(path.join(dirname, filename)); _filenames.push(path.join(dirname, filename));
}); });
} else { } else {
@ -166,7 +166,7 @@ export default async function({
}); });
const results = await Promise.all( const results = await Promise.all(
_filenames.map(async function(filename: string): Promise<Object> { _filenames.map(async function (filename: string): Promise<Object> {
let sourceFilename = filename; let sourceFilename = filename;
if (cliOptions.outFile) { if (cliOptions.outFile) {
sourceFilename = path.relative( sourceFilename = path.relative(
@ -224,7 +224,7 @@ export default async function({
pollInterval: 10, pollInterval: 10,
}, },
}) })
.on("all", function(type: string, filename: string): void { .on("all", function (type: string, filename: string): void {
if ( if (
!util.isCompilableExtension(filename, cliOptions.extensions) && !util.isCompilableExtension(filename, cliOptions.extensions) &&
!filenames.includes(filename) !filenames.includes(filename)

View File

@ -189,7 +189,7 @@ export default function parseArgv(args: Array<string>): CmdOptions | null {
const errors = []; const errors = [];
let filenames = commander.args.reduce(function(globbed, input) { let filenames = commander.args.reduce(function (globbed, input) {
let files = glob.sync(input); let files = glob.sync(input);
if (!files.length) files = [input]; if (!files.length) files = [input];
return globbed.concat(files); return globbed.concat(files);
@ -197,7 +197,7 @@ export default function parseArgv(args: Array<string>): CmdOptions | null {
filenames = uniq(filenames); filenames = uniq(filenames);
filenames.forEach(function(filename) { filenames.forEach(function (filename) {
if (!fs.existsSync(filename)) { if (!fs.existsSync(filename)) {
errors.push(filename + " does not exist"); errors.push(filename + " does not exist");
} }
@ -255,7 +255,7 @@ export default function parseArgv(args: Array<string>): CmdOptions | null {
if (errors.length) { if (errors.length) {
console.error("babel:"); console.error("babel:");
errors.forEach(function(e) { errors.forEach(function (e) {
console.error(" " + e); console.error(" " + e);
}); });
return null; return null;

View File

@ -33,7 +33,7 @@ export function readdirForCompilable(
includeDotfiles: boolean, includeDotfiles: boolean,
altExts?: Array<string>, altExts?: Array<string>,
): Array<string> { ): Array<string> {
return readdir(dirname, includeDotfiles, function(filename) { return readdir(dirname, includeDotfiles, function (filename) {
return isCompilableExtension(filename, altExts); return isCompilableExtension(filename, altExts);
}); });
} }
@ -96,7 +96,7 @@ export function compile(
export function deleteDir(path: string): void { export function deleteDir(path: string): void {
if (fs.existsSync(path)) { if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function(file) { fs.readdirSync(path).forEach(function (file) {
const curPath = path + "/" + file; const curPath = path + "/" + file;
if (fs.lstatSync(curPath).isDirectory()) { if (fs.lstatSync(curPath).isDirectory()) {
// recurse // recurse
@ -110,7 +110,7 @@ export function deleteDir(path: string): void {
} }
} }
process.on("uncaughtException", function(err) { process.on("uncaughtException", function (err) {
console.error(err); console.error(err);
process.exitCode = 1; process.exitCode = 1;
}); });

View File

@ -10,11 +10,11 @@ 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 fileFilter = function(x) { const fileFilter = function (x) {
return x !== ".DS_Store"; return x !== ".DS_Store";
}; };
const outputFileSync = function(filePath, data) { const outputFileSync = function (filePath, data) {
makeDirSync(path.dirname(filePath)); makeDirSync(path.dirname(filePath));
fs.writeFileSync(filePath, data); fs.writeFileSync(filePath, data);
}; };
@ -27,29 +27,29 @@ const pluginLocs = [
path.join(__dirname, "/../../babel-plugin-transform-modules-commonjs"), path.join(__dirname, "/../../babel-plugin-transform-modules-commonjs"),
].join(","); ].join(",");
const readDir = function(loc, filter) { const readDir = function (loc, filter) {
const files = {}; const files = {};
if (fs.existsSync(loc)) { if (fs.existsSync(loc)) {
readdir(loc, filter).forEach(function(filename) { readdir(loc, filter).forEach(function (filename) {
files[filename] = helper.readFile(path.join(loc, filename)); files[filename] = helper.readFile(path.join(loc, filename));
}); });
} }
return files; return files;
}; };
const saveInFiles = function(files) { const saveInFiles = function (files) {
// Place an empty .babelrc in each test so tests won't unexpectedly get to repo-level config. // Place an empty .babelrc in each test so tests won't unexpectedly get to repo-level config.
if (!fs.existsSync(".babelrc")) { if (!fs.existsSync(".babelrc")) {
outputFileSync(".babelrc", "{}"); outputFileSync(".babelrc", "{}");
} }
Object.keys(files).forEach(function(filename) { Object.keys(files).forEach(function (filename) {
const content = files[filename]; const content = files[filename];
outputFileSync(filename, content); outputFileSync(filename, content);
}); });
}; };
const normalizeOutput = function(str, cwd) { const normalizeOutput = function (str, cwd) {
let prev; let prev;
do { do {
prev = str; prev = str;
@ -59,7 +59,7 @@ const normalizeOutput = function(str, cwd) {
return str.replace(/\(\d+ms\)/g, "(123ms)"); return str.replace(/\(\d+ms\)/g, "(123ms)");
}; };
const assertTest = function(stdout, stderr, opts, cwd) { const assertTest = function (stdout, stderr, opts, cwd) {
stdout = normalizeOutput(stdout, cwd); stdout = normalizeOutput(stdout, cwd);
stderr = normalizeOutput(stderr, cwd); stderr = normalizeOutput(stderr, cwd);
@ -94,7 +94,7 @@ const assertTest = function(stdout, stderr, opts, cwd) {
if (opts.outFiles) { if (opts.outFiles) {
const actualFiles = readDir(tmpLoc, fileFilter); const actualFiles = readDir(tmpLoc, fileFilter);
Object.keys(actualFiles).forEach(function(filename) { Object.keys(actualFiles).forEach(function (filename) {
try { try {
if ( if (
// saveInFiles always creates an empty .babelrc, so lets exclude for now // saveInFiles always creates an empty .babelrc, so lets exclude for now
@ -113,16 +113,16 @@ const assertTest = function(stdout, stderr, opts, cwd) {
} }
}); });
Object.keys(opts.outFiles).forEach(function(filename) { Object.keys(opts.outFiles).forEach(function (filename) {
expect(actualFiles).toHaveProperty([filename]); expect(actualFiles).toHaveProperty([filename]);
}); });
} }
}; };
const buildTest = function(binName, testName, opts) { const buildTest = function (binName, testName, opts) {
const binLoc = path.join(__dirname, "../lib", binName); const binLoc = path.join(__dirname, "../lib", binName);
return function(callback) { return function (callback) {
saveInFiles(opts.inFiles); saveInFiles(opts.inFiles);
let args = [binLoc]; let args = [binLoc];
@ -138,15 +138,15 @@ const buildTest = function(binName, testName, opts) {
let stderr = ""; let stderr = "";
let stdout = ""; let stdout = "";
spawn.stderr.on("data", function(chunk) { spawn.stderr.on("data", function (chunk) {
stderr += chunk; stderr += chunk;
}); });
spawn.stdout.on("data", function(chunk) { spawn.stdout.on("data", function (chunk) {
stdout += chunk; stdout += chunk;
}); });
spawn.on("close", function() { spawn.on("close", function () {
let err; let err;
try { try {
@ -170,11 +170,11 @@ const buildTest = function(binName, testName, opts) {
}; };
}; };
fs.readdirSync(fixtureLoc).forEach(function(binName) { fs.readdirSync(fixtureLoc).forEach(function (binName) {
if (binName.startsWith(".")) return; if (binName.startsWith(".")) return;
const suiteLoc = path.join(fixtureLoc, binName); const suiteLoc = path.join(fixtureLoc, binName);
describe("bin/" + binName, function() { describe("bin/" + binName, function () {
let cwd; let cwd;
beforeEach(() => { beforeEach(() => {
@ -195,7 +195,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) {
process.chdir(cwd); process.chdir(cwd);
}); });
fs.readdirSync(suiteLoc).forEach(function(testName) { fs.readdirSync(suiteLoc).forEach(function (testName) {
if (testName.startsWith(".")) return; if (testName.startsWith(".")) return;
const testLoc = path.join(suiteLoc, testName); const testLoc = path.join(suiteLoc, testName);
@ -229,7 +229,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) {
merge(opts, taskOpts); merge(opts, taskOpts);
} }
["stdout", "stdin", "stderr"].forEach(function(key) { ["stdout", "stdin", "stderr"].forEach(function (key) {
const loc = path.join(testLoc, key + ".txt"); const loc = path.join(testLoc, key + ".txt");
opts[key + "Path"] = loc; opts[key + "Path"] = loc;
if (fs.existsSync(loc)) { if (fs.existsSync(loc)) {

View File

@ -175,7 +175,7 @@ export function codeFrameColumns(
* Create a code frame, adding line numbers, code highlighting, and pointing to a given position. * Create a code frame, adding line numbers, code highlighting, and pointing to a given position.
*/ */
export default function( export default function (
rawLines: string, rawLines: string,
lineNumber: number, lineNumber: number,
colNumber: ?number, colNumber: ?number,

View File

@ -2,8 +2,8 @@ import chalk from "chalk";
import stripAnsi from "strip-ansi"; import stripAnsi from "strip-ansi";
import codeFrame, { codeFrameColumns } from ".."; import codeFrame, { codeFrameColumns } from "..";
describe("@babel/code-frame", function() { describe("@babel/code-frame", function () {
test("basic usage", function() { test("basic usage", function () {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
expect(codeFrame(rawLines, 2, 16)).toEqual( expect(codeFrame(rawLines, 2, 16)).toEqual(
[ [
@ -15,14 +15,14 @@ describe("@babel/code-frame", function() {
); );
}); });
test("optional column number", function() { test("optional column number", function () {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
expect(codeFrame(rawLines, 2, null)).toEqual( expect(codeFrame(rawLines, 2, null)).toEqual(
[" 1 | class Foo {", "> 2 | constructor()", " 3 | };"].join("\n"), [" 1 | class Foo {", "> 2 | constructor()", " 3 | };"].join("\n"),
); );
}); });
test("maximum context lines and padding", function() { test("maximum context lines and padding", function () {
const rawLines = [ const rawLines = [
"/**", "/**",
" * Sums two numbers.", " * Sums two numbers.",
@ -49,7 +49,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("no unnecessary padding due to one-off errors", function() { test("no unnecessary padding due to one-off errors", function () {
const rawLines = [ const rawLines = [
"/**", "/**",
" * Sums two numbers.", " * Sums two numbers.",
@ -76,7 +76,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("tabs", function() { test("tabs", function () {
const rawLines = [ const rawLines = [
"\tclass Foo {", "\tclass Foo {",
"\t \t\t constructor\t(\t)", "\t \t\t constructor\t(\t)",
@ -92,7 +92,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.highlightCode", function() { test("opts.highlightCode", function () {
const rawLines = "console.log('babel')"; const rawLines = "console.log('babel')";
const result = codeFrame(rawLines, 1, 9, { highlightCode: true }); const result = codeFrame(rawLines, 1, 9, { highlightCode: true });
const stripped = stripAnsi(result); const stripped = stripAnsi(result);
@ -102,7 +102,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.highlightCode with multiple columns and lines", function() { test("opts.highlightCode with multiple columns and lines", function () {
// prettier-ignore // prettier-ignore
const rawLines = [ const rawLines = [
"function a(b, c) {", "function a(b, c) {",
@ -141,7 +141,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.linesAbove", function() { test("opts.linesAbove", function () {
const rawLines = [ const rawLines = [
"/**", "/**",
" * Sums two numbers.", " * Sums two numbers.",
@ -167,7 +167,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.linesBelow", function() { test("opts.linesBelow", function () {
const rawLines = [ const rawLines = [
"/**", "/**",
" * Sums two numbers.", " * Sums two numbers.",
@ -192,7 +192,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.linesAbove and opts.linesBelow", function() { test("opts.linesAbove and opts.linesBelow", function () {
const rawLines = [ const rawLines = [
"/**", "/**",
" * Sums two numbers.", " * Sums two numbers.",
@ -213,7 +213,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.linesAbove no lines above", function() { test("opts.linesAbove no lines above", function () {
const rawLines = [ const rawLines = [
"class Foo {", "class Foo {",
" constructor() {", " constructor() {",
@ -233,7 +233,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.linesBelow no lines below", function() { test("opts.linesBelow no lines below", function () {
const rawLines = [ const rawLines = [
"class Foo {", "class Foo {",
" constructor() {", " constructor() {",
@ -246,7 +246,7 @@ describe("@babel/code-frame", function() {
).toEqual([" 1 | class Foo {", "> 2 | constructor() {"].join("\n")); ).toEqual([" 1 | class Foo {", "> 2 | constructor() {"].join("\n"));
}); });
test("opts.linesBelow single line", function() { test("opts.linesBelow single line", function () {
const rawLines = [ const rawLines = [
"class Foo {", "class Foo {",
" constructor() {", " constructor() {",
@ -263,7 +263,7 @@ describe("@babel/code-frame", function() {
).toEqual(["> 2 | constructor() {"].join("\n")); ).toEqual(["> 2 | constructor() {"].join("\n"));
}); });
test("opts.forceColor", function() { test("opts.forceColor", function () {
const marker = chalk.red.bold; const marker = chalk.red.bold;
const gutter = chalk.grey; const gutter = chalk.grey;
@ -285,7 +285,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("basic usage, new API", function() { test("basic usage, new API", function () {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
expect( expect(
codeFrameColumns(rawLines, { start: { line: 2, column: 16 } }), codeFrameColumns(rawLines, { start: { line: 2, column: 16 } }),
@ -299,7 +299,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("mark multiple columns", function() { test("mark multiple columns", function () {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
expect( expect(
codeFrameColumns(rawLines, { codeFrameColumns(rawLines, {
@ -316,7 +316,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("mark multiple columns across lines", function() { test("mark multiple columns across lines", function () {
const rawLines = ["class Foo {", " constructor() {", " }", "};"].join( const rawLines = ["class Foo {", " constructor() {", " }", "};"].join(
"\n", "\n",
); );
@ -337,7 +337,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("mark multiple columns across multiple lines", function() { test("mark multiple columns across multiple lines", function () {
const rawLines = [ const rawLines = [
"class Foo {", "class Foo {",
" constructor() {", " constructor() {",
@ -364,7 +364,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("mark across multiple lines without columns", function() { test("mark across multiple lines without columns", function () {
const rawLines = [ const rawLines = [
"class Foo {", "class Foo {",
" constructor() {", " constructor() {",
@ -385,7 +385,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.message", function() { test("opts.message", function () {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
expect( expect(
codeFrameColumns( codeFrameColumns(
@ -405,7 +405,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.message without column", function() { test("opts.message without column", function () {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
expect( expect(
codeFrameColumns( codeFrameColumns(
@ -425,7 +425,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.message with multiple lines", function() { test("opts.message with multiple lines", function () {
const rawLines = [ const rawLines = [
"class Foo {", "class Foo {",
" constructor() {", " constructor() {",
@ -458,7 +458,7 @@ describe("@babel/code-frame", function() {
); );
}); });
test("opts.message with multiple lines without columns", function() { test("opts.message with multiple lines without columns", function () {
const rawLines = [ const rawLines = [
"class Foo {", "class Foo {",
" constructor() {", " constructor() {",

View File

@ -122,7 +122,7 @@ exports.generateData = (environments, features) => {
}); });
}; };
exports.writeFile = function(data, dataPath, name) { exports.writeFile = function (data, dataPath, name) {
const stringified = JSON.stringify(data, null, 2) + "\n"; const stringified = JSON.stringify(data, null, 2) + "\n";
if (process.env.CHECK_COMPAT_DATA) { if (process.env.CHECK_COMPAT_DATA) {
const currentData = fs.readFileSync(dataPath, "utf8"); const currentData = fs.readFileSync(dataPath, "utf8");

View File

@ -330,7 +330,7 @@ class CacheConfigurator<SideChannel = void> {
validator(): SideChannel => Handler<boolean> { validator(): SideChannel => Handler<boolean> {
const pairs = this._pairs; const pairs = this._pairs;
return function*(data: SideChannel) { return function* (data: SideChannel) {
for (const [key, fn] of pairs) { for (const [key, fn] of pairs) {
if (key !== (yield* fn(data))) return false; if (key !== (yield* fn(data))) return false;
} }

View File

@ -429,7 +429,7 @@ function makeChainWalker<ArgT: { options: ValidatedOptions, dirname: string }>({
ConfigContext, ConfigContext,
Set<ConfigFile> | void, Set<ConfigFile> | void,
) => Handler<ConfigChain | null> { ) => Handler<ConfigChain | null> {
return function*(input, context, files = new Set()) { return function* (input, context, files = new Set()) {
const { dirname } = input; const { dirname } = input;
const flattenedConfigs = []; const flattenedConfigs = [];

View File

@ -9,7 +9,7 @@ import nodeFs from "fs";
export function makeStaticFileCache<T>( export function makeStaticFileCache<T>(
fn: (string, string) => T, fn: (string, string) => T,
): Gensync<[string], T | null> { ): Gensync<[string], T | null> {
return (makeStrongCache(function*( return (makeStrongCache(function* (
filepath: string, filepath: string,
cache: CacheConfigurator<?void>, cache: CacheConfigurator<?void>,
): Handler<null | T> { ): Handler<null | T> {

View File

@ -211,7 +211,7 @@ export default gensync<[any], ResolvedConfig | null>(function* loadFullConfig(
/** /**
* Load a generic plugin/preset from the given descriptor loaded from the config object. * Load a generic plugin/preset from the given descriptor loaded from the config object.
*/ */
const loadDescriptor = makeWeakCache(function*( const loadDescriptor = makeWeakCache(function* (
{ value, options, dirname, alias }: UnloadedDescriptor, { value, options, dirname, alias }: UnloadedDescriptor,
cache: CacheConfigurator<SimpleContext>, cache: CacheConfigurator<SimpleContext>,
): Handler<LoadedDescriptor> { ): Handler<LoadedDescriptor> {
@ -277,7 +277,7 @@ function* loadPluginDescriptor(
); );
} }
const instantiatePlugin = makeWeakCache(function*( const instantiatePlugin = makeWeakCache(function* (
{ value, options, dirname, alias }: LoadedDescriptor, { value, options, dirname, alias }: LoadedDescriptor,
cache: CacheConfigurator<SimpleContext>, cache: CacheConfigurator<SimpleContext>,
): Handler<Plugin> { ): Handler<Plugin> {
@ -383,7 +383,7 @@ function chain(a, b) {
const fns = [a, b].filter(Boolean); const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0]; if (fns.length <= 1) return fns[0];
return function(...args) { return function (...args) {
for (const fn of fns) { for (const fn of fns) {
fn.apply(this, args); fn.apply(this, args);
} }

View File

@ -15,7 +15,7 @@ import { loadPartialConfig as loadPartialConfigRunner } from "./partial";
export { loadFullConfig as default }; export { loadFullConfig as default };
export type { PartialConfig } from "./partial"; export type { PartialConfig } from "./partial";
const loadOptionsRunner = gensync<[mixed], Object | null>(function*(opts) { const loadOptionsRunner = gensync<[mixed], Object | null>(function* (opts) {
const config = yield* loadFullConfig(opts); const config = yield* loadFullConfig(opts);
// NOTE: We want to return "null" explicitly, while ?. alone returns undefined // NOTE: We want to return "null" explicitly, while ?. alone returns undefined
return config?.options ?? null; return config?.options ?? null;

View File

@ -135,30 +135,32 @@ export default function* loadPrivatePartialConfig(
}; };
} }
export const loadPartialConfig = gensync<[any], PartialConfig | null>(function*( export const loadPartialConfig = gensync<[any], PartialConfig | null>(
inputOpts: mixed, function* (inputOpts: mixed): Handler<PartialConfig | null> {
): Handler<PartialConfig | null> { const result: ?PrivPartialConfig = yield* loadPrivatePartialConfig(
const result: ?PrivPartialConfig = yield* loadPrivatePartialConfig(inputOpts); inputOpts,
if (!result) return null; );
if (!result) return null;
const { options, babelrc, ignore, config } = result; const { options, babelrc, ignore, config } = result;
(options.plugins || []).forEach(item => { (options.plugins || []).forEach(item => {
if (item.value instanceof Plugin) { if (item.value instanceof Plugin) {
throw new Error( throw new Error(
"Passing cached plugin instances is not supported in " + "Passing cached plugin instances is not supported in " +
"babel.loadPartialConfig()", "babel.loadPartialConfig()",
); );
} }
}); });
return new PartialConfig( return new PartialConfig(
options, options,
babelrc ? babelrc.filepath : undefined, babelrc ? babelrc.filepath : undefined,
ignore ? ignore.filepath : undefined, ignore ? ignore.filepath : undefined,
config ? config.filepath : undefined, config ? config.filepath : undefined,
); );
}); },
);
export type { PartialConfig }; export type { PartialConfig };

View File

@ -6,7 +6,7 @@ type MaybePromise<T> = T | Promise<T>;
const id = x => x; const id = x => x;
const runGenerator = gensync(function*(item) { const runGenerator = gensync(function* (item) {
return yield* item; return yield* item;
}); });
@ -76,10 +76,10 @@ export function forwardAsync<ActionArgs: mixed[], ActionReturn, Return>(
export const onFirstPause = (gensync<[any, any], any>({ export const onFirstPause = (gensync<[any, any], any>({
name: "onFirstPause", name: "onFirstPause",
arity: 2, arity: 2,
sync: function(item) { sync: function (item) {
return runGenerator.sync(item); return runGenerator.sync(item);
}, },
errback: function(item, firstPause, cb) { errback: function (item, firstPause, cb) {
let completed = false; let completed = false;
runGenerator.errback(item, (err, value) => { runGenerator.errback(item, (err, value) => {

View File

@ -132,7 +132,7 @@ function buildHelpers(body, namespace, whitelist) {
}; };
const refs = {}; const refs = {};
helpers.list.forEach(function(name) { helpers.list.forEach(function (name) {
if (whitelist && whitelist.indexOf(name) < 0) return; if (whitelist && whitelist.indexOf(name) < 0) return;
const ref = (refs[name] = getHelperReference(name)); const ref = (refs[name] = getHelperReference(name));
@ -144,7 +144,7 @@ function buildHelpers(body, namespace, whitelist) {
}); });
return refs; return refs;
} }
export default function( export default function (
whitelist?: Array<string>, whitelist?: Array<string>,
outputType: "global" | "module" | "umd" | "var" = "global", outputType: "global" | "module" | "umd" | "var" = "global",
) { ) {

View File

@ -28,7 +28,7 @@ type TransformFromAst = {
const transformFromAstRunner = gensync< const transformFromAstRunner = gensync<
[AstRoot, string, ?InputOptions], [AstRoot, string, ?InputOptions],
FileResult | null, FileResult | null,
>(function*(ast, code, opts) { >(function* (ast, code, opts) {
const config: ResolvedConfig | null = yield* loadConfig(opts); const config: ResolvedConfig | null = yield* loadConfig(opts);
if (config === null) return null; if (config === null) return null;

View File

@ -24,7 +24,7 @@ type TransformFile = {
}; };
const transformFileRunner = gensync<[string, ?InputOptions], FileResult | null>( const transformFileRunner = gensync<[string, ?InputOptions], FileResult | null>(
function*(filename, opts) { function* (filename, opts) {
const options = { ...opts, filename }; const options = { ...opts, filename };
const config: ResolvedConfig | null = yield* loadConfig(options); const config: ResolvedConfig | null = yield* loadConfig(options);

View File

@ -51,7 +51,7 @@ const blockHoistPlugin = {
} }
if (!hasChange) return; if (!hasChange) return;
node.body = sortBy(node.body, function(bodyNode) { node.body = sortBy(node.body, function (bodyNode) {
let priority = bodyNode?._blockHoist; let priority = bodyNode?._blockHoist;
if (priority == null) priority = 1; if (priority == null) priority = 1;
if (priority === true) priority = 2; if (priority === true) priority = 2;

View File

@ -57,12 +57,12 @@ function transformFromAst(ast, code, opts) {
}); });
} }
describe("parser and generator options", function() { describe("parser and generator options", function () {
const recast = { const recast = {
parse: function(code, opts) { parse: function (code, opts) {
return opts.parser.parse(code); return opts.parser.parse(code);
}, },
print: function(ast) { print: function (ast) {
return generator(ast); return generator(ast);
}, },
}; };
@ -81,7 +81,7 @@ describe("parser and generator options", function() {
}); });
} }
it("options", function() { it("options", function () {
const string = "original;"; const string = "original;";
expect(newTransform(string).ast).toEqual( expect(newTransform(string).ast).toEqual(
transform(string, { ast: true }).ast, transform(string, { ast: true }).ast,
@ -89,7 +89,7 @@ describe("parser and generator options", function() {
expect(newTransform(string).code).toBe(string); expect(newTransform(string).code).toBe(string);
}); });
it("experimental syntax", function() { it("experimental syntax", function () {
const experimental = "var a: number = 1;"; const experimental = "var a: number = 1;";
expect(newTransform(experimental).ast).toEqual( expect(newTransform(experimental).ast).toEqual(
@ -126,7 +126,7 @@ describe("parser and generator options", function() {
expect(newTransformWithPlugins(experimental).code).toBe(experimental); expect(newTransformWithPlugins(experimental).code).toBe(experimental);
}); });
it("other options", function() { it("other options", function () {
const experimental = "if (true) {\n import a from 'a';\n}"; const experimental = "if (true) {\n import a from 'a';\n}";
expect(newTransform(experimental).ast).not.toBe( expect(newTransform(experimental).ast).not.toBe(
@ -141,33 +141,33 @@ describe("parser and generator options", function() {
}); });
}); });
describe("api", function() { describe("api", function () {
it("exposes the resolvePlugin method", function() { it("exposes the resolvePlugin method", function () {
expect(() => babel.resolvePlugin("nonexistent-plugin")).toThrow( expect(() => babel.resolvePlugin("nonexistent-plugin")).toThrow(
/Cannot find module 'babel-plugin-nonexistent-plugin'/, /Cannot find module 'babel-plugin-nonexistent-plugin'/,
); );
}); });
it("exposes the resolvePreset method", function() { it("exposes the resolvePreset method", function () {
expect(() => babel.resolvePreset("nonexistent-preset")).toThrow( expect(() => babel.resolvePreset("nonexistent-preset")).toThrow(
/Cannot find module 'babel-preset-nonexistent-preset'/, /Cannot find module 'babel-preset-nonexistent-preset'/,
); );
}); });
it("exposes types", function() { it("exposes types", function () {
expect(babel.types).toBeDefined(); expect(babel.types).toBeDefined();
}); });
it("exposes the parser's token types", function() { it("exposes the parser's token types", function () {
expect(babel.tokTypes).toBeDefined(); expect(babel.tokTypes).toBeDefined();
}); });
it("transformFile", function(done) { it("transformFile", function (done) {
const options = { const options = {
babelrc: false, babelrc: false,
}; };
Object.freeze(options); Object.freeze(options);
transformFile(__dirname + "/fixtures/api/file.js", options, function( transformFile(__dirname + "/fixtures/api/file.js", options, function (
err, err,
res, res,
) { ) {
@ -179,7 +179,7 @@ describe("api", function() {
}); });
}); });
it("transformFileSync", function() { it("transformFileSync", function () {
const options = { const options = {
babelrc: false, babelrc: false,
}; };
@ -190,15 +190,15 @@ describe("api", function() {
expect(options).toEqual({ babelrc: false }); expect(options).toEqual({ babelrc: false });
}); });
it("transformFromAst should not mutate the AST", function() { it("transformFromAst should not mutate the AST", function () {
const program = "const identifier = 1"; const program = "const identifier = 1";
const node = parse(program); const node = parse(program);
const { code } = transformFromAst(node, program, { const { code } = transformFromAst(node, program, {
plugins: [ plugins: [
function() { function () {
return { return {
visitor: { visitor: {
Identifier: function(path) { Identifier: function (path) {
path.node.name = "replaced"; path.node.name = "replaced";
}, },
}, },
@ -214,38 +214,38 @@ describe("api", function() {
); );
}); });
it("options throw on falsy true", function() { it("options throw on falsy true", function () {
return expect(function() { return expect(function () {
transform("", { transform("", {
plugins: [__dirname + "/../../babel-plugin-syntax-jsx", false], plugins: [__dirname + "/../../babel-plugin-syntax-jsx", false],
}); });
}).toThrow(/.plugins\[1\] must be a string, object, function/); }).toThrow(/.plugins\[1\] must be a string, object, function/);
}); });
it("options merge backwards", function() { it("options merge backwards", function () {
return transformAsync("", { return transformAsync("", {
presets: [__dirname + "/../../babel-preset-env"], presets: [__dirname + "/../../babel-preset-env"],
plugins: [__dirname + "/../../babel-plugin-syntax-jsx"], plugins: [__dirname + "/../../babel-plugin-syntax-jsx"],
}).then(function(result) { }).then(function (result) {
expect(result.options.plugins[0].manipulateOptions.toString()).toEqual( expect(result.options.plugins[0].manipulateOptions.toString()).toEqual(
expect.stringContaining("jsx"), expect.stringContaining("jsx"),
); );
}); });
}); });
it("option wrapPluginVisitorMethod", function() { it("option wrapPluginVisitorMethod", function () {
let calledRaw = 0; let calledRaw = 0;
let calledIntercept = 0; let calledIntercept = 0;
transform("function foo() { bar(foobar); }", { transform("function foo() { bar(foobar); }", {
wrapPluginVisitorMethod: function(pluginAlias, visitorType, callback) { wrapPluginVisitorMethod: function (pluginAlias, visitorType, callback) {
if (pluginAlias !== "foobar") { if (pluginAlias !== "foobar") {
return callback; return callback;
} }
expect(visitorType).toBe("enter"); expect(visitorType).toBe("enter");
return function() { return function () {
calledIntercept++; calledIntercept++;
return callback.apply(this, arguments); return callback.apply(this, arguments);
}; };
@ -255,7 +255,7 @@ describe("api", function() {
new Plugin({ new Plugin({
name: "foobar", name: "foobar",
visitor: { visitor: {
"Program|Identifier": function() { "Program|Identifier": function () {
calledRaw++; calledRaw++;
}, },
}, },
@ -267,7 +267,7 @@ describe("api", function() {
expect(calledIntercept).toBe(4); expect(calledIntercept).toBe(4);
}); });
it("pass per preset", function() { it("pass per preset", function () {
let aliasBaseType = null; let aliasBaseType = null;
function execTest(passPerPreset) { function execTest(passPerPreset) {
@ -276,12 +276,12 @@ describe("api", function() {
passPerPreset: passPerPreset, passPerPreset: passPerPreset,
presets: [ presets: [
// First preset with our plugin, "before" // First preset with our plugin, "before"
function() { function () {
return { return {
plugins: [ plugins: [
new Plugin({ new Plugin({
visitor: { visitor: {
Function: function(path) { Function: function (path) {
const alias = path.scope const alias = path.scope
.getProgramParent() .getProgramParent()
.path.get("body")[0].node; .path.get("body")[0].node;
@ -307,7 +307,7 @@ describe("api", function() {
require(__dirname + "/../../babel-preset-env"), require(__dirname + "/../../babel-preset-env"),
// Third preset for Flow. // Third preset for Flow.
function() { function () {
return { return {
plugins: [ plugins: [
require(__dirname + "/../../babel-plugin-syntax-flow"), require(__dirname + "/../../babel-plugin-syntax-flow"),
@ -339,7 +339,7 @@ describe("api", function() {
expect(result.code).toBe("var x = function x(y) {\n return y;\n};"); expect(result.code).toBe("var x = function x(y) {\n return y;\n};");
}); });
it("complex plugin and preset ordering", function() { it("complex plugin and preset ordering", function () {
function pushPlugin(str) { function pushPlugin(str) {
return { return {
visitor: { visitor: {
@ -414,7 +414,7 @@ describe("api", function() {
); );
}); });
it("interpreter directive backward-compat", function() { it("interpreter directive backward-compat", function () {
function doTransform(code, preHandler) { function doTransform(code, preHandler) {
return transform(code, { return transform(code, {
plugins: [ plugins: [
@ -468,7 +468,7 @@ describe("api", function() {
).toBe(`#!env node3`); ).toBe(`#!env node3`);
}); });
it("source map merging", function() { it("source map merging", function () {
const result = transform( const result = transform(
[ [
/* eslint-disable max-len */ /* eslint-disable max-len */
@ -515,52 +515,54 @@ describe("api", function() {
}); });
}); });
it("default source map filename", function() { it("default source map filename", function () {
return transformAsync("var a = 10;", { return transformAsync("var a = 10;", {
cwd: "/some/absolute", cwd: "/some/absolute",
filename: "/some/absolute/file/path.js", filename: "/some/absolute/file/path.js",
sourceMaps: true, sourceMaps: true,
}).then(function(result) { }).then(function (result) {
expect(result.map.sources).toEqual(["path.js"]); expect(result.map.sources).toEqual(["path.js"]);
}); });
}); });
it("code option false", function() { it("code option false", function () {
return transformAsync("foo('bar');", { code: false }).then(function( return transformAsync("foo('bar');", { code: false }).then(function (
result, result,
) { ) {
expect(result.code).toBeFalsy(); expect(result.code).toBeFalsy();
}); });
}); });
it("ast option false", function() { it("ast option false", function () {
return transformAsync("foo('bar');", { ast: false }).then(function(result) { return transformAsync("foo('bar');", { ast: false }).then(function (
result,
) {
expect(result.ast).toBeFalsy(); expect(result.ast).toBeFalsy();
}); });
}); });
it("ast option true", function() { it("ast option true", function () {
return transformAsync("foo('bar');", { ast: true }).then(function(result) { return transformAsync("foo('bar');", { ast: true }).then(function (result) {
expect(result.ast).toBeTruthy(); expect(result.ast).toBeTruthy();
}); });
}); });
it("ast option default", function() { it("ast option default", function () {
return transformAsync("foo('bar');").then(function(result) { return transformAsync("foo('bar');").then(function (result) {
expect(result.ast).toBeFalsy(); expect(result.ast).toBeFalsy();
}); });
}); });
it("auxiliaryComment option", function() { it("auxiliaryComment option", function () {
return transformAsync("class Foo {}", { return transformAsync("class Foo {}", {
auxiliaryCommentBefore: "before", auxiliaryCommentBefore: "before",
auxiliaryCommentAfter: "after", auxiliaryCommentAfter: "after",
plugins: [ plugins: [
function(babel) { function (babel) {
const t = babel.types; const t = babel.types;
return { return {
visitor: { visitor: {
Program: function(path) { Program: function (path) {
path.unshiftContainer( path.unshiftContainer(
"body", "body",
t.expressionStatement(t.identifier("start")), t.expressionStatement(t.identifier("start")),
@ -574,14 +576,14 @@ describe("api", function() {
}; };
}, },
], ],
}).then(function(result) { }).then(function (result) {
expect(result.code).toBe( expect(result.code).toBe(
"/*before*/\nstart;\n\n/*after*/\nclass Foo {}\n\n/*before*/\nend;\n\n/*after*/", "/*before*/\nstart;\n\n/*after*/\nclass Foo {}\n\n/*before*/\nend;\n\n/*after*/",
); );
}); });
}); });
it("ignore option", function() { it("ignore option", function () {
return Promise.all([ return Promise.all([
transformAsync("", { transformAsync("", {
ignore: ["/foo"], ignore: ["/foo"],
@ -620,7 +622,7 @@ describe("api", function() {
]); ]);
}); });
it("only option", function() { it("only option", function () {
return Promise.all([ return Promise.all([
transformAsync("", { transformAsync("", {
only: ["/foo"], only: ["/foo"],
@ -659,23 +661,23 @@ describe("api", function() {
]); ]);
}); });
describe("env option", function() { describe("env option", function () {
const oldBabelEnv = process.env.BABEL_ENV; const oldBabelEnv = process.env.BABEL_ENV;
const oldNodeEnv = process.env.NODE_ENV; const oldNodeEnv = process.env.NODE_ENV;
beforeEach(function() { beforeEach(function () {
// Tests need to run with the default and specific values for these. They // Tests need to run with the default and specific values for these. They
// need to be cleared for each test. // need to be cleared for each test.
delete process.env.BABEL_ENV; delete process.env.BABEL_ENV;
delete process.env.NODE_ENV; delete process.env.NODE_ENV;
}); });
afterAll(function() { afterAll(function () {
process.env.BABEL_ENV = oldBabelEnv; process.env.BABEL_ENV = oldBabelEnv;
process.env.NODE_ENV = oldNodeEnv; process.env.NODE_ENV = oldNodeEnv;
}); });
it("default", function() { it("default", function () {
const result = transform("foo;", { const result = transform("foo;", {
env: { env: {
development: { comments: false }, development: { comments: false },
@ -685,7 +687,7 @@ describe("api", function() {
expect(result.options.comments).toBe(false); expect(result.options.comments).toBe(false);
}); });
it("BABEL_ENV", function() { it("BABEL_ENV", function () {
process.env.BABEL_ENV = "foo"; process.env.BABEL_ENV = "foo";
const result = transform("foo;", { const result = transform("foo;", {
env: { env: {
@ -695,7 +697,7 @@ describe("api", function() {
expect(result.options.comments).toBe(false); expect(result.options.comments).toBe(false);
}); });
it("NODE_ENV", function() { it("NODE_ENV", function () {
process.env.NODE_ENV = "foo"; process.env.NODE_ENV = "foo";
const result = transform("foo;", { const result = transform("foo;", {
env: { env: {
@ -706,59 +708,59 @@ describe("api", function() {
}); });
}); });
describe("buildExternalHelpers", function() { describe("buildExternalHelpers", function () {
describe("smoke tests", function() { describe("smoke tests", function () {
it("builds external helpers in global output type", function() { it("builds external helpers in global output type", function () {
babel.buildExternalHelpers(null, "global"); babel.buildExternalHelpers(null, "global");
}); });
it("builds external helpers in module output type", function() { it("builds external helpers in module output type", function () {
babel.buildExternalHelpers(null, "module"); babel.buildExternalHelpers(null, "module");
}); });
it("builds external helpers in umd output type", function() { it("builds external helpers in umd output type", function () {
babel.buildExternalHelpers(null, "umd"); babel.buildExternalHelpers(null, "umd");
}); });
it("builds external helpers in var output type", function() { it("builds external helpers in var output type", function () {
babel.buildExternalHelpers(null, "var"); babel.buildExternalHelpers(null, "var");
}); });
}); });
it("all", function() { it("all", function () {
const script = babel.buildExternalHelpers(); const script = babel.buildExternalHelpers();
expect(script).toEqual(expect.stringContaining("classCallCheck")); expect(script).toEqual(expect.stringContaining("classCallCheck"));
expect(script).toEqual(expect.stringContaining("inherits")); expect(script).toEqual(expect.stringContaining("inherits"));
}); });
it("whitelist", function() { it("whitelist", function () {
const script = babel.buildExternalHelpers(["inherits"]); const script = babel.buildExternalHelpers(["inherits"]);
expect(script).not.toEqual(expect.stringContaining("classCallCheck")); expect(script).not.toEqual(expect.stringContaining("classCallCheck"));
expect(script).toEqual(expect.stringContaining("inherits")); expect(script).toEqual(expect.stringContaining("inherits"));
}); });
it("empty whitelist", function() { it("empty whitelist", function () {
const script = babel.buildExternalHelpers([]); const script = babel.buildExternalHelpers([]);
expect(script).not.toEqual(expect.stringContaining("classCallCheck")); expect(script).not.toEqual(expect.stringContaining("classCallCheck"));
expect(script).not.toEqual(expect.stringContaining("inherits")); expect(script).not.toEqual(expect.stringContaining("inherits"));
}); });
it("underscored", function() { it("underscored", function () {
const script = babel.buildExternalHelpers(["typeof"]); const script = babel.buildExternalHelpers(["typeof"]);
expect(script).toEqual(expect.stringContaining("typeof")); expect(script).toEqual(expect.stringContaining("typeof"));
}); });
}); });
describe("handle parsing errors", function() { describe("handle parsing errors", function () {
const options = { const options = {
babelrc: false, babelrc: false,
}; };
it("only syntax plugin available", function(done) { it("only syntax plugin available", function (done) {
transformFile( transformFile(
__dirname + "/fixtures/api/parsing-errors/only-syntax/file.js", __dirname + "/fixtures/api/parsing-errors/only-syntax/file.js",
options, options,
function(err) { function (err) {
expect(err.message).toMatch( expect(err.message).toMatch(
"Support for the experimental syntax 'pipelineOperator' isn't currently enabled (1:3):", "Support for the experimental syntax 'pipelineOperator' isn't currently enabled (1:3):",
); );
@ -771,11 +773,11 @@ describe("api", function() {
); );
}); });
it("both syntax and transform plugin available", function(done) { it("both syntax and transform plugin available", function (done) {
transformFile( transformFile(
__dirname + "/fixtures/api/parsing-errors/syntax-and-transform/file.js", __dirname + "/fixtures/api/parsing-errors/syntax-and-transform/file.js",
options, options,
function(err) { function (err) {
expect(err.message).toMatch( expect(err.message).toMatch(
"Support for the experimental syntax 'logicalAssignment' isn't currently enabled (1:3):", "Support for the experimental syntax 'logicalAssignment' isn't currently enabled (1:3):",
); );
@ -789,13 +791,13 @@ describe("api", function() {
}); });
}); });
describe("missing helpers", function() { describe("missing helpers", function () {
it("should always throw", function() { it("should always throw", function () {
expect(() => expect(() =>
babel.transformSync(``, { babel.transformSync(``, {
configFile: false, configFile: false,
plugins: [ plugins: [
function() { function () {
return { return {
visitor: { visitor: {
Program(path) { Program(path) {

View File

@ -11,12 +11,12 @@ describe("asynchronicity", () => {
const base = path.join(__dirname, "fixtures", "async"); const base = path.join(__dirname, "fixtures", "async");
let cwd; let cwd;
beforeEach(function() { beforeEach(function () {
cwd = process.cwd(); cwd = process.cwd();
process.chdir(base); process.chdir(base);
}); });
afterEach(function() { afterEach(function () {
process.chdir(cwd); process.chdir(cwd);
}); });

View File

@ -421,7 +421,7 @@ describe("caching API", () => {
it("should throw if the cache is configured asynchronously", async () => { it("should throw if the cache is configured asynchronously", async () => {
const fn = gensync( const fn = gensync(
makeStrongCache(function*(arg, cache) { makeStrongCache(function* (arg, cache) {
yield* wait(1000); yield* wait(1000);
cache.never(); cache.never();
return { arg }; return { arg };
@ -435,7 +435,7 @@ describe("caching API", () => {
it("should allow asynchronous cache invalidation functions", async () => { it("should allow asynchronous cache invalidation functions", async () => {
const fn = gensync( const fn = gensync(
makeStrongCache(function*(arg, cache) { makeStrongCache(function* (arg, cache) {
yield* waitFor( yield* waitFor(
cache.using(async () => { cache.using(async () => {
await wait.async(50); await wait.async(50);
@ -453,7 +453,7 @@ describe("caching API", () => {
it("should allow synchronous yield before cache configuration", async () => { it("should allow synchronous yield before cache configuration", async () => {
const fn = gensync( const fn = gensync(
makeStrongCache(function*(arg, cache) { makeStrongCache(function* (arg, cache) {
yield* gensync({ yield* gensync({
sync: () => 2, sync: () => 2,
errback: cb => cb(null, 2), errback: cb => cb(null, 2),

View File

@ -16,12 +16,12 @@ const pfs =
return function copyFile(source, target) { return function copyFile(source, target) {
const rd = fs.createReadStream(source); const rd = fs.createReadStream(source);
const wr = fs.createWriteStream(target); const wr = fs.createWriteStream(target);
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
rd.on("error", reject); rd.on("error", reject);
wr.on("error", reject); wr.on("error", reject);
wr.on("finish", resolve); wr.on("finish", resolve);
rd.pipe(wr); rd.pipe(wr);
}).catch(function(error) { }).catch(function (error) {
rd.destroy(); rd.destroy();
wr.end(); wr.end();
throw error; throw error;
@ -69,7 +69,7 @@ async function getTemp(name) {
return { cwd, tmp, config }; return { cwd, tmp, config };
} }
describe("buildConfigChain", function() { describe("buildConfigChain", function () {
describe("test", () => { describe("test", () => {
describe("single", () => { describe("single", () => {
it("should process matching string values", () => { it("should process matching string values", () => {
@ -702,8 +702,8 @@ describe("buildConfigChain", function() {
}); });
}); });
describe("caching", function() { describe("caching", function () {
describe("programmatic options", function() { describe("programmatic options", function () {
const plugins1 = [() => ({})]; const plugins1 = [() => ({})];
const plugins2 = [() => ({})]; const plugins2 = [() => ({})];
@ -807,7 +807,7 @@ describe("buildConfigChain", function() {
}); });
}); });
describe("config file options", function() { describe("config file options", function () {
function touch(filepath) { function touch(filepath) {
const s = fs.statSync(filepath); const s = fs.statSync(filepath);
fs.utimesSync( fs.utimesSync(

View File

@ -40,7 +40,7 @@ describe("@babel/core config loading", () => {
describe("loadPartialConfig", () => { describe("loadPartialConfig", () => {
it("should preserve disabled plugins in the partial config", () => { it("should preserve disabled plugins in the partial config", () => {
const plugin = function() { const plugin = function () {
return {}; return {};
}; };
@ -59,7 +59,7 @@ describe("@babel/core config loading", () => {
}); });
it("should preserve disabled presets in the partial config", () => { it("should preserve disabled presets in the partial config", () => {
const preset = function() { const preset = function () {
return {}; return {};
}; };

View File

@ -1,12 +1,12 @@
import traverse from "@babel/traverse"; import traverse from "@babel/traverse";
import { parse } from "@babel/parser"; import { parse } from "@babel/parser";
describe("evaluation", function() { describe("evaluation", function () {
function addTest(code, type, value, notConfident) { function addTest(code, type, value, notConfident) {
it(type + ": " + code, function() { it(type + ": " + code, function () {
const visitor = {}; const visitor = {};
visitor[type] = function(path) { visitor[type] = function (path) {
const evaluate = path.evaluate(); const evaluate = path.evaluate();
expect(evaluate.confident).toEqual(!notConfident); expect(evaluate.confident).toEqual(!notConfident);
expect(evaluate.value).toEqual(value); expect(evaluate.value).toEqual(value);

View File

@ -234,9 +234,9 @@ describe("option-manager", () => {
}); });
}); });
describe("presets", function() { describe("presets", function () {
function presetTest(name) { function presetTest(name) {
it(name, function() { it(name, function () {
const options = loadOptions({ const options = loadOptions({
presets: [ presets: [
path.join(__dirname, "fixtures/option-manager/presets", name), path.join(__dirname, "fixtures/option-manager/presets", name),
@ -250,7 +250,7 @@ describe("option-manager", () => {
} }
function presetThrowsTest(name, msg) { function presetThrowsTest(name, msg) {
it(name, function() { it(name, function () {
expect(() => expect(() =>
loadOptions({ loadOptions({
presets: [ presets: [

View File

@ -6,8 +6,8 @@ function fixture(...args) {
return path.join(__dirname, "fixtures", "parse", ...args); return path.join(__dirname, "fixtures", "parse", ...args);
} }
describe("parse", function() { describe("parse", function () {
it("should parse using configuration from .babelrc when a filename is provided", function() { it("should parse using configuration from .babelrc when a filename is provided", function () {
const input = fs.readFileSync(fixture("input.js"), "utf8"); const input = fs.readFileSync(fixture("input.js"), "utf8");
const output = require(fixture("output")); const output = require(fixture("output"));
@ -18,7 +18,7 @@ describe("parse", function() {
expect(JSON.parse(JSON.stringify(result))).toEqual(output); expect(JSON.parse(JSON.stringify(result))).toEqual(output);
}); });
it("should parse using passed in configuration", function() { it("should parse using passed in configuration", function () {
const input = fs.readFileSync(fixture("input.js"), "utf8"); const input = fs.readFileSync(fixture("input.js"), "utf8");
const output = require(fixture("output.json")); const output = require(fixture("output.json"));

View File

@ -1,8 +1,8 @@
import { transform } from "../lib/index"; import { transform } from "../lib/index";
import Plugin from "../lib/config/plugin"; import Plugin from "../lib/config/plugin";
describe("traversal path", function() { describe("traversal path", function () {
it("replaceWithSourceString", function() { it("replaceWithSourceString", function () {
const expectCode = "function foo() {}"; const expectCode = "function foo() {}";
const actualCode = transform(expectCode, { const actualCode = transform(expectCode, {
@ -10,7 +10,7 @@ describe("traversal path", function() {
plugins: [ plugins: [
new Plugin({ new Plugin({
visitor: { visitor: {
FunctionDeclaration: function(path) { FunctionDeclaration: function (path) {
path.replaceWithSourceString("console.whatever()"); path.replaceWithSourceString("console.whatever()");
}, },
}, },
@ -21,7 +21,7 @@ describe("traversal path", function() {
expect(actualCode).toBe("console.whatever();"); expect(actualCode).toBe("console.whatever();");
}); });
it("replaceWith (arrow expression body to block statement body)", function() { it("replaceWith (arrow expression body to block statement body)", function () {
const expectCode = "var fn = () => true;"; const expectCode = "var fn = () => true;";
const actualCode = transform(expectCode, { const actualCode = transform(expectCode, {
@ -29,7 +29,7 @@ describe("traversal path", function() {
plugins: [ plugins: [
new Plugin({ new Plugin({
visitor: { visitor: {
ArrowFunctionExpression: function(path) { ArrowFunctionExpression: function (path) {
path.get("body").replaceWith({ path.get("body").replaceWith({
type: "BlockStatement", type: "BlockStatement",
body: [ body: [
@ -51,7 +51,7 @@ describe("traversal path", function() {
expect(actualCode).toBe("var fn = () => {\n return true;\n};"); expect(actualCode).toBe("var fn = () => {\n return true;\n};");
}); });
it("replaceWith (arrow block statement body to expression body)", function() { it("replaceWith (arrow block statement body to expression body)", function () {
const expectCode = "var fn = () => { return true; }"; const expectCode = "var fn = () => { return true; }";
const actualCode = transform(expectCode, { const actualCode = transform(expectCode, {
@ -59,7 +59,7 @@ describe("traversal path", function() {
plugins: [ plugins: [
new Plugin({ new Plugin({
visitor: { visitor: {
ArrowFunctionExpression: function(path) { ArrowFunctionExpression: function (path) {
path.get("body").replaceWith({ path.get("body").replaceWith({
type: "BooleanLiteral", type: "BooleanLiteral",
value: true, value: true,
@ -73,7 +73,7 @@ describe("traversal path", function() {
expect(actualCode).toBe("var fn = () => true;"); expect(actualCode).toBe("var fn = () => true;");
}); });
it("replaceWith (for-in left expression to variable declaration)", function() { it("replaceWith (for-in left expression to variable declaration)", function () {
const expectCode = "for (KEY in right);"; const expectCode = "for (KEY in right);";
const actualCode = transform(expectCode, { const actualCode = transform(expectCode, {
@ -81,7 +81,7 @@ describe("traversal path", function() {
plugins: [ plugins: [
new Plugin({ new Plugin({
visitor: { visitor: {
ForInStatement: function(path) { ForInStatement: function (path) {
path.get("left").replaceWith({ path.get("left").replaceWith({
type: "VariableDeclaration", type: "VariableDeclaration",
kind: "var", kind: "var",
@ -104,7 +104,7 @@ describe("traversal path", function() {
expect(actualCode).toBe("for (var KEY in right);"); expect(actualCode).toBe("for (var KEY in right);");
}); });
it("replaceWith (for-in left variable declaration to expression)", function() { it("replaceWith (for-in left variable declaration to expression)", function () {
const expectCode = "for (var KEY in right);"; const expectCode = "for (var KEY in right);";
const actualCode = transform(expectCode, { const actualCode = transform(expectCode, {
@ -112,7 +112,7 @@ describe("traversal path", function() {
plugins: [ plugins: [
new Plugin({ new Plugin({
visitor: { visitor: {
ForInStatement: function(path) { ForInStatement: function (path) {
path.get("left").replaceWith({ path.get("left").replaceWith({
type: "Identifier", type: "Identifier",
name: "KEY", name: "KEY",
@ -126,7 +126,7 @@ describe("traversal path", function() {
expect(actualCode).toBe("for (KEY in right);"); expect(actualCode).toBe("for (KEY in right);");
}); });
it("replaceWith (for-loop left expression to variable declaration)", function() { it("replaceWith (for-loop left expression to variable declaration)", function () {
const expectCode = "for (KEY;;);"; const expectCode = "for (KEY;;);";
const actualCode = transform(expectCode, { const actualCode = transform(expectCode, {
@ -134,7 +134,7 @@ describe("traversal path", function() {
plugins: [ plugins: [
new Plugin({ new Plugin({
visitor: { visitor: {
ForStatement: function(path) { ForStatement: function (path) {
path.get("init").replaceWith({ path.get("init").replaceWith({
type: "VariableDeclaration", type: "VariableDeclaration",
kind: "var", kind: "var",
@ -157,7 +157,7 @@ describe("traversal path", function() {
expect(actualCode).toBe("for (var KEY;;);"); expect(actualCode).toBe("for (var KEY;;);");
}); });
it("replaceWith (for-loop left variable declaration to expression)", function() { it("replaceWith (for-loop left variable declaration to expression)", function () {
const expectCode = "for (var KEY;;);"; const expectCode = "for (var KEY;;);";
const actualCode = transform(expectCode, { const actualCode = transform(expectCode, {
@ -165,7 +165,7 @@ describe("traversal path", function() {
plugins: [ plugins: [
new Plugin({ new Plugin({
visitor: { visitor: {
ForStatement: function(path) { ForStatement: function (path) {
path.get("init").replaceWith({ path.get("init").replaceWith({
type: "Identifier", type: "Identifier",
name: "KEY", name: "KEY",

View File

@ -1,20 +1,20 @@
import * as babel from "../lib/index"; import * as babel from "../lib/index";
import path from "path"; import path from "path";
describe("addon resolution", function() { describe("addon resolution", function () {
const base = path.join(__dirname, "fixtures", "resolution"); const base = path.join(__dirname, "fixtures", "resolution");
let cwd; let cwd;
beforeEach(function() { beforeEach(function () {
cwd = process.cwd(); cwd = process.cwd();
process.chdir(base); process.chdir(base);
}); });
afterEach(function() { afterEach(function () {
process.chdir(cwd); process.chdir(cwd);
}); });
it("should find module: presets", function() { it("should find module: presets", function () {
process.chdir("module-paths"); process.chdir("module-paths");
babel.transform("", { babel.transform("", {
@ -24,7 +24,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find module: plugins", function() { it("should find module: plugins", function () {
process.chdir("module-paths"); process.chdir("module-paths");
babel.transform("", { babel.transform("", {
@ -34,7 +34,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find standard presets", function() { it("should find standard presets", function () {
process.chdir("standard-paths"); process.chdir("standard-paths");
babel.transform("", { babel.transform("", {
@ -44,7 +44,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find standard plugins", function() { it("should find standard plugins", function () {
process.chdir("standard-paths"); process.chdir("standard-paths");
babel.transform("", { babel.transform("", {
@ -54,7 +54,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find standard presets with an existing prefix", function() { it("should find standard presets with an existing prefix", function () {
process.chdir("standard-paths"); process.chdir("standard-paths");
babel.transform("", { babel.transform("", {
@ -64,7 +64,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find standard plugins with an existing prefix", function() { it("should find standard plugins with an existing prefix", function () {
process.chdir("standard-paths"); process.chdir("standard-paths");
babel.transform("", { babel.transform("", {
@ -74,7 +74,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @babel scoped presets", function() { it("should find @babel scoped presets", function () {
process.chdir("babel-org-paths"); process.chdir("babel-org-paths");
babel.transform("", { babel.transform("", {
@ -84,7 +84,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @babel scoped plugins", function() { it("should find @babel scoped plugins", function () {
process.chdir("babel-org-paths"); process.chdir("babel-org-paths");
babel.transform("", { babel.transform("", {
@ -94,7 +94,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @babel scoped presets with an existing prefix", function() { it("should find @babel scoped presets with an existing prefix", function () {
process.chdir("babel-org-paths"); process.chdir("babel-org-paths");
babel.transform("", { babel.transform("", {
@ -104,7 +104,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @babel scoped plugins", function() { it("should find @babel scoped plugins", function () {
process.chdir("babel-org-paths"); process.chdir("babel-org-paths");
babel.transform("", { babel.transform("", {
@ -114,7 +114,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo scoped presets", function() { it("should find @foo scoped presets", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -124,7 +124,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo scoped plugins", function() { it("should find @foo scoped plugins", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -134,7 +134,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo scoped presets with an inner babel-preset", function() { it("should find @foo scoped presets with an inner babel-preset", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -144,7 +144,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo scoped plugins with an inner babel-plugin", function() { it("should find @foo scoped plugins with an inner babel-plugin", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -154,7 +154,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo scoped presets with an babel-preset suffix", function() { it("should find @foo scoped presets with an babel-preset suffix", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -164,7 +164,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo scoped plugins with an babel-plugin suffix", function() { it("should find @foo scoped plugins with an babel-plugin suffix", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -174,7 +174,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo scoped presets with an existing prefix", function() { it("should find @foo scoped presets with an existing prefix", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -184,7 +184,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo scoped plugins with an existing prefix", function() { it("should find @foo scoped plugins with an existing prefix", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -194,7 +194,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo/babel-plugin when specified", function() { it("should find @foo/babel-plugin when specified", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -204,7 +204,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo/babel-preset when specified", function() { it("should find @foo/babel-preset when specified", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -214,7 +214,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo/babel-plugin/index when specified", function() { it("should find @foo/babel-plugin/index when specified", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -224,7 +224,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo/babel-preset/index when specified", function() { it("should find @foo/babel-preset/index when specified", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -234,7 +234,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo/babel-plugin when just scope given", function() { it("should find @foo/babel-plugin when just scope given", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -244,7 +244,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo/babel-preset when just scope given", function() { it("should find @foo/babel-preset when just scope given", function () {
process.chdir("foo-org-paths"); process.chdir("foo-org-paths");
babel.transform("", { babel.transform("", {
@ -254,7 +254,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find relative path presets", function() { it("should find relative path presets", function () {
process.chdir("relative-paths"); process.chdir("relative-paths");
babel.transform("", { babel.transform("", {
@ -264,7 +264,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find relative path plugins", function() { it("should find relative path plugins", function () {
process.chdir("relative-paths"); process.chdir("relative-paths");
babel.transform("", { babel.transform("", {
@ -274,7 +274,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find module file presets", function() { it("should find module file presets", function () {
process.chdir("nested-module-paths"); process.chdir("nested-module-paths");
babel.transform("", { babel.transform("", {
@ -284,7 +284,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find module file plugins", function() { it("should find module file plugins", function () {
process.chdir("nested-module-paths"); process.chdir("nested-module-paths");
babel.transform("", { babel.transform("", {
@ -294,7 +294,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo scoped module file presets", function() { it("should find @foo scoped module file presets", function () {
process.chdir("scoped-nested-module-paths"); process.chdir("scoped-nested-module-paths");
babel.transform("", { babel.transform("", {
@ -304,7 +304,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @foo scoped module file plugins", function() { it("should find @foo scoped module file plugins", function () {
process.chdir("scoped-nested-module-paths"); process.chdir("scoped-nested-module-paths");
babel.transform("", { babel.transform("", {
@ -314,7 +314,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @babel scoped module file presets", function() { it("should find @babel scoped module file presets", function () {
process.chdir("babel-scoped-nested-module-paths"); process.chdir("babel-scoped-nested-module-paths");
babel.transform("", { babel.transform("", {
@ -324,7 +324,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should find @babel scoped module file plugins", function() { it("should find @babel scoped module file plugins", function () {
process.chdir("babel-scoped-nested-module-paths"); process.chdir("babel-scoped-nested-module-paths");
babel.transform("", { babel.transform("", {
@ -334,7 +334,7 @@ describe("addon resolution", function() {
}); });
}); });
it("should throw about module: usage for presets", function() { it("should throw about module: usage for presets", function () {
process.chdir("throw-module-paths"); process.chdir("throw-module-paths");
expect(() => { expect(() => {
@ -348,7 +348,7 @@ describe("addon resolution", function() {
); );
}); });
it("should throw about module: usage for plugins", function() { it("should throw about module: usage for plugins", function () {
process.chdir("throw-module-paths"); process.chdir("throw-module-paths");
expect(() => { expect(() => {
@ -362,7 +362,7 @@ describe("addon resolution", function() {
); );
}); });
it("should throw about @babel usage for presets", function() { it("should throw about @babel usage for presets", function () {
process.chdir("throw-babel-paths"); process.chdir("throw-babel-paths");
expect(() => { expect(() => {
@ -376,7 +376,7 @@ describe("addon resolution", function() {
); );
}); });
it("should throw about @babel usage for plugins", function() { it("should throw about @babel usage for plugins", function () {
process.chdir("throw-babel-paths"); process.chdir("throw-babel-paths");
expect(() => { expect(() => {
@ -390,7 +390,7 @@ describe("addon resolution", function() {
); );
}); });
it("should throw about passing a preset as a plugin", function() { it("should throw about passing a preset as a plugin", function () {
process.chdir("throw-opposite-paths"); process.chdir("throw-opposite-paths");
expect(() => { expect(() => {
@ -404,7 +404,7 @@ describe("addon resolution", function() {
); );
}); });
it("should throw about passing a plugin as a preset", function() { it("should throw about passing a plugin as a preset", function () {
process.chdir("throw-opposite-paths"); process.chdir("throw-opposite-paths");
expect(() => { expect(() => {
@ -418,7 +418,7 @@ describe("addon resolution", function() {
); );
}); });
it("should throw about missing presets", function() { it("should throw about missing presets", function () {
process.chdir("throw-missing-paths"); process.chdir("throw-missing-paths");
expect(() => { expect(() => {
@ -430,7 +430,7 @@ describe("addon resolution", function() {
}).toThrow(/Cannot find module 'babel-preset-foo'/); }).toThrow(/Cannot find module 'babel-preset-foo'/);
}); });
it("should throw about missing plugins", function() { it("should throw about missing plugins", function () {
process.chdir("throw-missing-paths"); process.chdir("throw-missing-paths");
expect(() => { expect(() => {

View File

@ -154,7 +154,7 @@ export function Import() {
} }
function buildYieldAwait(keyword: string) { function buildYieldAwait(keyword: string) {
return function(node: Object) { return function (node: Object) {
this.word(keyword); this.word(keyword);
if (node.delegate) { if (node.delegate) {

View File

@ -81,8 +81,8 @@ export function WhileStatement(node: Object) {
this.printBlock(node); this.printBlock(node);
} }
const buildForXStatement = function(op) { const buildForXStatement = function (op) {
return function(node: Object) { return function (node: Object) {
this.word("for"); this.word("for");
this.space(); this.space();
if (op === "of" && node.await) { if (op === "of" && node.await) {
@ -117,7 +117,7 @@ export function DoWhileStatement(node: Object) {
} }
function buildLabelStatement(prefix, key = "label") { function buildLabelStatement(prefix, key = "label") {
return function(node: Object) { return function (node: Object) {
this.word(prefix); this.word(prefix);
const label = node[key]; const label = node[key];

View File

@ -108,7 +108,7 @@ export class CodeGenerator {
} }
} }
export default function(ast: Object, opts: Object, code: string): Object { export default function (ast: Object, opts: Object, code: string): Object {
const gen = new Generator(ast, opts, code); const gen = new Generator(ast, opts, code);
return gen.generate(); return gen.generate();
} }

View File

@ -8,7 +8,7 @@ function expandAliases(obj) {
function add(type, func) { function add(type, func) {
const fn = newObj[type]; const fn = newObj[type];
newObj[type] = fn newObj[type] = fn
? function(node, parent, stack) { ? function (node, parent, stack) {
const result = fn(node, parent, stack); const result = fn(node, parent, stack);
return result == null ? func(node, parent, stack) : result; return result == null ? func(node, parent, stack) : result;

View File

@ -181,7 +181,7 @@ export const nodes = {
* Test if Property needs whitespace. * Test if Property needs whitespace.
*/ */
nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function( nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function (
node: Object, node: Object,
parent, parent,
): ?WhitespaceObject { ): ?WhitespaceObject {
@ -192,7 +192,7 @@ nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function(
} }
}; };
nodes.ObjectTypeCallProperty = function( nodes.ObjectTypeCallProperty = function (
node: Object, node: Object,
parent, parent,
): ?WhitespaceObject { ): ?WhitespaceObject {
@ -203,7 +203,7 @@ nodes.ObjectTypeCallProperty = function(
} }
}; };
nodes.ObjectTypeIndexer = function(node: Object, parent): ?WhitespaceObject { nodes.ObjectTypeIndexer = function (node: Object, parent): ?WhitespaceObject {
if ( if (
parent.indexers[0] === node && parent.indexers[0] === node &&
!parent.properties?.length && !parent.properties?.length &&
@ -215,7 +215,7 @@ nodes.ObjectTypeIndexer = function(node: Object, parent): ?WhitespaceObject {
} }
}; };
nodes.ObjectTypeInternalSlot = function( nodes.ObjectTypeInternalSlot = function (
node: Object, node: Object,
parent, parent,
): ?WhitespaceObject { ): ?WhitespaceObject {
@ -272,12 +272,12 @@ export const list = {
["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 };
} }
[type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function(type) { [type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) {
nodes[type] = function() { nodes[type] = function () {
return amounts; return amounts;
}; };
}); });

View File

@ -6,24 +6,24 @@ import fs from "fs";
import path from "path"; import path from "path";
import fixtures from "@babel/helper-fixtures"; import fixtures from "@babel/helper-fixtures";
describe("generation", function() { describe("generation", function () {
it("completeness", function() { it("completeness", function () {
Object.keys(t.VISITOR_KEYS).forEach(function(type) { Object.keys(t.VISITOR_KEYS).forEach(function (type) {
expect(Printer.prototype[type]).toBeTruthy(); expect(Printer.prototype[type]).toBeTruthy();
}); });
Object.keys(Printer.prototype).forEach(function(type) { Object.keys(Printer.prototype).forEach(function (type) {
if (!/[A-Z]/.test(type[0])) return; if (!/[A-Z]/.test(type[0])) return;
expect(t.VISITOR_KEYS[type]).toBeTruthy(); expect(t.VISITOR_KEYS[type]).toBeTruthy();
}); });
}); });
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], { _parsed[filename] = parse(sources[filename], {
sourceFilename: filename, sourceFilename: filename,
}); });
@ -185,7 +185,7 @@ describe("generation", function() {
); );
}); });
it("identifierName", function() { it("identifierName", function () {
const code = "function foo() { bar; }\n"; const code = "function foo() { bar; }\n";
const ast = parse(code, { filename: "inline" }).program; const ast = parse(code, { filename: "inline" }).program;
@ -277,7 +277,7 @@ describe("generation", function() {
expect(generated.code).toBe("function foo2() {\n bar2;\n}"); expect(generated.code).toBe("function foo2() {\n bar2;\n}");
}); });
it("lazy source map generation", function() { it("lazy source map generation", function () {
const code = "function hi (msg) { console.log(msg); }\n"; const code = "function hi (msg) { console.log(msg); }\n";
const ast = parse(code, { filename: "a.js" }).program; const ast = parse(code, { filename: "a.js" }).program;
@ -306,8 +306,8 @@ describe("generation", function() {
}); });
}); });
describe("programmatic generation", function() { describe("programmatic generation", function () {
it("should add parenthesis when NullishCoalescing is used along with ||", function() { it("should add parenthesis when NullishCoalescing is used along with ||", function () {
// https://github.com/babel/babel/issues/10260 // https://github.com/babel/babel/issues/10260
const nullishCoalesc = t.logicalExpression( const nullishCoalesc = t.logicalExpression(
"??", "??",
@ -318,7 +318,7 @@ describe("programmatic generation", function() {
expect(output).toBe(`(a || b) ?? c`); expect(output).toBe(`(a || b) ?? c`);
}); });
it("should add parenthesis when NullishCoalesing is used with &&", function() { it("should add parenthesis when NullishCoalesing is used with &&", function () {
const nullishCoalesc = t.logicalExpression( const nullishCoalesc = t.logicalExpression(
"??", "??",
t.identifier("a"), t.identifier("a"),
@ -332,7 +332,7 @@ describe("programmatic generation", function() {
expect(output).toBe(`a ?? (b && c && d)`); expect(output).toBe(`a ?? (b && c && d)`);
}); });
it("numeric member expression", function() { it("numeric member expression", function () {
// Should not generate `0.foo` // Should not generate `0.foo`
const mem = t.memberExpression( const mem = t.memberExpression(
t.numericLiteral(60702), t.numericLiteral(60702),
@ -341,7 +341,7 @@ describe("programmatic generation", function() {
new Function(generate(mem).code); new Function(generate(mem).code);
}); });
it("nested if statements needs block", function() { it("nested if statements needs block", function () {
const ifStatement = t.ifStatement( const ifStatement = t.ifStatement(
t.stringLiteral("top cond"), t.stringLiteral("top cond"),
t.whileStatement( t.whileStatement(
@ -358,7 +358,7 @@ describe("programmatic generation", function() {
expect(ast.program.body[0].consequent.type).toBe("BlockStatement"); expect(ast.program.body[0].consequent.type).toBe("BlockStatement");
}); });
it("prints directives in block with empty body", function() { it("prints directives in block with empty body", function () {
const blockStatement = t.blockStatement( const blockStatement = t.blockStatement(
[], [],
[t.directive(t.directiveLiteral("use strict"))], [t.directive(t.directiveLiteral("use strict"))],
@ -370,7 +370,7 @@ describe("programmatic generation", function() {
}`); }`);
}); });
it("flow object indentation", function() { it("flow object indentation", function () {
const objectStatement = t.objectTypeAnnotation( const objectStatement = t.objectTypeAnnotation(
[t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())], [t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())],
null, null,
@ -384,7 +384,7 @@ describe("programmatic generation", function() {
}`); }`);
}); });
it("flow object exact", function() { it("flow object exact", function () {
const objectStatement = t.objectTypeAnnotation( const objectStatement = t.objectTypeAnnotation(
[t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())], [t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())],
null, null,
@ -399,7 +399,7 @@ describe("programmatic generation", function() {
|}`); |}`);
}); });
it("flow object indentation with empty leading ObjectTypeProperty", function() { it("flow object indentation with empty leading ObjectTypeProperty", function () {
const objectStatement = t.objectTypeAnnotation( const objectStatement = t.objectTypeAnnotation(
[], [],
[ [
@ -419,8 +419,8 @@ describe("programmatic generation", function() {
}`); }`);
}); });
describe("directives", function() { describe("directives", function () {
it("preserves escapes", function() { it("preserves escapes", function () {
const directive = t.directive( const directive = t.directive(
t.directiveLiteral(String.raw`us\x65 strict`), t.directiveLiteral(String.raw`us\x65 strict`),
); );
@ -429,7 +429,7 @@ describe("programmatic generation", function() {
expect(output).toBe(String.raw`"us\x65 strict";`); expect(output).toBe(String.raw`"us\x65 strict";`);
}); });
it("preserves escapes in minified output", function() { it("preserves escapes in minified output", function () {
// https://github.com/babel/babel/issues/4767 // https://github.com/babel/babel/issues/4767
const directive = t.directive(t.directiveLiteral(String.raw`foo\n\t\r`)); const directive = t.directive(t.directiveLiteral(String.raw`foo\n\t\r`));
@ -438,21 +438,21 @@ describe("programmatic generation", function() {
expect(output).toBe(String.raw`"foo\n\t\r";`); expect(output).toBe(String.raw`"foo\n\t\r";`);
}); });
it("unescaped single quote", function() { it("unescaped single quote", function () {
const directive = t.directive(t.directiveLiteral(String.raw`'\'\"`)); const directive = t.directive(t.directiveLiteral(String.raw`'\'\"`));
const output = generate(directive).code; const output = generate(directive).code;
expect(output).toBe(String.raw`"'\'\"";`); expect(output).toBe(String.raw`"'\'\"";`);
}); });
it("unescaped double quote", function() { it("unescaped double quote", function () {
const directive = t.directive(t.directiveLiteral(String.raw`"\'\"`)); const directive = t.directive(t.directiveLiteral(String.raw`"\'\"`));
const output = generate(directive).code; const output = generate(directive).code;
expect(output).toBe(String.raw`'"\'\"';`); expect(output).toBe(String.raw`'"\'\"';`);
}); });
it("unescaped single and double quotes together throw", function() { it("unescaped single and double quotes together throw", function () {
const directive = t.directive(t.directiveLiteral(String.raw`'"`)); const directive = t.directive(t.directiveLiteral(String.raw`'"`));
expect(() => { expect(() => {
@ -461,7 +461,7 @@ describe("programmatic generation", function() {
}); });
}); });
describe("typescript generate parentheses if necessary", function() { describe("typescript generate parentheses if necessary", function () {
it("wraps around union for array", () => { it("wraps around union for array", () => {
const typeStatement = t.TSArrayType( const typeStatement = t.TSArrayType(
t.TSUnionType([ t.TSUnionType([
@ -496,8 +496,8 @@ describe("programmatic generation", function() {
}); });
}); });
describe("CodeGenerator", function() { describe("CodeGenerator", function () {
it("generate", function() { it("generate", function () {
const codeGen = new CodeGenerator(t.numericLiteral(123)); const codeGen = new CodeGenerator(t.numericLiteral(123));
const code = codeGen.generate().code; const code = codeGen.generate().code;
expect(parse(code).program.body[0].expression.value).toBe(123); expect(parse(code).program.body[0].expression.value).toBe(123);
@ -506,15 +506,15 @@ describe("CodeGenerator", function() {
const suites = fixtures(`${__dirname}/fixtures`); const suites = fixtures(`${__dirname}/fixtures`);
suites.forEach(function(testSuite) { suites.forEach(function (testSuite) {
describe("generation/" + testSuite.title, function() { describe("generation/" + testSuite.title, function () {
testSuite.tests.forEach(function(task) { testSuite.tests.forEach(function (task) {
const testFn = task.disabled ? it.skip : it; const testFn = task.disabled ? it.skip : it;
testFn( testFn(
task.title, task.title,
function() { function () {
const expected = task.expect; const expected = task.expect;
const actual = task.actual; const actual = task.actual;
const actualCode = actual.code; const actualCode = actual.code;

View File

@ -1,7 +1,7 @@
import explode from "@babel/helper-explode-assignable-expression"; import explode from "@babel/helper-explode-assignable-expression";
import * as t from "@babel/types"; import * as t from "@babel/types";
export default function(opts: { build: Function, operator: string }): Object { export default function (opts: { build: Function, operator: string }): Object {
const { build, operator } = opts; const { build, operator } = opts;
return { return {

View File

@ -9,10 +9,10 @@ type ElementState = {
pure: boolean, // true if the element can be marked with a #__PURE__ annotation pure: boolean, // true if the element can be marked with a #__PURE__ annotation
}; };
export default function(opts) { export default function (opts) {
const visitor = {}; const visitor = {};
visitor.JSXNamespacedName = function(path) { visitor.JSXNamespacedName = function (path) {
if (opts.throwIfNamespace) { if (opts.throwIfNamespace) {
throw path.buildCodeFrameError( throw path.buildCodeFrameError(
`Namespace tags are not supported by default. React's JSX doesn't support namespace tags. \ `Namespace tags are not supported by default. React's JSX doesn't support namespace tags. \
@ -21,7 +21,7 @@ You can set \`throwIfNamespace: false\` to bypass this warning.`,
} }
}; };
visitor.JSXSpreadChild = function(path) { visitor.JSXSpreadChild = function (path) {
throw path.buildCodeFrameError( throw path.buildCodeFrameError(
"Spread children are not supported in React.", "Spread children are not supported in React.",
); );

View File

@ -18,7 +18,7 @@ const visitor = {
}, },
}; };
export default function( export default function (
path: NodePath, path: NodePath,
scope = path.scope, scope = path.scope,
shouldHoistVariables = true, shouldHoistVariables = true,

View File

@ -124,13 +124,13 @@ export function toComputedObjectFromClass(obj: Object): Object {
export function toClassObject(mutatorMap: Object): Object { export function toClassObject(mutatorMap: Object): Object {
const objExpr = t.objectExpression([]); const objExpr = t.objectExpression([]);
Object.keys(mutatorMap).forEach(function(mutatorMapKey) { Object.keys(mutatorMap).forEach(function (mutatorMapKey) {
const map = mutatorMap[mutatorMapKey]; const map = mutatorMap[mutatorMapKey];
const mapNode = t.objectExpression([]); const mapNode = t.objectExpression([]);
const propNode = t.objectProperty(map._key, mapNode, map._computed); const propNode = t.objectProperty(map._key, mapNode, map._computed);
Object.keys(map).forEach(function(key) { Object.keys(map).forEach(function (key) {
const node = map[key]; const node = map[key];
if (key[0] === "_") return; if (key[0] === "_") return;
@ -148,7 +148,7 @@ export function toClassObject(mutatorMap: Object): Object {
} }
export function toDefineObject(mutatorMap: Object): Object { export function toDefineObject(mutatorMap: Object): Object {
Object.keys(mutatorMap).forEach(function(key) { Object.keys(mutatorMap).forEach(function (key) {
const map = mutatorMap[key]; const map = mutatorMap[key];
if (map.value) map.writable = t.booleanLiteral(true); if (map.value) map.writable = t.booleanLiteral(true);
map.configurable = t.booleanLiteral(true); map.configurable = t.booleanLiteral(true);

View File

@ -48,7 +48,7 @@ function getPropRef(node, nodes, file, scope) {
return temp; return temp;
} }
export default function( export default function (
node: Object, node: Object,
nodes: Array<Object>, nodes: Array<Object>,
file, file,

View File

@ -2,7 +2,7 @@ import bindifyDecorators from "@babel/helper-bindify-decorators";
import type { NodePath } from "@babel/traverse"; import type { NodePath } from "@babel/traverse";
import * as t from "@babel/types"; import * as t from "@babel/types";
export default function(classPath) { export default function (classPath) {
classPath.assertClass(); classPath.assertClass();
const memoisedExpressions = []; const memoisedExpressions = [];

View File

@ -150,7 +150,7 @@ function visit(node, name, scope) {
* @param {NodePath} param0 * @param {NodePath} param0
* @param {Boolean} localBinding whether a name could shadow a self-reference (e.g. converting arrow function) * @param {Boolean} localBinding whether a name could shadow a self-reference (e.g. converting arrow function)
*/ */
export default function({ node, parent, scope, id }, localBinding = false) { export default function ({ node, parent, scope, id }, localBinding = false) {
// has an `id` so we don't need to infer one // has an `id` so we don't need to infer one
if (node.id) return; if (node.id) return;

View File

@ -1,6 +1,6 @@
import * as t from "@babel/types"; import * as t from "@babel/types";
export default function(node): number { export default function (node): number {
const params: Array<Object> = node.params; const params: Array<Object> = node.params;
for (let i = 0; i < params.length; i++) { for (let i = 0; i < params.length; i++) {
const param = params[i]; const param = params[i];

View File

@ -42,6 +42,6 @@ const visitor = {
}, },
}; };
export default function(path, emit: Function, kind: "var" | "let" = "var") { export default function (path, emit: Function, kind: "var" | "let" = "var") {
path.traverse(visitor, { kind, emit }); path.traverse(visitor, { kind, emit });
} }

View File

@ -294,10 +294,7 @@ export default class ImportInjector {
builder.var(importedSource).read(importName); builder.var(importedSource).read(importName);
} }
} else if (isDefault) { } else if (isDefault) {
builder builder.var(name).defaultInterop().prop(importName);
.var(name)
.defaultInterop()
.prop(importName);
} else if (isNamed) { } else if (isNamed) {
builder.var(name).prop(importName); builder.var(name).prop(importName);
} }

View File

@ -15,7 +15,7 @@ function test(sourceType, opts, initializer, expectedCode) {
filename: "example" + (sourceType === "module" ? ".mjs" : ".js"), filename: "example" + (sourceType === "module" ? ".mjs" : ".js"),
babelrc: false, babelrc: false,
plugins: [ plugins: [
function({ types: t }) { function ({ types: t }) {
return { return {
pre(file) { pre(file) {
file.set("helperGenerator", name => file.set("helperGenerator", name =>

View File

@ -1,6 +1,6 @@
import * as t from "@babel/types"; import * as t from "@babel/types";
export default function(callee, thisNode, args, optional) { export default function (callee, thisNode, args, optional) {
if ( if (
args.length === 1 && args.length === 1 &&
t.isSpreadElement(args[0]) && t.isSpreadElement(args[0]) &&

View File

@ -1,7 +1,7 @@
import testRunner from "@babel/helper-transform-fixture-test-runner"; import testRunner from "@babel/helper-transform-fixture-test-runner";
import path from "path"; import path from "path";
export default function(loc) { export default function (loc) {
const name = path.basename(path.dirname(loc)); const name = path.basename(path.dirname(loc));
testRunner(loc + "/fixtures", name); testRunner(loc + "/fixtures", name);
} }

View File

@ -28,7 +28,7 @@ const awaitVisitor = {
}, },
}; };
export default function( export default function (
path: NodePath, path: NodePath,
helpers: { wrapAsync: Object, wrapAwait: Object }, helpers: { wrapAsync: Object, wrapAwait: Object },
) { ) {

View File

@ -107,7 +107,7 @@ export function runCodeInTestContext(code: string, opts: { filename: string }) {
} }
function wrapPackagesArray(type, names, optionsDir) { function wrapPackagesArray(type, names, optionsDir) {
return (names || []).map(function(val) { return (names || []).map(function (val) {
if (typeof val === "string") val = [val]; if (typeof val === "string") val = [val];
// relative path (outside of monorepo) // relative path (outside of monorepo)
@ -164,7 +164,7 @@ function run(task) {
"preset", "preset",
newOpts.presets, newOpts.presets,
optionsDir, optionsDir,
).map(function(val) { ).map(function (val) {
if (val.length > 3) { if (val.length > 3) {
throw new Error( throw new Error(
"Unexpected extra options " + "Unexpected extra options " +
@ -269,7 +269,7 @@ function run(task) {
if (task.sourceMappings) { if (task.sourceMappings) {
const consumer = new sourceMap.SourceMapConsumer(result.map); const consumer = new sourceMap.SourceMapConsumer(result.map);
task.sourceMappings.forEach(function(mapping) { task.sourceMappings.forEach(function (mapping) {
const actual = mapping.original; const actual = mapping.original;
const expected = consumer.originalPositionFor(mapping.generated); const expected = consumer.originalPositionFor(mapping.generated);
@ -342,7 +342,7 @@ const toEqualFile = () => ({
}, },
}); });
export default function( export default function (
fixturesLoc: string, fixturesLoc: string,
name: string, name: string,
suiteOpts = {}, suiteOpts = {},
@ -354,7 +354,7 @@ export default function(
for (const testSuite of suites) { for (const testSuite of suites) {
if (includes(suiteOpts.ignoreSuites, testSuite.title)) continue; if (includes(suiteOpts.ignoreSuites, testSuite.title)) continue;
describe(name + "/" + testSuite.title, function() { describe(name + "/" + testSuite.title, function () {
jest.addMatchers({ jest.addMatchers({
toEqualFile, toEqualFile,
}); });
@ -372,7 +372,7 @@ export default function(
testFn( testFn(
task.title, task.title,
function() { function () {
function runTask() { function runTask() {
run(task); run(task);
} }
@ -391,7 +391,7 @@ export default function(
// the options object with useless options // the options object with useless options
delete task.options.throws; delete task.options.throws;
assert.throws(runTask, function(err) { assert.throws(runTask, function (err) {
return throwMsg === true || err.message.indexOf(throwMsg) >= 0; return throwMsg === true || err.message.indexOf(throwMsg) >= 0;
}); });
} else { } else {

View File

@ -1,7 +1,7 @@
import { runCodeInTestContext } from ".."; import { runCodeInTestContext } from "..";
describe("helper-transform-fixture-test-runner", function() { describe("helper-transform-fixture-test-runner", function () {
it("should not execute code in Node's global context", function() { it("should not execute code in Node's global context", function () {
try { try {
global.foo = "outer"; global.foo = "outer";
runCodeInTestContext( runCodeInTestContext(

View File

@ -6,14 +6,14 @@ const version = "13.0.0";
const start = require("unicode-" + const start = require("unicode-" +
version + version +
"/Binary_Property/ID_Start/code-points.js").filter(function(ch) { "/Binary_Property/ID_Start/code-points.js").filter(function (ch) {
return ch > 0x7f; return ch > 0x7f;
}); });
let last = -1; let last = -1;
const cont = [0x200c, 0x200d].concat( const cont = [0x200c, 0x200d].concat(
require("unicode-" + require("unicode-" +
version + version +
"/Binary_Property/ID_Continue/code-points.js").filter(function(ch) { "/Binary_Property/ID_Continue/code-points.js").filter(function (ch) {
return ch > 0x7f && search(start, ch, last + 1) == -1; return ch > 0x7f && search(start, ch, last + 1) == -1;
}) })
); );

View File

@ -1,22 +1,22 @@
import { isIdentifierName } from ".."; import { isIdentifierName } from "..";
describe("isIdentifierName", function() { describe("isIdentifierName", function () {
it("returns false if provided string is empty", function() { it("returns false if provided string is empty", function () {
expect(isIdentifierName("")).toBe(false); expect(isIdentifierName("")).toBe(false);
}); });
it.each(["hello", "$", "ゆゆ式", "$20", "hello20", "_", "if"])( it.each(["hello", "$", "ゆゆ式", "$20", "hello20", "_", "if"])(
"returns true if provided string %p is an IdentifierName", "returns true if provided string %p is an IdentifierName",
function(word) { function (word) {
expect(isIdentifierName(word)).toBe(true); expect(isIdentifierName(word)).toBe(true);
}, },
); );
it.each(["+hello", "0$", "-ゆゆ式", "#_", "_#"])( it.each(["+hello", "0$", "-ゆゆ式", "#_", "_#"])(
"returns false if provided string %p is not an IdentifierName", "returns false if provided string %p is not an IdentifierName",
function(word) { function (word) {
expect(isIdentifierName(word)).toBe(false); expect(isIdentifierName(word)).toBe(false);
}, },
); );
it("supports astral symbols", function() { it("supports astral symbols", function () {
expect(isIdentifierName("x\uDB40\uDDD5")).toBe(true); expect(isIdentifierName("x\uDB40\uDDD5")).toBe(true);
}); });
}); });

View File

@ -77,7 +77,7 @@ function getTokenType(match) {
* Highlight `text` using the token definitions in `defs`. * Highlight `text` using the token definitions in `defs`.
*/ */
function highlightTokens(defs: Object, text: string) { function highlightTokens(defs: Object, text: string) {
return text.replace(jsTokens, function(...args) { return text.replace(jsTokens, function (...args) {
const type = getTokenType(args); const type = getTokenType(args);
const colorize = defs[type]; const colorize = defs[type];
if (colorize) { if (colorize) {

View File

@ -2,24 +2,24 @@ import chalk from "chalk";
import stripAnsi from "strip-ansi"; import stripAnsi from "strip-ansi";
import highlight, { shouldHighlight, getChalk } from ".."; import highlight, { shouldHighlight, getChalk } from "..";
describe("@babel/highlight", function() { describe("@babel/highlight", function () {
function stubColorSupport(supported) { function stubColorSupport(supported) {
let originalSupportsColor; let originalSupportsColor;
beforeEach(function() { beforeEach(function () {
originalSupportsColor = chalk.supportsColor; originalSupportsColor = chalk.supportsColor;
chalk.supportsColor = supported; chalk.supportsColor = supported;
}); });
afterEach(function() { afterEach(function () {
chalk.supportsColor = originalSupportsColor; chalk.supportsColor = originalSupportsColor;
}); });
} }
describe("highlight", function() { describe("highlight", function () {
describe("when colors are supported", function() { describe("when colors are supported", function () {
stubColorSupport(true); stubColorSupport(true);
it("highlights code", function() { it("highlights code", function () {
const code = "console.log('hi')"; const code = "console.log('hi')";
const result = highlight(code); const result = highlight(code);
const stripped = stripAnsi(result); const stripped = stripAnsi(result);
@ -28,10 +28,10 @@ describe("@babel/highlight", function() {
}); });
}); });
describe("when colors are not supported", function() { describe("when colors are not supported", function () {
stubColorSupport(false); stubColorSupport(false);
it("does not attempt to highlight code", function() { it("does not attempt to highlight code", function () {
const code = "console.log('hi')"; const code = "console.log('hi')";
const result = highlight(code); const result = highlight(code);
const stripped = stripAnsi(result); const stripped = stripAnsi(result);
@ -39,8 +39,8 @@ describe("@babel/highlight", function() {
expect(result).toBe(code); expect(result).toBe(code);
}); });
describe("and the forceColor option is passed", function() { describe("and the forceColor option is passed", function () {
it("highlights the code anyway", function() { it("highlights the code anyway", function () {
const code = "console.log('hi')"; const code = "console.log('hi')";
const result = highlight(code, { forceColor: true }); const result = highlight(code, { forceColor: true });
const stripped = stripAnsi(result); const stripped = stripAnsi(result);
@ -51,42 +51,42 @@ describe("@babel/highlight", function() {
}); });
}); });
describe("shouldHighlight", function() { describe("shouldHighlight", function () {
describe("when colors are supported", function() { describe("when colors are supported", function () {
stubColorSupport(true); stubColorSupport(true);
it("returns true", function() { it("returns true", function () {
expect(shouldHighlight({})).toBeTruthy(); expect(shouldHighlight({})).toBeTruthy();
}); });
}); });
describe("when colors are not supported", function() { describe("when colors are not supported", function () {
stubColorSupport(false); stubColorSupport(false);
it("returns false", function() { it("returns false", function () {
expect(shouldHighlight({})).toBeFalsy(); expect(shouldHighlight({})).toBeFalsy();
}); });
describe("and the forceColor option is passed", function() { describe("and the forceColor option is passed", function () {
it("returns true", function() { it("returns true", function () {
expect(shouldHighlight({ forceColor: true })).toBeTruthy(); expect(shouldHighlight({ forceColor: true })).toBeTruthy();
}); });
}); });
}); });
}); });
describe("getChalk", function() { describe("getChalk", function () {
describe("when colors are supported", function() { describe("when colors are supported", function () {
stubColorSupport(true); stubColorSupport(true);
describe("when forceColor is not passed", function() { describe("when forceColor is not passed", function () {
it("returns a Chalk instance", function() { it("returns a Chalk instance", function () {
expect(getChalk({}).constructor).toBe(chalk.constructor); expect(getChalk({}).constructor).toBe(chalk.constructor);
}); });
}); });
describe("when forceColor is passed", function() { describe("when forceColor is passed", function () {
it("returns a Chalk instance", function() { it("returns a Chalk instance", function () {
expect(getChalk({ forceColor: true }).constructor).toBe( expect(getChalk({ forceColor: true }).constructor).toBe(
chalk.constructor, chalk.constructor,
); );
@ -94,17 +94,17 @@ describe("@babel/highlight", function() {
}); });
}); });
describe("when colors are not supported", function() { describe("when colors are not supported", function () {
stubColorSupport(false); stubColorSupport(false);
describe("when forceColor is not passed", function() { describe("when forceColor is not passed", function () {
it("returns a Chalk instance", function() { it("returns a Chalk instance", function () {
expect(getChalk({}).constructor).toBe(chalk.constructor); expect(getChalk({}).constructor).toBe(chalk.constructor);
}); });
}); });
describe("when forceColor is passed", function() { describe("when forceColor is passed", function () {
it("returns a Chalk instance", function() { it("returns a Chalk instance", function () {
expect(getChalk({ forceColor: true }).constructor).toBe( expect(getChalk({ forceColor: true }).constructor).toBe(
chalk.constructor, chalk.constructor,
); );

View File

@ -120,7 +120,7 @@ const replPlugin = ({ types: t }) => ({
}, },
}); });
const _eval = function(code, filename) { const _eval = function (code, filename) {
code = code.trim(); code = code.trim();
if (!code) return undefined; if (!code) return undefined;
@ -162,7 +162,7 @@ if (program.eval || program.print) {
let i = 0; let i = 0;
let ignoreNext = false; let ignoreNext = false;
args.some(function(arg, i2) { args.some(function (arg, i2) {
if (ignoreNext) { if (ignoreNext) {
ignoreNext = false; ignoreNext = false;
return; return;

View File

@ -45,7 +45,7 @@ const aliases = new Map([
["-gc", "--expose-gc"], ["-gc", "--expose-gc"],
]); ]);
getV8Flags(function(err, v8Flags) { getV8Flags(function (err, v8Flags) {
for (let i = 0; i < babelArgs.length; i++) { for (let i = 0; i < babelArgs.length; i++) {
const arg = babelArgs[i]; const arg = babelArgs[i];
const flag = arg.split("=")[0]; const flag = arg.split("=")[0];
@ -87,8 +87,8 @@ getV8Flags(function(err, v8Flags) {
const proc = child_process.spawn(process.argv[0], args, { const proc = child_process.spawn(process.argv[0], args, {
stdio: "inherit", stdio: "inherit",
}); });
proc.on("exit", function(code, signal) { proc.on("exit", function (code, signal) {
process.on("exit", function() { process.on("exit", function () {
if (signal) { if (signal) {
process.kill(process.pid, signal); process.kill(process.pid, signal);
} else { } else {

View File

@ -11,36 +11,36 @@ 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 fileFilter = function(x) { const fileFilter = function (x) {
return x !== ".DS_Store"; return x !== ".DS_Store";
}; };
const outputFileSync = function(filePath, data) { const outputFileSync = function (filePath, data) {
makeDirSync(path.dirname(filePath)); makeDirSync(path.dirname(filePath));
fs.writeFileSync(filePath, data); fs.writeFileSync(filePath, data);
}; };
const readDir = function(loc, filter) { const readDir = function (loc, filter) {
const files = {}; const files = {};
if (fs.existsSync(loc)) { if (fs.existsSync(loc)) {
readdir(loc, filter).forEach(function(filename) { readdir(loc, filter).forEach(function (filename) {
files[filename] = helper.readFile(path.join(loc, filename)); files[filename] = helper.readFile(path.join(loc, filename));
}); });
} }
return files; return files;
}; };
const saveInFiles = function(files) { const saveInFiles = function (files) {
// Place an empty .babelrc in each test so tests won't unexpectedly get to repo-level config. // Place an empty .babelrc in each test so tests won't unexpectedly get to repo-level config.
outputFileSync(".babelrc", "{}"); outputFileSync(".babelrc", "{}");
Object.keys(files).forEach(function(filename) { Object.keys(files).forEach(function (filename) {
const content = files[filename]; const content = files[filename];
outputFileSync(filename, content); outputFileSync(filename, content);
}); });
}; };
const assertTest = function(stdout, stderr, opts) { const assertTest = function (stdout, stderr, opts) {
const expectStderr = opts.stderr.trim(); const expectStderr = opts.stderr.trim();
stderr = stderr.trim(); stderr = stderr.trim();
@ -71,7 +71,7 @@ const assertTest = function(stdout, stderr, opts) {
if (opts.outFiles) { if (opts.outFiles) {
const actualFiles = readDir(path.join(tmpLoc)); const actualFiles = readDir(path.join(tmpLoc));
Object.keys(actualFiles).forEach(function(filename) { Object.keys(actualFiles).forEach(function (filename) {
if (!Object.prototype.hasOwnProperty.call(opts.inFiles, filename)) { if (!Object.prototype.hasOwnProperty.call(opts.inFiles, filename)) {
const expected = opts.outFiles[filename]; const expected = opts.outFiles[filename];
const actual = actualFiles[filename]; const actual = actualFiles[filename];
@ -84,16 +84,16 @@ const assertTest = function(stdout, stderr, opts) {
} }
}); });
Object.keys(opts.outFiles).forEach(function(filename) { Object.keys(opts.outFiles).forEach(function (filename) {
expect(actualFiles).toHaveProperty(filename); expect(actualFiles).toHaveProperty(filename);
}); });
} }
}; };
const buildTest = function(binName, testName, opts) { const buildTest = function (binName, testName, opts) {
const binLoc = path.join(__dirname, "../lib", binName); const binLoc = path.join(__dirname, "../lib", binName);
return function(callback) { return function (callback) {
saveInFiles(opts.inFiles); saveInFiles(opts.inFiles);
let args = [binLoc]; let args = [binLoc];
args.push("--config-file", "../config.json"); args.push("--config-file", "../config.json");
@ -104,15 +104,15 @@ const buildTest = function(binName, testName, opts) {
let stderr = ""; let stderr = "";
let stdout = ""; let stdout = "";
spawn.stderr.on("data", function(chunk) { spawn.stderr.on("data", function (chunk) {
stderr += chunk; stderr += chunk;
}); });
spawn.stdout.on("data", function(chunk) { spawn.stdout.on("data", function (chunk) {
stdout += chunk; stdout += chunk;
}); });
spawn.on("close", function() { spawn.on("close", function () {
let err; let err;
try { try {
@ -136,11 +136,11 @@ const buildTest = function(binName, testName, opts) {
}; };
}; };
fs.readdirSync(fixtureLoc).forEach(function(binName) { fs.readdirSync(fixtureLoc).forEach(function (binName) {
if (binName[0] === ".") return; if (binName[0] === ".") return;
const suiteLoc = path.join(fixtureLoc, binName); const suiteLoc = path.join(fixtureLoc, binName);
describe("bin/" + binName, function() { describe("bin/" + binName, function () {
let cwd; let cwd;
beforeEach(() => { beforeEach(() => {
@ -161,7 +161,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) {
process.chdir(cwd); process.chdir(cwd);
}); });
fs.readdirSync(suiteLoc).forEach(function(testName) { fs.readdirSync(suiteLoc).forEach(function (testName) {
if (testName[0] === ".") return; if (testName[0] === ".") return;
const testLoc = path.join(suiteLoc, testName); const testLoc = path.join(suiteLoc, testName);
@ -173,7 +173,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) {
const optionsLoc = path.join(testLoc, "options.json"); const optionsLoc = path.join(testLoc, "options.json");
if (fs.existsSync(optionsLoc)) merge(opts, require(optionsLoc)); if (fs.existsSync(optionsLoc)) merge(opts, require(optionsLoc));
["stdout", "stdin", "stderr"].forEach(function(key) { ["stdout", "stdin", "stderr"].forEach(function (key) {
const loc = path.join(testLoc, key + ".txt"); const loc = path.join(testLoc, key + ".txt");
if (fs.existsSync(loc)) { if (fs.existsSync(loc)) {
opts[key] = helper.readFile(loc); opts[key] = helper.readFile(loc);

View File

@ -39,13 +39,13 @@ tt.jsxText = new TokenType("jsxText", { beforeExpr: true });
tt.jsxTagStart = new TokenType("jsxTagStart", { startsExpr: true }); tt.jsxTagStart = new TokenType("jsxTagStart", { startsExpr: true });
tt.jsxTagEnd = new TokenType("jsxTagEnd"); tt.jsxTagEnd = new TokenType("jsxTagEnd");
tt.jsxTagStart.updateContext = function() { tt.jsxTagStart.updateContext = function () {
this.state.context.push(tc.j_expr); // treat as beginning of JSX expression this.state.context.push(tc.j_expr); // treat as beginning of JSX expression
this.state.context.push(tc.j_oTag); // start opening tag context this.state.context.push(tc.j_oTag); // start opening tag context
this.state.exprAllowed = false; this.state.exprAllowed = false;
}; };
tt.jsxTagEnd.updateContext = function(prevType) { tt.jsxTagEnd.updateContext = function (prevType) {
const out = this.state.context.pop(); const out = this.state.context.pop();
if ((out === tc.j_oTag && prevType === tt.slash) || out === tc.j_cTag) { if ((out === tc.j_oTag && prevType === tt.slash) || out === tc.j_cTag) {
this.state.context.pop(); this.state.context.pop();

View File

@ -41,7 +41,7 @@ export const types: {
// Token-specific context update code // Token-specific context update code
tt.parenR.updateContext = tt.braceR.updateContext = function() { tt.parenR.updateContext = tt.braceR.updateContext = function () {
if (this.state.context.length === 1) { if (this.state.context.length === 1) {
this.state.exprAllowed = true; this.state.exprAllowed = true;
return; return;
@ -55,7 +55,7 @@ tt.parenR.updateContext = tt.braceR.updateContext = function() {
this.state.exprAllowed = !out.isExpr; this.state.exprAllowed = !out.isExpr;
}; };
tt.name.updateContext = function(prevType) { tt.name.updateContext = function (prevType) {
let allowed = false; let allowed = false;
if (prevType !== tt.dot) { if (prevType !== tt.dot) {
if ( if (
@ -75,19 +75,19 @@ tt.name.updateContext = function(prevType) {
} }
}; };
tt.braceL.updateContext = function(prevType) { tt.braceL.updateContext = function (prevType) {
this.state.context.push( this.state.context.push(
this.braceIsBlock(prevType) ? types.braceStatement : types.braceExpression, this.braceIsBlock(prevType) ? types.braceStatement : types.braceExpression,
); );
this.state.exprAllowed = true; this.state.exprAllowed = true;
}; };
tt.dollarBraceL.updateContext = function() { tt.dollarBraceL.updateContext = function () {
this.state.context.push(types.templateQuasi); this.state.context.push(types.templateQuasi);
this.state.exprAllowed = true; this.state.exprAllowed = true;
}; };
tt.parenL.updateContext = function(prevType) { tt.parenL.updateContext = function (prevType) {
const statementParens = const statementParens =
prevType === tt._if || prevType === tt._if ||
prevType === tt._for || prevType === tt._for ||
@ -99,11 +99,11 @@ tt.parenL.updateContext = function(prevType) {
this.state.exprAllowed = true; this.state.exprAllowed = true;
}; };
tt.incDec.updateContext = function() { tt.incDec.updateContext = function () {
// tokExprAllowed stays unchanged // tokExprAllowed stays unchanged
}; };
tt._function.updateContext = tt._class.updateContext = function(prevType) { tt._function.updateContext = tt._class.updateContext = function (prevType) {
if (prevType === tt.dot || prevType === tt.questionDot) { if (prevType === tt.dot || prevType === tt.questionDot) {
// when function/class follows dot/questionDot, it is part of // when function/class follows dot/questionDot, it is part of
// (optional)MemberExpression, then we don't need to push new token context // (optional)MemberExpression, then we don't need to push new token context
@ -128,7 +128,7 @@ tt._function.updateContext = tt._class.updateContext = function(prevType) {
this.state.exprAllowed = false; this.state.exprAllowed = false;
}; };
tt.backQuote.updateContext = function() { tt.backQuote.updateContext = function () {
if (this.curContext() === types.template) { if (this.curContext() === types.template) {
this.state.context.pop(); this.state.context.pop();
} else { } else {
@ -137,6 +137,6 @@ tt.backQuote.updateContext = function() {
this.state.exprAllowed = false; this.state.exprAllowed = false;
}; };
tt.star.updateContext = function() { tt.star.updateContext = function () {
this.state.exprAllowed = false; this.state.exprAllowed = false;
}; };

View File

@ -26,8 +26,9 @@ class FixtureError extends Error {
{ highlightCode: true }, { highlightCode: true },
) + ) +
"\n" + "\n" +
`at fixture (${fixturePath}:${previousError.loc.line}:${previousError `at fixture (${fixturePath}:${previousError.loc.line}:${
.loc.column + 1})\n`; previousError.loc.column + 1
})\n`;
} }
this.stack = this.stack =
@ -36,22 +37,19 @@ class FixtureError extends Error {
previousError.message + previousError.message +
"\n" + "\n" +
fixtureStackFrame + fixtureStackFrame +
previousError.stack previousError.stack.split("\n").slice(messageLines).join("\n");
.split("\n")
.slice(messageLines)
.join("\n");
} }
} }
export function runFixtureTests(fixturesPath, parseFunction) { export function runFixtureTests(fixturesPath, parseFunction) {
const fixtures = getFixtures(fixturesPath); const fixtures = getFixtures(fixturesPath);
Object.keys(fixtures).forEach(function(name) { Object.keys(fixtures).forEach(function (name) {
fixtures[name].forEach(function(testSuite) { fixtures[name].forEach(function (testSuite) {
testSuite.tests.forEach(function(task) { testSuite.tests.forEach(function (task) {
const testFn = task.disabled ? it.skip : it; const testFn = task.disabled ? it.skip : it;
testFn(name + "/" + testSuite.title + "/" + task.title, function() { testFn(name + "/" + testSuite.title + "/" + task.title, function () {
try { try {
runTest(task, parseFunction); runTest(task, parseFunction);
} catch (err) { } catch (err) {
@ -82,9 +80,9 @@ export function runFixtureTests(fixturesPath, parseFunction) {
export function runThrowTestsWithEstree(fixturesPath, parseFunction) { export function runThrowTestsWithEstree(fixturesPath, parseFunction) {
const fixtures = getFixtures(fixturesPath); const fixtures = getFixtures(fixturesPath);
Object.keys(fixtures).forEach(function(name) { Object.keys(fixtures).forEach(function (name) {
fixtures[name].forEach(function(testSuite) { fixtures[name].forEach(function (testSuite) {
testSuite.tests.forEach(function(task) { testSuite.tests.forEach(function (task) {
if (!task.options.throws) return; if (!task.options.throws) return;
task.options.plugins = task.options.plugins || []; task.options.plugins = task.options.plugins || [];
@ -92,7 +90,7 @@ export function runThrowTestsWithEstree(fixturesPath, parseFunction) {
const testFn = task.disabled ? it.skip : it; const testFn = task.disabled ? it.skip : it;
testFn(name + "/" + testSuite.title + "/" + task.title, function() { testFn(name + "/" + testSuite.title + "/" + task.title, function () {
try { try {
runTest(task, parseFunction); runTest(task, parseFunction);
} catch (err) { } catch (err) {

View File

@ -4,12 +4,12 @@ function getParser(code, plugins) {
return () => parse(code, { plugins, sourceType: "module" }); return () => parse(code, { plugins, sourceType: "module" });
} }
describe("plugin options", function() { describe("plugin options", function () {
describe("the first options are used", function() { describe("the first options are used", function () {
// NOTE: This test is not specific about decorators, it can be applied // NOTE: This test is not specific about decorators, it can be applied
// to any plugin with options. // to any plugin with options.
it("when they aren't specified", function() { it("when they aren't specified", function () {
const WITHOUT_FLAG = "flow"; const WITHOUT_FLAG = "flow";
const WITH_FLAG = ["flow", { all: true }]; const WITH_FLAG = ["flow", { all: true }];
@ -52,7 +52,7 @@ describe("plugin options", function() {
).toMatchObject(AST_WITH_FLAG); ).toMatchObject(AST_WITH_FLAG);
}); });
it("when they are specified", function() { it("when they are specified", function () {
const NAME = "decorators"; const NAME = "decorators";
const OPT_1 = [NAME, { decoratorsBeforeExport: true }]; const OPT_1 = [NAME, { decoratorsBeforeExport: true }];
const OPT_2 = [NAME, { decoratorsBeforeExport: false }]; const OPT_2 = [NAME, { decoratorsBeforeExport: false }];

View File

@ -33,7 +33,7 @@ const buildForAwait = template(`
} }
`); `);
export default function(path, { getAsyncIterator }) { export default function (path, { getAsyncIterator }) {
const { node, scope, parent } = path; const { node, scope, parent } = path;
const stepKey = scope.generateUidIdentifier("step"); const stepKey = scope.generateUidIdentifier("step");

View File

@ -71,7 +71,7 @@ function applyClassDecorators(classPath) {
return decorators return decorators
.map(dec => dec.expression) .map(dec => dec.expression)
.reverse() .reverse()
.reduce(function(acc, decorator) { .reduce(function (acc, decorator) {
return buildClassDecorator({ return buildClassDecorator({
CLASS_REF: t.cloneNode(name), CLASS_REF: t.cloneNode(name),
DECORATOR: t.cloneNode(decorator), DECORATOR: t.cloneNode(decorator),
@ -116,7 +116,7 @@ function applyTargetDecorators(path, state, decoratedProps) {
path.isClass() ? "class" : "obj", path.isClass() ? "class" : "obj",
); );
const exprs = decoratedProps.reduce(function(acc, node) { const exprs = decoratedProps.reduce(function (acc, node) {
const decorators = node.decorators || []; const decorators = node.decorators || [];
node.decorators = null; node.decorators = null;

View File

@ -234,7 +234,7 @@ export default declare((api, opts) => {
// example: f({...R}, a = R) // example: f({...R}, a = R)
let idInRest = false; let idInRest = false;
const IdentifierHandler = function(path, functionScope) { const IdentifierHandler = function (path, functionScope) {
const name = path.node.name; const name = path.node.name;
if ( if (
path.scope.getBinding(name) === functionScope.getBinding(name) && path.scope.getBinding(name) === functionScope.getBinding(name) &&

View File

@ -10,34 +10,34 @@ function makeParser(code, options) {
}); });
} }
describe("'legacy' option", function() { describe("'legacy' option", function () {
test("must be boolean", function() { test("must be boolean", function () {
expect(makeParser("", { legacy: "legacy" })).toThrow(); expect(makeParser("", { legacy: "legacy" })).toThrow();
}); });
test("'legacy': false", function() { test("'legacy': false", function () {
expect(makeParser("({ @dec fn() {} })", { legacy: false })).toThrow(); expect(makeParser("({ @dec fn() {} })", { legacy: false })).toThrow();
}); });
test("'legacy': true", function() { test("'legacy': true", function () {
expect(makeParser("({ @dec fn() {} })", { legacy: true })).not.toThrow(); expect(makeParser("({ @dec fn() {} })", { legacy: true })).not.toThrow();
}); });
test("defaults to 'false'", function() { test("defaults to 'false'", function () {
expect(makeParser("({ @dec fn() {} })", {})).toThrow(); expect(makeParser("({ @dec fn() {} })", {})).toThrow();
}); });
}); });
describe("'decoratorsBeforeExport' option", function() { describe("'decoratorsBeforeExport' option", function () {
test("must be boolean", function() { test("must be boolean", function () {
expect(makeParser("", { decoratorsBeforeExport: "before" })).toThrow(); expect(makeParser("", { decoratorsBeforeExport: "before" })).toThrow();
}); });
test("is required", function() { test("is required", function () {
expect(makeParser("", { legacy: false })).toThrow(/decoratorsBeforeExport/); expect(makeParser("", { legacy: false })).toThrow(/decoratorsBeforeExport/);
}); });
test("is incompatible with legacy", function() { test("is incompatible with legacy", function () {
expect( expect(
makeParser("", { decoratorsBeforeExport: false, legacy: true }), makeParser("", { decoratorsBeforeExport: false, legacy: true }),
).toThrow(); ).toThrow();
@ -59,7 +59,7 @@ describe("'decoratorsBeforeExport' option", function() {
(code === BEFORE ? "before" : "after") + (code === BEFORE ? "before" : "after") +
"export"; "export";
test(name, function() { test(name, function () {
const expectTheParser = expect( const expectTheParser = expect(
makeParser(code, { decoratorsBeforeExport: before }), makeParser(code, { decoratorsBeforeExport: before }),
); );

View File

@ -320,7 +320,7 @@ export default function transformClass(
path.traverse(findThisesVisitor); path.traverse(findThisesVisitor);
let thisRef = function() { let thisRef = function () {
const ref = path.scope.generateDeclaredUidIdentifier("this"); const ref = path.scope.generateDeclaredUidIdentifier("this");
thisRef = () => t.cloneNode(ref); thisRef = () => t.cloneNode(ref);
return ref; return ref;
@ -360,7 +360,7 @@ export default function transformClass(
wrapSuperCall(bareSuper, classState.superName, thisRef, body); wrapSuperCall(bareSuper, classState.superName, thisRef, body);
if (guaranteedSuperBeforeFinish) { if (guaranteedSuperBeforeFinish) {
bareSuper.find(function(parentPath) { bareSuper.find(function (parentPath) {
// hit top so short circuit // hit top so short circuit
if (parentPath === path) { if (parentPath === path) {
return true; return true;

View File

@ -159,7 +159,7 @@ export default declare((api, options) => {
let mutatorRef; let mutatorRef;
const getMutatorId = function() { const getMutatorId = function () {
if (!mutatorRef) { if (!mutatorRef) {
mutatorRef = scope.generateUidIdentifier("mutatorMap"); mutatorRef = scope.generateUidIdentifier("mutatorMap");

View File

@ -1,6 +1,6 @@
const babel = require("@babel/core"); const babel = require("@babel/core");
test("Doesn't use the same object for two different nodes in the AST", function() { test("Doesn't use the same object for two different nodes in the AST", function () {
const code = 'import Foo from "bar"; Foo; Foo;'; const code = 'import Foo from "bar"; Foo; Foo;';
const ast = babel.transform(code, { const ast = babel.transform(code, {

View File

@ -1,7 +1,7 @@
const babel = require("@babel/core"); const babel = require("@babel/core");
const vm = require("vm"); const vm = require("vm");
test("Re-export doesn't overwrite __esModule flag", function() { test("Re-export doesn't overwrite __esModule flag", function () {
let code = 'export * from "./dep";'; let code = 'export * from "./dep";';
const depStub = { const depStub = {
__esModule: false, __esModule: false,
@ -11,7 +11,7 @@ test("Re-export doesn't overwrite __esModule flag", function() {
module: { module: {
exports: {}, exports: {},
}, },
require: function(id) { require: function (id) {
if (id === "./dep") return depStub; if (id === "./dep") return depStub;
return require(id); return require(id);
}, },

View File

@ -253,7 +253,7 @@ export default declare((api, options) => {
function pushModule(source, key, specifiers) { function pushModule(source, key, specifiers) {
let module; let module;
modules.forEach(function(m) { modules.forEach(function (m) {
if (m.key === source) { if (m.key === source) {
module = m; module = m;
} }
@ -424,7 +424,7 @@ export default declare((api, options) => {
} }
} }
modules.forEach(function(specifiers) { modules.forEach(function (specifiers) {
let setterBody = []; let setterBody = [];
const target = path.scope.generateUid(specifiers.key); const target = path.scope.generateUid(specifiers.key);

View File

@ -1,7 +1,7 @@
/* eslint-disable @babel/development/plugin-name */ /* eslint-disable @babel/development/plugin-name */
import { createRegExpFeaturePlugin } from "@babel/helper-create-regexp-features-plugin"; import { createRegExpFeaturePlugin } from "@babel/helper-create-regexp-features-plugin";
export default function(core, options) { export default function (core, options) {
const { runtime = true } = options; const { runtime = true } = options;
if (typeof runtime !== "boolean") { if (typeof runtime !== "boolean") {
throw new Error("The 'runtime' option must be boolean"); throw new Error("The 'runtime' option must be boolean");

View File

@ -7,7 +7,7 @@ export default declare(api => {
name: "transform-object-assign", name: "transform-object-assign",
visitor: { visitor: {
CallExpression: function(path, file) { CallExpression: function (path, file) {
if (path.get("callee").matchesPattern("Object.assign")) { if (path.get("callee").matchesPattern("Object.assign")) {
path.node.callee = file.addHelper("extends"); path.node.callee = file.addHelper("extends");
} }

View File

@ -22,7 +22,7 @@ export default declare(api => {
const mutatorMap = {}; const mutatorMap = {};
node.properties = node.properties.filter(function(prop) { node.properties = node.properties.filter(function (prop) {
if (!prop.computed && (prop.kind === "get" || prop.kind === "set")) { if (!prop.computed && (prop.kind === "get" || prop.kind === "set")) {
defineMap.push(mutatorMap, prop, null, file); defineMap.push(mutatorMap, prop, null, file);
return false; return false;

View File

@ -78,7 +78,7 @@ export default declare(api => {
let id; let id;
// crawl up the ancestry looking for possible candidates for displayName inference // crawl up the ancestry looking for possible candidates for displayName inference
path.find(function(path) { path.find(function (path) {
if (path.isAssignmentExpression()) { if (path.isAssignmentExpression()) {
id = path.node.left; id = path.node.left;
} else if (path.isObjectProperty()) { } else if (path.isObjectProperty()) {

View File

@ -92,7 +92,7 @@ export default declare((api, options) => {
}, },
}; };
visitor.JSXAttribute = function(path) { visitor.JSXAttribute = function (path) {
if (t.isJSXElement(path.node.value)) { if (t.isJSXElement(path.node.value)) {
path.node.value = t.jsxExpressionContainer(path.node.value); path.node.value = t.jsxExpressionContainer(path.node.value);
} }

View File

@ -78,7 +78,7 @@ function writeCoreJS({
} }
const runtimeRoot = proposals ? "core-js" : "core-js-stable"; const runtimeRoot = proposals ? "core-js" : "core-js-stable";
paths.forEach(function(corejsPath) { paths.forEach(function (corejsPath) {
outputFile( outputFile(
path.join(pkgDirname, runtimeRoot, `${corejsPath}.js`), path.join(pkgDirname, runtimeRoot, `${corejsPath}.js`),
`module.exports = require("${corejsRoot}/${corejsPath}");` `module.exports = require("${corejsRoot}/${corejsPath}");`

View File

@ -1,4 +1,4 @@
export default function(moduleName, dirname, absoluteRuntime) { export default function (moduleName, dirname, absoluteRuntime) {
if (absoluteRuntime === false) return moduleName; if (absoluteRuntime === false) return moduleName;
throw new Error( throw new Error(

View File

@ -1,7 +1,7 @@
import path from "path"; import path from "path";
import resolve from "resolve"; import resolve from "resolve";
export default function(moduleName, dirname, absoluteRuntime) { export default function (moduleName, dirname, absoluteRuntime) {
if (absoluteRuntime === false) return moduleName; if (absoluteRuntime === false) return moduleName;
return resolveAbsoluteRuntime( return resolveAbsoluteRuntime(

View File

@ -25,7 +25,7 @@ export default declare((api, options) => {
*/ */
function buildConcatCallExpressions(items) { function buildConcatCallExpressions(items) {
let avail = true; let avail = true;
return items.reduce(function(left, right) { return items.reduce(function (left, right) {
let canBeInserted = t.isLiteral(right); let canBeInserted = t.isLiteral(right);
if (!canBeInserted && avail) { if (!canBeInserted && avail) {

View File

@ -2,6 +2,6 @@
const defaultExcludesForLooseMode = ["transform-typeof-symbol"]; const defaultExcludesForLooseMode = ["transform-typeof-symbol"];
export default function({ loose }: { loose: boolean }): null | string[] { export default function ({ loose }: { loose: boolean }): null | string[] {
return loose ? defaultExcludesForLooseMode : null; return loose ? defaultExcludesForLooseMode : null;
} }

View File

@ -14,7 +14,7 @@ import { logEntryPolyfills } from "../../debug";
import type { InternalPluginOptions } from "../../types"; import type { InternalPluginOptions } from "../../types";
import type { NodePath } from "@babel/traverse"; import type { NodePath } from "@babel/traverse";
export default function( export default function (
_: any, _: any,
{ {
include, include,
@ -53,7 +53,7 @@ export default function(
pre() { pre() {
this.importPolyfillIncluded = false; this.importPolyfillIncluded = false;
this.replaceBySeparateModulesImport = function(path) { this.replaceBySeparateModulesImport = function (path) {
this.importPolyfillIncluded = true; this.importPolyfillIncluded = true;
if (regenerator) { if (regenerator) {

View File

@ -8,7 +8,7 @@ export const defaultWebIncludes = [
"web.dom.iterable", "web.dom.iterable",
]; ];
export default function(targets: Targets): null | string[] { export default function (targets: Targets): null | string[] {
const targetNames = Object.keys(targets); const targetNames = Object.keys(targets);
const isAnyTarget = !targetNames.length; const isAnyTarget = !targetNames.length;
const isWebTarget = targetNames.some(name => name !== "node"); const isWebTarget = targetNames.some(name => name !== "node");

View File

@ -26,7 +26,7 @@ const NO_DIRECT_POLYFILL_IMPORT = `
When setting \`useBuiltIns: 'usage'\`, polyfills are automatically imported when needed. When setting \`useBuiltIns: 'usage'\`, polyfills are automatically imported when needed.
Please remove the \`import '@babel/polyfill'\` call or use \`useBuiltIns: 'entry'\` instead.`; Please remove the \`import '@babel/polyfill'\` call or use \`useBuiltIns: 'entry'\` instead.`;
export default function( export default function (
{ types: t }: { types: Object }, { types: t }: { types: Object },
{ include, exclude, polyfillTargets, debug }: InternalPluginOptions, { include, exclude, polyfillTargets, debug }: InternalPluginOptions,
) { ) {
@ -191,14 +191,14 @@ export default function(
pre({ path }: { path: NodePath }) { pre({ path }: { path: NodePath }) {
this.polyfillsSet = new Set(); this.polyfillsSet = new Set();
this.addImport = function(builtIn) { this.addImport = function (builtIn) {
if (!this.polyfillsSet.has(builtIn)) { if (!this.polyfillsSet.has(builtIn)) {
this.polyfillsSet.add(builtIn); this.polyfillsSet.add(builtIn);
createImport(path, builtIn); createImport(path, builtIn);
} }
}; };
this.addUnsupported = function(builtIn) { this.addUnsupported = function (builtIn) {
const modules = Array.isArray(builtIn) ? builtIn : [builtIn]; const modules = Array.isArray(builtIn) ? builtIn : [builtIn];
for (const module of modules) { for (const module of modules) {
if (polyfills.has(module)) { if (polyfills.has(module)) {

View File

@ -35,7 +35,7 @@ const BABEL_POLYFILL_DEPRECATION = `
\`@babel/polyfill\` is deprecated. Please, use required parts of \`core-js\` \`@babel/polyfill\` is deprecated. Please, use required parts of \`core-js\`
and \`regenerator-runtime/runtime\` separately`; and \`regenerator-runtime/runtime\` separately`;
export default function( export default function (
_: any, _: any,
{ corejs, include, exclude, polyfillTargets, debug }: InternalPluginOptions, { corejs, include, exclude, polyfillTargets, debug }: InternalPluginOptions,
) { ) {
@ -115,7 +115,7 @@ export default function(
this.injectedPolyfills = new Set(); this.injectedPolyfills = new Set();
this.polyfillsSet = new Set(); this.polyfillsSet = new Set();
this.replaceBySeparateModulesImport = function(path, modules) { this.replaceBySeparateModulesImport = function (path, modules) {
for (const module of modules) { for (const module of modules) {
this.polyfillsSet.add(module); this.polyfillsSet.add(module);
} }

View File

@ -47,7 +47,7 @@ const corejs3PolyfillsWithShippedProposals = (corejs3ShippedProposalsList: strin
{ ...corejs3PolyfillsWithoutProposals }, { ...corejs3PolyfillsWithoutProposals },
); );
export default function( export default function (
_: any, _: any,
{ {
corejs, corejs,
@ -234,21 +234,21 @@ export default function(
this.injectedPolyfills = new Set(); this.injectedPolyfills = new Set();
this.polyfillsSet = new Set(); this.polyfillsSet = new Set();
this.addUnsupported = function(builtIn) { this.addUnsupported = function (builtIn) {
const modules = Array.isArray(builtIn) ? builtIn : [builtIn]; const modules = Array.isArray(builtIn) ? builtIn : [builtIn];
for (const module of modules) { for (const module of modules) {
this.polyfillsSet.add(module); this.polyfillsSet.add(module);
} }
}; };
this.addBuiltInDependencies = function(builtIn) { this.addBuiltInDependencies = function (builtIn) {
if (has(BuiltIns, builtIn)) { if (has(BuiltIns, builtIn)) {
const BuiltInDependencies = BuiltIns[builtIn]; const BuiltInDependencies = BuiltIns[builtIn];
this.addUnsupported(BuiltInDependencies); this.addUnsupported(BuiltInDependencies);
} }
}; };
this.addPropertyDependencies = function(source = {}, key) { this.addPropertyDependencies = function (source = {}, key) {
const { builtIn, instanceType, isNamespaced } = source; const { builtIn, instanceType, isNamespaced } = source;
if (isNamespaced) return; if (isNamespaced) return;
if (PossibleGlobalObjects.has(builtIn)) { if (PossibleGlobalObjects.has(builtIn)) {

View File

@ -7,7 +7,7 @@ function isRegeneratorSource(source) {
return source === "regenerator-runtime/runtime"; return source === "regenerator-runtime/runtime";
} }
export default function() { export default function () {
const visitor = { const visitor = {
ImportDeclaration(path: NodePath) { ImportDeclaration(path: NodePath) {
if (isRegeneratorSource(getImportSource(path))) { if (isRegeneratorSource(getImportSource(path))) {

View File

@ -3,7 +3,7 @@
import { createImport } from "../../utils"; import { createImport } from "../../utils";
import type { NodePath } from "@babel/traverse"; import type { NodePath } from "@babel/traverse";
export default function() { export default function () {
return { return {
name: "regenerator-usage", name: "regenerator-usage",
pre() { pre() {

View File

@ -8,10 +8,7 @@ import type { Targets } from "@babel/helper-compilation-targets";
export const has = Object.hasOwnProperty.call.bind(Object.hasOwnProperty); export const has = Object.hasOwnProperty.call.bind(Object.hasOwnProperty);
export function getType(target: any): string { export function getType(target: any): string {
return Object.prototype.toString return Object.prototype.toString.call(target).slice(8, -1).toLowerCase();
.call(target)
.slice(8, -1)
.toLowerCase();
} }
export function intersection<T>( export function intersection<T>(

View File

@ -214,8 +214,8 @@ describe("normalize-options", () => {
}); });
}); });
describe("checkDuplicateIncludeExcludes", function() { describe("checkDuplicateIncludeExcludes", function () {
it("should throw if duplicate names in both", function() { it("should throw if duplicate names in both", function () {
expect(() => { expect(() => {
checkDuplicateIncludeExcludes( checkDuplicateIncludeExcludes(
["transform-regenerator", "map"], ["transform-regenerator", "map"],
@ -224,7 +224,7 @@ describe("normalize-options", () => {
}).toThrow(); }).toThrow();
}); });
it("should not throw if no duplicate names in both", function() { it("should not throw if no duplicate names in both", function () {
expect(() => { expect(() => {
checkDuplicateIncludeExcludes(["transform-regenerator"], ["map"]); checkDuplicateIncludeExcludes(["transform-regenerator"], ["map"]);
}).not.toThrow(); }).not.toThrow();

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