forked from babel/babel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gulpfile.mjs
712 lines (643 loc) · 21.1 KB
/
Gulpfile.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
import path from "path";
import fs from "fs";
import { cpus } from "os";
import { createRequire } from "module";
import { fileURLToPath } from "url";
import plumber from "gulp-plumber";
import through from "through2";
import chalk from "chalk";
import filter from "gulp-filter";
import gulp from "gulp";
import { rollup } from "rollup";
import { babel as rollupBabel } from "@rollup/plugin-babel";
import rollupCommonJs from "@rollup/plugin-commonjs";
import rollupJson from "@rollup/plugin-json";
import rollupPolyfillNode from "rollup-plugin-polyfill-node";
import rollupNodeResolve from "@rollup/plugin-node-resolve";
import rollupReplace from "@rollup/plugin-replace";
import { terser as rollupTerser } from "rollup-plugin-terser";
import rollupDts from "rollup-plugin-dts";
import { Worker as JestWorker } from "jest-worker";
import glob from "glob";
import { resolve as importMetaResolve } from "import-meta-resolve";
import rollupBabelSource from "./scripts/rollup-plugin-babel-source.js";
import formatCode from "./scripts/utils/formatCode.js";
import { log } from "./scripts/utils/logger.cjs";
let USE_ESM = false;
try {
const type = fs
.readFileSync(new URL(".module-type", import.meta.url), "utf-8")
.trim();
USE_ESM = type === "module";
} catch {}
const require = createRequire(import.meta.url);
const monorepoRoot = path.dirname(fileURLToPath(import.meta.url));
const defaultPackagesGlob = "./@(codemods|packages|eslint)/*";
const defaultSourcesGlob = `${defaultPackagesGlob}/src/**/{*.js,*.cjs,!(*.d).ts}`;
const babelStandalonePluginConfigGlob =
"./packages/babel-standalone/scripts/pluginConfig.json";
const buildTypingsWatchGlob = [
"./packages/babel-types/lib/definitions/**/*.js",
"./packages/babel-types/scripts/generators/*.js",
];
/**
* map source code path to the generated artifacts path
* @example
* mapSrcToLib("packages/babel-core/src/index.js")
* // returns "packages/babel-core/lib/index.js"
* @example
* mapSrcToLib("packages/babel-template/src/index.ts")
* // returns "packages/babel-template/lib/index.js"
* @example
* mapSrcToLib("packages/babel-template/src/index.d.ts")
* // returns "packages/babel-template/lib/index.d.ts"
* @param {string} srcPath
* @returns {string}
*/
function mapSrcToLib(srcPath) {
const parts = srcPath.replace(/(?<!\.d)\.ts$/, ".js").split("/");
parts[2] = "lib";
return parts.join("/");
}
function mapToDts(packageName) {
return packageName.replace(
/(?<=\\|\/|^)(packages|eslint|codemods)(?=\\|\/)/,
"dts/$1"
);
}
function getIndexFromPackage(name) {
try {
fs.statSync(`./${name}/src/index.ts`);
return `${name}/src/index.ts`;
} catch {
return `${name}/src/index.js`;
}
}
function errorsLogger() {
return plumber({
errorHandler(err) {
log(err.stack);
},
});
}
function rename(fn) {
return through.obj(function (file, enc, callback) {
file.path = fn(file);
callback(null, file);
});
}
/**
* @param {string} generator
* @param {string} pkg
* @param {string} filename
* @param {string} message
*/
function generateHelpers(generator, dest, filename, message) {
const stream = gulp
.src(".", { base: monorepoRoot })
.pipe(errorsLogger())
.pipe(
through.obj(async (file, enc, callback) => {
const { default: generateCode } = await import(generator);
file.path = filename;
file.contents = Buffer.from(
formatCode(await generateCode(filename), dest + file.path)
);
log(`${chalk.green("✔")} Generated ${message}`);
callback(null, file);
})
)
.pipe(gulp.dest(dest, { mode: 0o644 }));
return finish(stream);
}
/**
*
* @typedef {("asserts" | "builders" | "constants" | "validators")} TypesHelperKind
* @param {TypesHelperKind} helperKind
* @param {string} filename
*/
async function generateTypeHelpers(helperKind, filename = "index.ts") {
return generateHelpers(
`./packages/babel-types/scripts/generators/${helperKind}.js`,
`./packages/babel-types/src/${helperKind}/generated/`,
filename,
`@babel/types -> ${helperKind}`
);
}
/**
*
* @typedef {("asserts" | "validators")} TraverseHelperKind
* @param {TraverseHelperKind} helperKind
*/
function generateTraverseHelpers(helperKind) {
return generateHelpers(
`./packages/babel-traverse/scripts/generators/${helperKind}.js`,
`./packages/babel-traverse/src/path/generated/`,
`${helperKind}.ts`,
`@babel/traverse -> ${helperKind}`
);
}
async function generateRuntimeHelpers() {
await generateHelpers(
`./packages/babel-helpers/scripts/generate-regenerator-runtime.js`,
`./packages/babel-helpers/src/helpers`,
"regeneratorRuntime.js",
"@babel/helpers -> regeneratorRuntime"
);
return generateHelpers(
`./packages/babel-helpers/scripts/generate-helpers.js`,
`./packages/babel-helpers/src/`,
"helpers-generated.ts",
"@babel/helpers"
);
}
function generateStandalone() {
const dest = "./packages/babel-standalone/src/generated/";
return gulp
.src(babelStandalonePluginConfigGlob, { base: monorepoRoot })
.pipe(
through.obj((file, enc, callback) => {
log("Generating @babel/standalone files");
const pluginConfig = JSON.parse(file.contents);
let imports = "";
let list = "";
let allList = "";
for (const plugin of pluginConfig) {
const camelPlugin = plugin.replace(/-[a-z]/g, c =>
c[1].toUpperCase()
);
imports += `import ${camelPlugin} from "@babel/plugin-${plugin}";`;
list += `${camelPlugin},`;
allList += `"${plugin}": ${camelPlugin},`;
}
const fileContents = `/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'yarn gulp generate-standalone'
*/
${imports}
export {${list}};
export const all: { [k: string]: any } = {${allList}};`;
file.path = "plugins.ts";
file.contents = Buffer.from(formatCode(fileContents, dest));
callback(null, file);
})
)
.pipe(gulp.dest(dest));
}
function finish(stream) {
return new Promise((resolve, reject) => {
stream.on("end", resolve);
stream.on("finish", resolve);
stream.on("error", reject);
});
}
function getFiles(glob, { include, exclude }) {
let stream = gulp.src(glob, { base: monorepoRoot });
if (exclude) {
const filters = exclude.map(p => `!**/${p}/**`);
filters.unshift("**");
stream = stream.pipe(filter(filters));
}
if (include) {
const filters = include.map(p => `**/${p}/**`);
stream = stream.pipe(filter(filters));
}
return stream;
}
function createWorker(useWorker) {
const numWorkers = Math.ceil(Math.max(cpus().length, 1) / 2) - 1;
if (numWorkers === 0 || !useWorker) {
return require("./babel-worker.cjs");
}
const worker = new JestWorker(require.resolve("./babel-worker.cjs"), {
numWorkers,
exposedMethods: ["transform"],
});
worker.getStdout().pipe(process.stdout);
worker.getStderr().pipe(process.stderr);
return worker;
}
async function buildBabel(useWorker, ignore = []) {
const enableSourceMap = !process.env.IS_PUBLISH;
const worker = createWorker(useWorker);
const files = await new Promise((resolve, reject) => {
glob(
defaultSourcesGlob,
{
ignore: ignore.map(p => `./${p.src}/**`),
},
(err, files) => {
if (err) reject(err);
resolve(files);
}
);
});
const promises = [];
for (const file of files) {
// @example ./packages/babel-parser/src/index.js
const dest = "./" + mapSrcToLib(file.slice(2));
promises.push(
worker.transform(file, dest, {
sourceMaps: enableSourceMap && !file.endsWith(".d.ts"),
})
);
}
return Promise.allSettled(promises)
.then(results => {
results.forEach(result => {
if (result.status == "rejected") {
if (process.env.WATCH_SKIP_BUILD) {
console.error(result.reason);
} else {
throw result.reason;
}
}
});
})
.finally(() => {
if (worker.end !== undefined) {
worker.end();
}
});
}
/**
* Resolve a nested dependency starting from the given file
*/
function resolveChain(baseUrl, ...packages) {
const require = createRequire(baseUrl);
return packages.reduce(
(base, pkg) =>
path.dirname(require.resolve(pkg + "/package.json", { paths: [base] })),
path.dirname(fileURLToPath(baseUrl))
);
}
// If this build is part of a pull request, include the pull request number in
// the version number.
let versionSuffix = "";
if (process.env.CIRCLE_PR_NUMBER) {
versionSuffix = "+pr." + process.env.CIRCLE_PR_NUMBER;
}
const babelVersion =
require("./packages/babel-core/package.json").version + versionSuffix;
function buildRollup(packages, targetBrowsers) {
const sourcemap = process.env.NODE_ENV === "production";
return Promise.all(
packages.map(
async ({ src, format, dest, name, filename, envName = "rollup" }) => {
const pkgJSON = require("./" + src + "/package.json");
const version = pkgJSON.version + versionSuffix;
const { dependencies = {}, peerDependencies = {} } = pkgJSON;
const external = Object.keys(dependencies).concat(
Object.keys(peerDependencies)
);
const input = getIndexFromPackage(src);
log(`Compiling '${chalk.cyan(input)}' with rollup ...`);
const bundle = await rollup({
input,
external,
onwarn(warning, warn) {
switch (warning.code) {
case "CIRCULAR_DEPENDENCY":
case "SOURCEMAP_ERROR": // Rollup warns about the babel-polyfills source maps
return;
case "UNUSED_EXTERNAL_IMPORT":
warn(warning);
return;
case "MISSING_EXPORT":
// Rollup warns about using babel.default at
// https://github.com/babel/babel-polyfills/blob/4ac92be5b70b13e3d8a34614d8ecd900eb3f40e4/packages/babel-helper-define-polyfill-provider/src/types.js#L5
// We can safely ignore this warning, and let Rollup replace it with undefined.
if (
warning.exporter === "packages/babel-core/src/index.ts" &&
warning.missing === "default" &&
[
"@babel/helper-define-polyfill-provider",
"babel-plugin-polyfill-corejs2",
"babel-plugin-polyfill-corejs3",
"babel-plugin-polyfill-regenerator",
].some(pkg => warning.importer.includes(pkg))
) {
return;
}
}
// We use console.warn here since it prints more info than just "warn",
// in case we want to stop throwing for a specific message.
console.warn(warning);
// https://github.com/babel/babel/pull/12011#discussion_r540434534
throw new Error("Rollup aborted due to warnings above");
},
plugins: [
rollupBabelSource(),
rollupReplace({
preventAssignment: true,
values: {
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
BABEL_VERSION: JSON.stringify(babelVersion),
VERSION: JSON.stringify(version),
},
}),
rollupCommonJs({
include: [
/node_modules/,
"packages/babel-runtime/regenerator/**",
"packages/babel-runtime/helpers/*.js",
"packages/babel-preset-env/data/*.js",
// Rollup doesn't read export maps, so it loads the cjs fallback
"packages/babel-compat-data/*.js",
"packages/*/src/**/*.cjs",
],
dynamicRequireTargets: [
// https://github.com/mathiasbynens/regexpu-core/blob/ffd8fff2e31f4597f6fdfee75d5ac1c5c8111ec3/rewrite-pattern.js#L48
resolveChain(
import.meta.url,
"./packages/babel-helper-create-regexp-features-plugin",
"regexpu-core",
"regenerate-unicode-properties"
) + "/**/*.js",
],
// Never delegate to the native require()
ignoreDynamicRequires: false,
// Align with the Node.js behavior
defaultIsModuleExports: true,
}),
rollupBabel({
envName,
babelrc: false,
babelHelpers: "bundled",
extends: "./babel.config.js",
extensions: [".ts", ".js", ".mjs", ".cjs"],
ignore: ["packages/babel-runtime/helpers/*.js"],
}),
rollupNodeResolve({
extensions: [".ts", ".js", ".mjs", ".cjs", ".json"],
browser: targetBrowsers,
exportConditions: targetBrowsers ? ["browser"] : [],
// It needs to be set to 'false' when using rollupNodePolyfills
// https://github.com/rollup/plugins/issues/772
preferBuiltins: !targetBrowsers,
}),
rollupJson(),
targetBrowsers &&
rollupPolyfillNode({
sourceMap: sourcemap,
include: "**/*.{js,cjs,ts}",
}),
].filter(Boolean),
});
const outputFile = path.join(src, dest, filename || "index.js");
await bundle.write({
file: outputFile,
format,
name,
sourcemap: sourcemap,
exports: "named",
});
if (!process.env.IS_PUBLISH) {
log(
chalk.yellow(
`Skipped minification of '${chalk.cyan(
outputFile
)}' because not publishing`
)
);
return undefined;
}
log(`Minifying '${chalk.cyan(outputFile)}'...`);
await bundle.write({
file: outputFile.replace(/\.js$/, ".min.js"),
format,
name,
sourcemap: sourcemap,
exports: "named",
plugins: [
rollupTerser({
// workaround https://bugs.webkit.org/show_bug.cgi?id=212725
output: {
ascii_only: true,
},
numWorkers: process.env.CIRCLECI ? 1 : undefined,
}),
],
});
}
)
);
}
function buildRollupDts(packages) {
const sourcemap = process.env.NODE_ENV === "production";
return Promise.all(
packages.map(async packageName => {
const input = `${mapToDts(packageName)}/src/index.d.ts`;
const output = `${packageName}/lib/index.d.ts`;
log(`Bundling '${chalk.cyan(output)}' with rollup ...`);
const bundle = await rollup({
input,
plugins: [rollupDts()],
onwarn(warning, warn) {
if (warning.code !== "CIRCULAR_DEPENDENCY") warn(warning);
},
});
await bundle.write({
file: output,
format: "es",
sourcemap: sourcemap,
exports: "named",
});
})
);
}
function copyDts(packages) {
return getFiles(`${defaultPackagesGlob}/src/**/*.d.ts`, { include: packages })
.pipe(rename(file => path.resolve(file.base, mapToDts(file.relative))))
.pipe(gulp.dest(monorepoRoot));
}
const libBundles = [
"packages/babel-parser",
"packages/babel-plugin-proposal-destructuring-private",
"packages/babel-plugin-proposal-object-rest-spread",
"packages/babel-plugin-proposal-optional-chaining",
"packages/babel-preset-react",
"packages/babel-plugin-transform-destructuring",
"packages/babel-preset-typescript",
"packages/babel-helper-member-expression-to-functions",
"packages/babel-plugin-bugfix-v8-spread-parameters-in-optional-chaining",
"packages/babel-plugin-bugfix-safari-id-destructuring-collision-in-function-expression",
].map(src => ({
src,
format: USE_ESM ? "esm" : "cjs",
dest: "lib",
}));
const cjsBundles = [
// This is used by @babel/register and @babel/eslint-parser
{ src: "packages/babel-parser" },
];
const dtsBundles = ["packages/babel-types"];
const standaloneBundle = [
{
src: "packages/babel-standalone",
format: "umd",
name: "Babel",
filename: "babel.js",
dest: "",
version: babelVersion,
envName: "standalone",
},
];
gulp.task("generate-type-helpers", () => {
log("Generating @babel/types and @babel/traverse dynamic functions");
return Promise.all([
generateTypeHelpers("asserts"),
generateTypeHelpers("builders"),
generateTypeHelpers("builders", "uppercase.js"),
generateTypeHelpers("constants"),
generateTypeHelpers("validators"),
generateTypeHelpers("ast-types"),
generateTraverseHelpers("asserts"),
generateTraverseHelpers("validators"),
]);
});
gulp.task("generate-runtime-helpers", () => {
log("Generating @babel/helpers runtime helpers");
return generateRuntimeHelpers();
});
gulp.task("generate-standalone", () => generateStandalone());
gulp.task("build-rollup", () => buildRollup(libBundles));
gulp.task("rollup-babel-standalone", () => buildRollup(standaloneBundle, true));
gulp.task(
"build-babel-standalone",
gulp.series("generate-standalone", "rollup-babel-standalone")
);
gulp.task("copy-dts", () => copyDts(dtsBundles));
gulp.task(
"bundle-dts",
gulp.series("copy-dts", () => buildRollupDts(dtsBundles))
);
gulp.task("build-babel", () => buildBabel(true, /* exclude */ libBundles));
gulp.task("build-vendor", async () => {
const input = fileURLToPath(
await importMetaResolve("import-meta-resolve", import.meta.url)
);
const output = "./packages/babel-core/src/vendor/import-meta-resolve.js";
const bundle = await rollup({
input,
onwarn(warning, warn) {
if (warning.code === "CIRCULAR_DEPENDENCY") return;
warn(warning);
},
plugins: [
rollupCommonJs({ defaultIsModuleExports: true }),
rollupNodeResolve({
extensions: [".js", ".mjs", ".cjs", ".json"],
preferBuiltins: true,
}),
],
});
await bundle.write({
file: output,
format: "es",
sourcemap: false,
exports: "named",
banner: String.raw`
/****************************************************************************\
* NOTE FROM BABEL AUTHORS *
* This file is inlined from https://github.com/wooorm/import-meta-resolve, *
* because we need to compile it to CommonJS. *
\****************************************************************************/
/*
${fs.readFileSync(path.join(path.dirname(input), "license"), "utf8")}*/
`,
});
fs.writeFileSync(
output.replace(".js", ".d.ts"),
`export function resolve(specifier: string, parent: string): Promise<string>;`
);
});
gulp.task("build-cjs-bundles", () => {
if (!USE_ESM) {
log(
chalk.yellow(
"Skipping CJS-compat bundles for ESM-based builds, because not compiling to ESM"
)
);
return Promise.resolve();
}
return Promise.all(
cjsBundles.map(async ({ src, external = [] }) => {
const input = `./${src}/lib/index.js`;
const output = `./${src}/lib/index.cjs`;
const bundle = await rollup({
input,
external,
onwarn(warning, warn) {
if (warning.code === "CIRCULAR_DEPENDENCY") return;
warn(warning);
},
plugins: [
rollupCommonJs({ defaultIsModuleExports: true }),
rollupNodeResolve({
extensions: [".js", ".mjs", ".cjs", ".json"],
preferBuiltins: true,
}),
],
});
await bundle.write({
file: output,
format: "cjs",
sourcemap: false,
});
})
);
});
gulp.task(
"build",
gulp.series(
"build-vendor",
gulp.parallel("build-rollup", "build-babel"),
gulp.parallel("generate-type-helpers", "generate-runtime-helpers"),
// rebuild @babel/types and @babel/helpers since
// type-helpers and generated helpers may be changed
"build-babel",
gulp.parallel("generate-standalone", "build-cjs-bundles")
)
);
gulp.task("default", gulp.series("build"));
// First build on worker processes for compilation speed
gulp.task("build-no-bundle", () => buildBabel(true));
// Incremental builds take place in main process
gulp.task("build-no-bundle-watch", () => buildBabel(false));
gulp.task(
"build-dev",
gulp.series(
"build-vendor",
"build-no-bundle",
gulp.parallel(
"generate-standalone",
"generate-runtime-helpers",
gulp.series(
"generate-type-helpers",
// rebuild @babel/types since type-helpers may be changed
"build-no-bundle",
"build-cjs-bundles"
)
)
)
);
function watch() {
gulp.watch(defaultSourcesGlob, gulp.task("build-no-bundle-watch"));
gulp.watch(babelStandalonePluginConfigGlob, gulp.task("generate-standalone"));
gulp.watch(buildTypingsWatchGlob, gulp.task("generate-type-helpers"));
gulp.watch(
"./packages/babel-helpers/src/helpers/*.js",
gulp.task("generate-runtime-helpers")
);
if (USE_ESM) {
gulp.watch(
cjsBundles.map(({ src }) => `./${src}/lib/**.js`),
gulp.task("build-cjs-bundles")
);
}
}
gulp.task(
"watch",
process.env.WATCH_SKIP_BUILD ? watch : gulp.series("build-dev", watch)
);