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() {
return through.obj(function(file, enc, callback) {
return through.obj(function (file, enc, callback) {
fancyLog(`Compiling '${chalk.cyan(file.relative)}'...`);
callback(null, file);
});
@ -48,7 +48,7 @@ function errorsLogger() {
}
function rename(fn) {
return through.obj(function(file, enc, callback) {
return through.obj(function (file, enc, callback) {
file.path = fn(file);
callback(null, file);
});

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -84,7 +84,7 @@ describe("Babel and Espree", () => {
});
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`", {
eslintScopeManager: true,
eslintVisitorKeys: true,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -10,11 +10,11 @@ const fs = require("fs");
const fixtureLoc = path.join(__dirname, "fixtures");
const tmpLoc = path.join(__dirname, "tmp");
const fileFilter = function(x) {
const fileFilter = function (x) {
return x !== ".DS_Store";
};
const outputFileSync = function(filePath, data) {
const outputFileSync = function (filePath, data) {
makeDirSync(path.dirname(filePath));
fs.writeFileSync(filePath, data);
};
@ -27,29 +27,29 @@ const pluginLocs = [
path.join(__dirname, "/../../babel-plugin-transform-modules-commonjs"),
].join(",");
const readDir = function(loc, filter) {
const readDir = function (loc, filter) {
const files = {};
if (fs.existsSync(loc)) {
readdir(loc, filter).forEach(function(filename) {
readdir(loc, filter).forEach(function (filename) {
files[filename] = helper.readFile(path.join(loc, filename));
});
}
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.
if (!fs.existsSync(".babelrc")) {
outputFileSync(".babelrc", "{}");
}
Object.keys(files).forEach(function(filename) {
Object.keys(files).forEach(function (filename) {
const content = files[filename];
outputFileSync(filename, content);
});
};
const normalizeOutput = function(str, cwd) {
const normalizeOutput = function (str, cwd) {
let prev;
do {
prev = str;
@ -59,7 +59,7 @@ const normalizeOutput = function(str, cwd) {
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);
stderr = normalizeOutput(stderr, cwd);
@ -94,7 +94,7 @@ const assertTest = function(stdout, stderr, opts, cwd) {
if (opts.outFiles) {
const actualFiles = readDir(tmpLoc, fileFilter);
Object.keys(actualFiles).forEach(function(filename) {
Object.keys(actualFiles).forEach(function (filename) {
try {
if (
// 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]);
});
}
};
const buildTest = function(binName, testName, opts) {
const buildTest = function (binName, testName, opts) {
const binLoc = path.join(__dirname, "../lib", binName);
return function(callback) {
return function (callback) {
saveInFiles(opts.inFiles);
let args = [binLoc];
@ -138,15 +138,15 @@ const buildTest = function(binName, testName, opts) {
let stderr = "";
let stdout = "";
spawn.stderr.on("data", function(chunk) {
spawn.stderr.on("data", function (chunk) {
stderr += chunk;
});
spawn.stdout.on("data", function(chunk) {
spawn.stdout.on("data", function (chunk) {
stdout += chunk;
});
spawn.on("close", function() {
spawn.on("close", function () {
let err;
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;
const suiteLoc = path.join(fixtureLoc, binName);
describe("bin/" + binName, function() {
describe("bin/" + binName, function () {
let cwd;
beforeEach(() => {
@ -195,7 +195,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) {
process.chdir(cwd);
});
fs.readdirSync(suiteLoc).forEach(function(testName) {
fs.readdirSync(suiteLoc).forEach(function (testName) {
if (testName.startsWith(".")) return;
const testLoc = path.join(suiteLoc, testName);
@ -229,7 +229,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) {
merge(opts, taskOpts);
}
["stdout", "stdin", "stderr"].forEach(function(key) {
["stdout", "stdin", "stderr"].forEach(function (key) {
const loc = path.join(testLoc, key + ".txt");
opts[key + "Path"] = 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.
*/
export default function(
export default function (
rawLines: string,
lineNumber: number,
colNumber: ?number,

View File

@ -2,8 +2,8 @@ import chalk from "chalk";
import stripAnsi from "strip-ansi";
import codeFrame, { codeFrameColumns } from "..";
describe("@babel/code-frame", function() {
test("basic usage", function() {
describe("@babel/code-frame", function () {
test("basic usage", function () {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
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");
expect(codeFrame(rawLines, 2, null)).toEqual(
[" 1 | class Foo {", "> 2 | constructor()", " 3 | };"].join("\n"),
);
});
test("maximum context lines and padding", function() {
test("maximum context lines and padding", function () {
const rawLines = [
"/**",
" * 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 = [
"/**",
" * Sums two numbers.",
@ -76,7 +76,7 @@ describe("@babel/code-frame", function() {
);
});
test("tabs", function() {
test("tabs", function () {
const rawLines = [
"\tclass Foo {",
"\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 result = codeFrame(rawLines, 1, 9, { highlightCode: true });
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
const rawLines = [
"function a(b, c) {",
@ -141,7 +141,7 @@ describe("@babel/code-frame", function() {
);
});
test("opts.linesAbove", function() {
test("opts.linesAbove", function () {
const rawLines = [
"/**",
" * Sums two numbers.",
@ -167,7 +167,7 @@ describe("@babel/code-frame", function() {
);
});
test("opts.linesBelow", function() {
test("opts.linesBelow", function () {
const rawLines = [
"/**",
" * 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 = [
"/**",
" * 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 = [
"class Foo {",
" 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 = [
"class Foo {",
" constructor() {",
@ -246,7 +246,7 @@ describe("@babel/code-frame", function() {
).toEqual([" 1 | class Foo {", "> 2 | constructor() {"].join("\n"));
});
test("opts.linesBelow single line", function() {
test("opts.linesBelow single line", function () {
const rawLines = [
"class Foo {",
" constructor() {",
@ -263,7 +263,7 @@ describe("@babel/code-frame", function() {
).toEqual(["> 2 | constructor() {"].join("\n"));
});
test("opts.forceColor", function() {
test("opts.forceColor", function () {
const marker = chalk.red.bold;
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");
expect(
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");
expect(
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(
"\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 = [
"class Foo {",
" 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 = [
"class Foo {",
" 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");
expect(
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");
expect(
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 = [
"class Foo {",
" 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 = [
"class Foo {",
" 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";
if (process.env.CHECK_COMPAT_DATA) {
const currentData = fs.readFileSync(dataPath, "utf8");

View File

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

View File

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

View File

@ -9,7 +9,7 @@ import nodeFs from "fs";
export function makeStaticFileCache<T>(
fn: (string, string) => T,
): Gensync<[string], T | null> {
return (makeStrongCache(function*(
return (makeStrongCache(function* (
filepath: string,
cache: CacheConfigurator<?void>,
): 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.
*/
const loadDescriptor = makeWeakCache(function*(
const loadDescriptor = makeWeakCache(function* (
{ value, options, dirname, alias }: UnloadedDescriptor,
cache: CacheConfigurator<SimpleContext>,
): Handler<LoadedDescriptor> {
@ -277,7 +277,7 @@ function* loadPluginDescriptor(
);
}
const instantiatePlugin = makeWeakCache(function*(
const instantiatePlugin = makeWeakCache(function* (
{ value, options, dirname, alias }: LoadedDescriptor,
cache: CacheConfigurator<SimpleContext>,
): Handler<Plugin> {
@ -383,7 +383,7 @@ function chain(a, b) {
const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0];
return function(...args) {
return function (...args) {
for (const fn of fns) {
fn.apply(this, args);
}

View File

@ -15,7 +15,7 @@ import { loadPartialConfig as loadPartialConfigRunner } from "./partial";
export { loadFullConfig as default };
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);
// NOTE: We want to return "null" explicitly, while ?. alone returns undefined
return config?.options ?? null;

View File

@ -135,10 +135,11 @@ export default function* loadPrivatePartialConfig(
};
}
export const loadPartialConfig = gensync<[any], PartialConfig | null>(function*(
inputOpts: mixed,
): Handler<PartialConfig | null> {
const result: ?PrivPartialConfig = yield* loadPrivatePartialConfig(inputOpts);
export const loadPartialConfig = gensync<[any], PartialConfig | null>(
function* (inputOpts: mixed): Handler<PartialConfig | null> {
const result: ?PrivPartialConfig = yield* loadPrivatePartialConfig(
inputOpts,
);
if (!result) return null;
const { options, babelrc, ignore, config } = result;
@ -158,7 +159,8 @@ export const loadPartialConfig = gensync<[any], PartialConfig | null>(function*(
ignore ? ignore.filepath : undefined,
config ? config.filepath : undefined,
);
});
},
);
export type { PartialConfig };

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,8 +6,8 @@ function fixture(...args) {
return path.join(__dirname, "fixtures", "parse", ...args);
}
describe("parse", function() {
it("should parse using configuration from .babelrc when a filename is provided", function() {
describe("parse", function () {
it("should parse using configuration from .babelrc when a filename is provided", function () {
const input = fs.readFileSync(fixture("input.js"), "utf8");
const output = require(fixture("output"));
@ -18,7 +18,7 @@ describe("parse", function() {
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 output = require(fixture("output.json"));

View File

@ -1,8 +1,8 @@
import { transform } from "../lib/index";
import Plugin from "../lib/config/plugin";
describe("traversal path", function() {
it("replaceWithSourceString", function() {
describe("traversal path", function () {
it("replaceWithSourceString", function () {
const expectCode = "function foo() {}";
const actualCode = transform(expectCode, {
@ -10,7 +10,7 @@ describe("traversal path", function() {
plugins: [
new Plugin({
visitor: {
FunctionDeclaration: function(path) {
FunctionDeclaration: function (path) {
path.replaceWithSourceString("console.whatever()");
},
},
@ -21,7 +21,7 @@ describe("traversal path", function() {
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 actualCode = transform(expectCode, {
@ -29,7 +29,7 @@ describe("traversal path", function() {
plugins: [
new Plugin({
visitor: {
ArrowFunctionExpression: function(path) {
ArrowFunctionExpression: function (path) {
path.get("body").replaceWith({
type: "BlockStatement",
body: [
@ -51,7 +51,7 @@ describe("traversal path", function() {
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 actualCode = transform(expectCode, {
@ -59,7 +59,7 @@ describe("traversal path", function() {
plugins: [
new Plugin({
visitor: {
ArrowFunctionExpression: function(path) {
ArrowFunctionExpression: function (path) {
path.get("body").replaceWith({
type: "BooleanLiteral",
value: true,
@ -73,7 +73,7 @@ describe("traversal path", function() {
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 actualCode = transform(expectCode, {
@ -81,7 +81,7 @@ describe("traversal path", function() {
plugins: [
new Plugin({
visitor: {
ForInStatement: function(path) {
ForInStatement: function (path) {
path.get("left").replaceWith({
type: "VariableDeclaration",
kind: "var",
@ -104,7 +104,7 @@ describe("traversal path", function() {
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 actualCode = transform(expectCode, {
@ -112,7 +112,7 @@ describe("traversal path", function() {
plugins: [
new Plugin({
visitor: {
ForInStatement: function(path) {
ForInStatement: function (path) {
path.get("left").replaceWith({
type: "Identifier",
name: "KEY",
@ -126,7 +126,7 @@ describe("traversal path", function() {
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 actualCode = transform(expectCode, {
@ -134,7 +134,7 @@ describe("traversal path", function() {
plugins: [
new Plugin({
visitor: {
ForStatement: function(path) {
ForStatement: function (path) {
path.get("init").replaceWith({
type: "VariableDeclaration",
kind: "var",
@ -157,7 +157,7 @@ describe("traversal path", function() {
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 actualCode = transform(expectCode, {
@ -165,7 +165,7 @@ describe("traversal path", function() {
plugins: [
new Plugin({
visitor: {
ForStatement: function(path) {
ForStatement: function (path) {
path.get("init").replaceWith({
type: "Identifier",
name: "KEY",

View File

@ -1,20 +1,20 @@
import * as babel from "../lib/index";
import path from "path";
describe("addon resolution", function() {
describe("addon resolution", function () {
const base = path.join(__dirname, "fixtures", "resolution");
let cwd;
beforeEach(function() {
beforeEach(function () {
cwd = process.cwd();
process.chdir(base);
});
afterEach(function() {
afterEach(function () {
process.chdir(cwd);
});
it("should find module: presets", function() {
it("should find module: presets", function () {
process.chdir("module-paths");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
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");
expect(() => {
@ -430,7 +430,7 @@ describe("addon resolution", function() {
}).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");
expect(() => {

View File

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

View File

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

View File

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

View File

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

View File

@ -6,24 +6,24 @@ import fs from "fs";
import path from "path";
import fixtures from "@babel/helper-fixtures";
describe("generation", function() {
it("completeness", function() {
Object.keys(t.VISITOR_KEYS).forEach(function(type) {
describe("generation", function () {
it("completeness", function () {
Object.keys(t.VISITOR_KEYS).forEach(function (type) {
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;
expect(t.VISITOR_KEYS[type]).toBeTruthy();
});
});
it("multiple sources", function() {
it("multiple sources", function () {
const sources = {
"a.js": "function hi (msg) { console.log(msg); }\n",
"b.js": "hi('hello');\n",
};
const parsed = Object.keys(sources).reduce(function(_parsed, filename) {
const parsed = Object.keys(sources).reduce(function (_parsed, filename) {
_parsed[filename] = parse(sources[filename], {
sourceFilename: filename,
});
@ -185,7 +185,7 @@ describe("generation", function() {
);
});
it("identifierName", function() {
it("identifierName", function () {
const code = "function foo() { bar; }\n";
const ast = parse(code, { filename: "inline" }).program;
@ -277,7 +277,7 @@ describe("generation", function() {
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 ast = parse(code, { filename: "a.js" }).program;
@ -306,8 +306,8 @@ describe("generation", function() {
});
});
describe("programmatic generation", function() {
it("should add parenthesis when NullishCoalescing is used along with ||", function() {
describe("programmatic generation", function () {
it("should add parenthesis when NullishCoalescing is used along with ||", function () {
// https://github.com/babel/babel/issues/10260
const nullishCoalesc = t.logicalExpression(
"??",
@ -318,7 +318,7 @@ describe("programmatic generation", function() {
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(
"??",
t.identifier("a"),
@ -332,7 +332,7 @@ describe("programmatic generation", function() {
expect(output).toBe(`a ?? (b && c && d)`);
});
it("numeric member expression", function() {
it("numeric member expression", function () {
// Should not generate `0.foo`
const mem = t.memberExpression(
t.numericLiteral(60702),
@ -341,7 +341,7 @@ describe("programmatic generation", function() {
new Function(generate(mem).code);
});
it("nested if statements needs block", function() {
it("nested if statements needs block", function () {
const ifStatement = t.ifStatement(
t.stringLiteral("top cond"),
t.whileStatement(
@ -358,7 +358,7 @@ describe("programmatic generation", function() {
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(
[],
[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(
[t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())],
null,
@ -384,7 +384,7 @@ describe("programmatic generation", function() {
}`);
});
it("flow object exact", function() {
it("flow object exact", function () {
const objectStatement = t.objectTypeAnnotation(
[t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())],
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(
[],
[
@ -419,8 +419,8 @@ describe("programmatic generation", function() {
}`);
});
describe("directives", function() {
it("preserves escapes", function() {
describe("directives", function () {
it("preserves escapes", function () {
const directive = t.directive(
t.directiveLiteral(String.raw`us\x65 strict`),
);
@ -429,7 +429,7 @@ describe("programmatic generation", function() {
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
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";`);
});
it("unescaped single quote", function() {
it("unescaped single quote", function () {
const directive = t.directive(t.directiveLiteral(String.raw`'\'\"`));
const output = generate(directive).code;
expect(output).toBe(String.raw`"'\'\"";`);
});
it("unescaped double quote", function() {
it("unescaped double quote", function () {
const directive = t.directive(t.directiveLiteral(String.raw`"\'\"`));
const output = generate(directive).code;
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`'"`));
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", () => {
const typeStatement = t.TSArrayType(
t.TSUnionType([
@ -496,8 +496,8 @@ describe("programmatic generation", function() {
});
});
describe("CodeGenerator", function() {
it("generate", function() {
describe("CodeGenerator", function () {
it("generate", function () {
const codeGen = new CodeGenerator(t.numericLiteral(123));
const code = codeGen.generate().code;
expect(parse(code).program.body[0].expression.value).toBe(123);
@ -506,15 +506,15 @@ describe("CodeGenerator", function() {
const suites = fixtures(`${__dirname}/fixtures`);
suites.forEach(function(testSuite) {
describe("generation/" + testSuite.title, function() {
testSuite.tests.forEach(function(task) {
suites.forEach(function (testSuite) {
describe("generation/" + testSuite.title, function () {
testSuite.tests.forEach(function (task) {
const testFn = task.disabled ? it.skip : it;
testFn(
task.title,
function() {
function () {
const expected = task.expect;
const actual = task.actual;
const actualCode = actual.code;

View File

@ -1,7 +1,7 @@
import explode from "@babel/helper-explode-assignable-expression";
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;
return {

View File

@ -9,10 +9,10 @@ type ElementState = {
pure: boolean, // true if the element can be marked with a #__PURE__ annotation
};
export default function(opts) {
export default function (opts) {
const visitor = {};
visitor.JSXNamespacedName = function(path) {
visitor.JSXNamespacedName = function (path) {
if (opts.throwIfNamespace) {
throw path.buildCodeFrameError(
`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(
"Spread children are not supported in React.",
);

View File

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

View File

@ -124,13 +124,13 @@ export function toComputedObjectFromClass(obj: Object): Object {
export function toClassObject(mutatorMap: Object): Object {
const objExpr = t.objectExpression([]);
Object.keys(mutatorMap).forEach(function(mutatorMapKey) {
Object.keys(mutatorMap).forEach(function (mutatorMapKey) {
const map = mutatorMap[mutatorMapKey];
const mapNode = t.objectExpression([]);
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];
if (key[0] === "_") return;
@ -148,7 +148,7 @@ export function toClassObject(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];
if (map.value) map.writable = t.booleanLiteral(true);
map.configurable = t.booleanLiteral(true);

View File

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

View File

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

View File

@ -150,7 +150,7 @@ function visit(node, name, scope) {
* @param {NodePath} param0
* @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
if (node.id) return;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,24 +2,24 @@ import chalk from "chalk";
import stripAnsi from "strip-ansi";
import highlight, { shouldHighlight, getChalk } from "..";
describe("@babel/highlight", function() {
describe("@babel/highlight", function () {
function stubColorSupport(supported) {
let originalSupportsColor;
beforeEach(function() {
beforeEach(function () {
originalSupportsColor = chalk.supportsColor;
chalk.supportsColor = supported;
});
afterEach(function() {
afterEach(function () {
chalk.supportsColor = originalSupportsColor;
});
}
describe("highlight", function() {
describe("when colors are supported", function() {
describe("highlight", function () {
describe("when colors are supported", function () {
stubColorSupport(true);
it("highlights code", function() {
it("highlights code", function () {
const code = "console.log('hi')";
const result = highlight(code);
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);
it("does not attempt to highlight code", function() {
it("does not attempt to highlight code", function () {
const code = "console.log('hi')";
const result = highlight(code);
const stripped = stripAnsi(result);
@ -39,8 +39,8 @@ describe("@babel/highlight", function() {
expect(result).toBe(code);
});
describe("and the forceColor option is passed", function() {
it("highlights the code anyway", function() {
describe("and the forceColor option is passed", function () {
it("highlights the code anyway", function () {
const code = "console.log('hi')";
const result = highlight(code, { forceColor: true });
const stripped = stripAnsi(result);
@ -51,42 +51,42 @@ describe("@babel/highlight", function() {
});
});
describe("shouldHighlight", function() {
describe("when colors are supported", function() {
describe("shouldHighlight", function () {
describe("when colors are supported", function () {
stubColorSupport(true);
it("returns true", function() {
it("returns true", function () {
expect(shouldHighlight({})).toBeTruthy();
});
});
describe("when colors are not supported", function() {
describe("when colors are not supported", function () {
stubColorSupport(false);
it("returns false", function() {
it("returns false", function () {
expect(shouldHighlight({})).toBeFalsy();
});
describe("and the forceColor option is passed", function() {
it("returns true", function() {
describe("and the forceColor option is passed", function () {
it("returns true", function () {
expect(shouldHighlight({ forceColor: true })).toBeTruthy();
});
});
});
});
describe("getChalk", function() {
describe("when colors are supported", function() {
describe("getChalk", function () {
describe("when colors are supported", function () {
stubColorSupport(true);
describe("when forceColor is not passed", function() {
it("returns a Chalk instance", function() {
describe("when forceColor is not passed", function () {
it("returns a Chalk instance", function () {
expect(getChalk({}).constructor).toBe(chalk.constructor);
});
});
describe("when forceColor is passed", function() {
it("returns a Chalk instance", function() {
describe("when forceColor is passed", function () {
it("returns a Chalk instance", function () {
expect(getChalk({ forceColor: true }).constructor).toBe(
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);
describe("when forceColor is not passed", function() {
it("returns a Chalk instance", function() {
describe("when forceColor is not passed", function () {
it("returns a Chalk instance", function () {
expect(getChalk({}).constructor).toBe(chalk.constructor);
});
});
describe("when forceColor is passed", function() {
it("returns a Chalk instance", function() {
describe("when forceColor is passed", function () {
it("returns a Chalk instance", function () {
expect(getChalk({ forceColor: true }).constructor).toBe(
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();
if (!code) return undefined;
@ -162,7 +162,7 @@ if (program.eval || program.print) {
let i = 0;
let ignoreNext = false;
args.some(function(arg, i2) {
args.some(function (arg, i2) {
if (ignoreNext) {
ignoreNext = false;
return;

View File

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

View File

@ -11,36 +11,36 @@ const fs = require("fs");
const fixtureLoc = path.join(__dirname, "fixtures");
const tmpLoc = path.join(__dirname, "tmp");
const fileFilter = function(x) {
const fileFilter = function (x) {
return x !== ".DS_Store";
};
const outputFileSync = function(filePath, data) {
const outputFileSync = function (filePath, data) {
makeDirSync(path.dirname(filePath));
fs.writeFileSync(filePath, data);
};
const readDir = function(loc, filter) {
const readDir = function (loc, filter) {
const files = {};
if (fs.existsSync(loc)) {
readdir(loc, filter).forEach(function(filename) {
readdir(loc, filter).forEach(function (filename) {
files[filename] = helper.readFile(path.join(loc, filename));
});
}
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.
outputFileSync(".babelrc", "{}");
Object.keys(files).forEach(function(filename) {
Object.keys(files).forEach(function (filename) {
const content = files[filename];
outputFileSync(filename, content);
});
};
const assertTest = function(stdout, stderr, opts) {
const assertTest = function (stdout, stderr, opts) {
const expectStderr = opts.stderr.trim();
stderr = stderr.trim();
@ -71,7 +71,7 @@ const assertTest = function(stdout, stderr, opts) {
if (opts.outFiles) {
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)) {
const expected = opts.outFiles[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);
});
}
};
const buildTest = function(binName, testName, opts) {
const buildTest = function (binName, testName, opts) {
const binLoc = path.join(__dirname, "../lib", binName);
return function(callback) {
return function (callback) {
saveInFiles(opts.inFiles);
let args = [binLoc];
args.push("--config-file", "../config.json");
@ -104,15 +104,15 @@ const buildTest = function(binName, testName, opts) {
let stderr = "";
let stdout = "";
spawn.stderr.on("data", function(chunk) {
spawn.stderr.on("data", function (chunk) {
stderr += chunk;
});
spawn.stdout.on("data", function(chunk) {
spawn.stdout.on("data", function (chunk) {
stdout += chunk;
});
spawn.on("close", function() {
spawn.on("close", function () {
let err;
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;
const suiteLoc = path.join(fixtureLoc, binName);
describe("bin/" + binName, function() {
describe("bin/" + binName, function () {
let cwd;
beforeEach(() => {
@ -161,7 +161,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) {
process.chdir(cwd);
});
fs.readdirSync(suiteLoc).forEach(function(testName) {
fs.readdirSync(suiteLoc).forEach(function (testName) {
if (testName[0] === ".") return;
const testLoc = path.join(suiteLoc, testName);
@ -173,7 +173,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) {
const optionsLoc = path.join(testLoc, "options.json");
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");
if (fs.existsSync(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.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_oTag); // start opening tag context
this.state.exprAllowed = false;
};
tt.jsxTagEnd.updateContext = function(prevType) {
tt.jsxTagEnd.updateContext = function (prevType) {
const out = this.state.context.pop();
if ((out === tc.j_oTag && prevType === tt.slash) || out === tc.j_cTag) {
this.state.context.pop();

View File

@ -41,7 +41,7 @@ export const types: {
// 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) {
this.state.exprAllowed = true;
return;
@ -55,7 +55,7 @@ tt.parenR.updateContext = tt.braceR.updateContext = function() {
this.state.exprAllowed = !out.isExpr;
};
tt.name.updateContext = function(prevType) {
tt.name.updateContext = function (prevType) {
let allowed = false;
if (prevType !== tt.dot) {
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.braceIsBlock(prevType) ? types.braceStatement : types.braceExpression,
);
this.state.exprAllowed = true;
};
tt.dollarBraceL.updateContext = function() {
tt.dollarBraceL.updateContext = function () {
this.state.context.push(types.templateQuasi);
this.state.exprAllowed = true;
};
tt.parenL.updateContext = function(prevType) {
tt.parenL.updateContext = function (prevType) {
const statementParens =
prevType === tt._if ||
prevType === tt._for ||
@ -99,11 +99,11 @@ tt.parenL.updateContext = function(prevType) {
this.state.exprAllowed = true;
};
tt.incDec.updateContext = function() {
tt.incDec.updateContext = function () {
// 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) {
// when function/class follows dot/questionDot, it is part of
// (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;
};
tt.backQuote.updateContext = function() {
tt.backQuote.updateContext = function () {
if (this.curContext() === types.template) {
this.state.context.pop();
} else {
@ -137,6 +137,6 @@ tt.backQuote.updateContext = function() {
this.state.exprAllowed = false;
};
tt.star.updateContext = function() {
tt.star.updateContext = function () {
this.state.exprAllowed = false;
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
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 ast = babel.transform(code, {

View File

@ -1,7 +1,7 @@
const babel = require("@babel/core");
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";';
const depStub = {
__esModule: false,
@ -11,7 +11,7 @@ test("Re-export doesn't overwrite __esModule flag", function() {
module: {
exports: {},
},
require: function(id) {
require: function (id) {
if (id === "./dep") return depStub;
return require(id);
},

View File

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

View File

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

View File

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

View File

@ -22,7 +22,7 @@ export default declare(api => {
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")) {
defineMap.push(mutatorMap, prop, null, file);
return false;

View File

@ -78,7 +78,7 @@ export default declare(api => {
let id;
// crawl up the ancestry looking for possible candidates for displayName inference
path.find(function(path) {
path.find(function (path) {
if (path.isAssignmentExpression()) {
id = path.node.left;
} 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)) {
path.node.value = t.jsxExpressionContainer(path.node.value);
}

View File

@ -78,7 +78,7 @@ function writeCoreJS({
}
const runtimeRoot = proposals ? "core-js" : "core-js-stable";
paths.forEach(function(corejsPath) {
paths.forEach(function (corejsPath) {
outputFile(
path.join(pkgDirname, runtimeRoot, `${corejsPath}.js`),
`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;
throw new Error(

View File

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

View File

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

View File

@ -2,6 +2,6 @@
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;
}

View File

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

View File

@ -8,7 +8,7 @@ export const defaultWebIncludes = [
"web.dom.iterable",
];
export default function(targets: Targets): null | string[] {
export default function (targets: Targets): null | string[] {
const targetNames = Object.keys(targets);
const isAnyTarget = !targetNames.length;
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.
Please remove the \`import '@babel/polyfill'\` call or use \`useBuiltIns: 'entry'\` instead.`;
export default function(
export default function (
{ types: t }: { types: Object },
{ include, exclude, polyfillTargets, debug }: InternalPluginOptions,
) {
@ -191,14 +191,14 @@ export default function(
pre({ path }: { path: NodePath }) {
this.polyfillsSet = new Set();
this.addImport = function(builtIn) {
this.addImport = function (builtIn) {
if (!this.polyfillsSet.has(builtIn)) {
this.polyfillsSet.add(builtIn);
createImport(path, builtIn);
}
};
this.addUnsupported = function(builtIn) {
this.addUnsupported = function (builtIn) {
const modules = Array.isArray(builtIn) ? builtIn : [builtIn];
for (const module of modules) {
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\`
and \`regenerator-runtime/runtime\` separately`;
export default function(
export default function (
_: any,
{ corejs, include, exclude, polyfillTargets, debug }: InternalPluginOptions,
) {
@ -115,7 +115,7 @@ export default function(
this.injectedPolyfills = new Set();
this.polyfillsSet = new Set();
this.replaceBySeparateModulesImport = function(path, modules) {
this.replaceBySeparateModulesImport = function (path, modules) {
for (const module of modules) {
this.polyfillsSet.add(module);
}

View File

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

View File

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

View File

@ -3,7 +3,7 @@
import { createImport } from "../../utils";
import type { NodePath } from "@babel/traverse";
export default function() {
export default function () {
return {
name: "regenerator-usage",
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 function getType(target: any): string {
return Object.prototype.toString
.call(target)
.slice(8, -1)
.toLowerCase();
return Object.prototype.toString.call(target).slice(8, -1).toLowerCase();
}
export function intersection<T>(

View File

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

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