-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathBundler.js
759 lines (635 loc) Β· 21.4 KB
/
Bundler.js
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
const fs = require('./utils/fs');
const Resolver = require('./Resolver');
const Parser = require('./Parser');
const WorkerFarm = require('./workerfarm/WorkerFarm');
const Path = require('path');
const Bundle = require('./Bundle');
const Watcher = require('./Watcher');
const FSCache = require('./FSCache');
const HMRServer = require('./HMRServer');
const Server = require('./Server');
const {EventEmitter} = require('events');
const logger = require('./Logger');
const PackagerRegistry = require('./packagers');
const localRequire = require('./utils/localRequire');
const config = require('./utils/config');
const loadEnv = require('./utils/env');
const PromiseQueue = require('./utils/PromiseQueue');
const installPackage = require('./utils/installPackage');
const bundleReport = require('./utils/bundleReport');
const prettifyTime = require('./utils/prettifyTime');
const getRootDir = require('./utils/getRootDir');
const glob = require('fast-glob');
/**
* The Bundler is the main entry point. It resolves and loads assets,
* creates the bundle tree, and manages the worker farm, cache, and file watcher.
*/
class Bundler extends EventEmitter {
constructor(entryFiles, options = {}) {
super();
this.entryFiles = this.normalizeEntries(entryFiles);
this.options = this.normalizeOptions(options);
this.resolver = new Resolver(this.options);
this.parser = new Parser(this.options);
this.packagers = new PackagerRegistry(this.options);
this.cache = this.options.cache ? new FSCache(this.options) : null;
this.delegate = options.delegate || {};
this.bundleLoaders = {};
this.addBundleLoader('wasm', {
browser: require.resolve('./builtins/loaders/browser/wasm-loader'),
node: require.resolve('./builtins/loaders/node/wasm-loader')
});
this.addBundleLoader('css', {
browser: require.resolve('./builtins/loaders/browser/css-loader'),
node: require.resolve('./builtins/loaders/node/css-loader')
});
this.addBundleLoader('js', {
browser: require.resolve('./builtins/loaders/browser/js-loader'),
node: require.resolve('./builtins/loaders/node/js-loader')
});
this.pending = false;
this.loadedAssets = new Map();
this.watchedAssets = new Map();
this.farm = null;
this.watcher = null;
this.hmr = null;
this.bundleHashes = null;
this.error = null;
this.buildQueue = new PromiseQueue(this.processAsset.bind(this));
this.rebuildTimeout = null;
logger.setOptions(this.options);
}
normalizeEntries(entryFiles) {
// Support passing a single file
if (entryFiles && !Array.isArray(entryFiles)) {
entryFiles = [entryFiles];
}
// If no entry files provided, resolve the entry point from the current directory.
if (!entryFiles || entryFiles.length === 0) {
entryFiles = [process.cwd()];
}
// Match files as globs
return entryFiles
.reduce((p, m) => p.concat(glob.sync(m)), [])
.map(f => Path.resolve(f));
}
normalizeOptions(options) {
const isProduction =
options.production || process.env.NODE_ENV === 'production';
const publicURL = options.publicUrl || options.publicURL || '/';
const watch =
typeof options.watch === 'boolean' ? options.watch : !isProduction;
const target = options.target || 'browser';
const hmr =
target === 'node'
? false
: typeof options.hmr === 'boolean'
? options.hmr
: watch;
const scopeHoist =
options.scopeHoist !== undefined ? options.scopeHoist : false;
return {
production: isProduction,
outDir: Path.resolve(options.outDir || 'dist'),
outFile: options.outFile || '',
publicURL: publicURL,
watch: watch,
cache: typeof options.cache === 'boolean' ? options.cache : true,
cacheDir: Path.resolve(options.cacheDir || '.cache'),
killWorkers:
typeof options.killWorkers === 'boolean' ? options.killWorkers : true,
minify:
typeof options.minify === 'boolean' ? options.minify : isProduction,
target: target,
hmr: hmr,
https: options.https || false,
logLevel: isNaN(options.logLevel) ? 3 : options.logLevel,
entryFiles: this.entryFiles,
hmrPort: options.hmrPort || 0,
rootDir: getRootDir(this.entryFiles),
sourceMaps:
(typeof options.sourceMaps === 'boolean' ? options.sourceMaps : true) &&
!scopeHoist,
hmrHostname:
options.hmrHostname ||
(options.target === 'electron' ? 'localhost' : ''),
detailedReport: options.detailedReport || false,
global: options.global,
autoinstall:
typeof options.autoinstall === 'boolean'
? options.autoinstall
: !isProduction,
scopeHoist: scopeHoist,
contentHash:
typeof options.contentHash === 'boolean'
? options.contentHash
: isProduction
};
}
addAssetType(extension, path) {
if (typeof path !== 'string') {
throw new Error('Asset type should be a module path.');
}
if (this.farm) {
throw new Error('Asset types must be added before bundling.');
}
this.parser.registerExtension(extension, path);
}
addPackager(type, packager) {
if (this.farm) {
throw new Error('Packagers must be added before bundling.');
}
this.packagers.add(type, packager);
}
addBundleLoader(type, paths) {
if (typeof paths === 'string') {
paths = {node: paths, browser: paths};
} else if (typeof paths !== 'object') {
throw new Error('Bundle loaders should be an object.');
}
for (const target in paths) {
if (target !== 'node' && target !== 'browser') {
throw new Error(`Unknown bundle loader target "${target}".`);
}
if (typeof paths[target] !== 'string') {
throw new Error('Bundle loader should be a string.');
}
}
if (this.farm) {
throw new Error('Bundle loaders must be added before bundling.');
}
this.bundleLoaders[type] = paths;
}
async loadPlugins() {
let relative = Path.join(this.options.rootDir, 'index');
let pkg = await config.load(relative, ['package.json']);
if (!pkg) {
return;
}
try {
let deps = Object.assign({}, pkg.dependencies, pkg.devDependencies);
for (let dep in deps) {
const pattern = /^(@.*\/)?parcel-plugin-.+/;
if (pattern.test(dep)) {
let plugin = await localRequire(dep, relative);
await plugin(this);
}
}
} catch (err) {
logger.warn(err);
}
}
async bundle() {
// If another bundle is already pending, wait for that one to finish and retry.
if (this.pending) {
return new Promise((resolve, reject) => {
this.once('buildEnd', () => {
this.bundle().then(resolve, reject);
});
});
}
let isInitialBundle = !this.entryAssets;
let startTime = Date.now();
this.pending = true;
this.error = null;
logger.clear();
logger.progress('Building...');
try {
// Start worker farm, watcher, etc. if needed
await this.start();
// Emit start event, after bundler is initialised
this.emit('buildStart', this.entryFiles);
// If this is the initial bundle, ensure the output directory exists, and resolve the main asset.
if (isInitialBundle) {
await fs.mkdirp(this.options.outDir);
this.entryAssets = new Set();
for (let entry of this.entryFiles) {
let asset = await this.resolveAsset(entry);
this.buildQueue.add(asset);
this.entryAssets.add(asset);
}
}
// Build the queued assets.
let loadedAssets = await this.buildQueue.run();
// The changed assets are any that don't have a parent bundle yet
// plus the ones that were in the build queue.
let changedAssets = [...this.findOrphanAssets(), ...loadedAssets];
// Invalidate bundles
for (let asset of this.loadedAssets.values()) {
asset.invalidateBundle();
}
logger.progress(`Producing bundles...`);
// Create a root bundle to hold all of the entry assets, and add them to the tree.
this.mainBundle = new Bundle();
for (let asset of this.entryAssets) {
this.createBundleTree(asset, this.mainBundle);
}
// If there is only one child bundle, replace the root with that bundle.
if (this.mainBundle.childBundles.size === 1) {
this.mainBundle = Array.from(this.mainBundle.childBundles)[0];
}
// Generate the final bundle names, and replace references in the built assets.
this.bundleNameMap = this.mainBundle.getBundleNameMap(
this.options.contentHash
);
for (let asset of changedAssets) {
asset.replaceBundleNames(this.bundleNameMap);
}
// Emit an HMR update if this is not the initial bundle.
if (this.hmr && !isInitialBundle) {
this.hmr.emitUpdate(changedAssets);
}
logger.progress(`Packaging...`);
// Package everything up
this.bundleHashes = await this.mainBundle.package(
this,
this.bundleHashes
);
// Unload any orphaned assets
this.unloadOrphanedAssets();
let buildTime = Date.now() - startTime;
let time = prettifyTime(buildTime);
logger.success(`Built in ${time}.`);
if (!this.watcher) {
bundleReport(this.mainBundle, this.options.detailedReport);
}
this.emit('bundled', this.mainBundle);
return this.mainBundle;
} catch (err) {
this.error = err;
logger.error(err);
this.emit('buildError', err);
if (this.hmr) {
this.hmr.emitError(err);
}
if (process.env.NODE_ENV === 'production') {
process.exitCode = 1;
} else if (process.env.NODE_ENV === 'test' && !this.hmr) {
throw err;
}
} finally {
this.pending = false;
this.emit('buildEnd');
// If not in watch mode, stop the worker farm so we don't keep the process running.
if (!this.watcher && this.options.killWorkers) {
this.stop();
}
}
}
async start() {
if (this.farm) {
return;
}
await this.loadPlugins();
if (!this.options.env) {
await loadEnv(Path.join(this.options.rootDir, 'index'));
this.options.env = process.env;
}
this.options.extensions = Object.assign({}, this.parser.extensions);
this.options.bundleLoaders = this.bundleLoaders;
if (this.options.watch) {
this.watcher = new Watcher();
// Wait for ready event for reliable testing on watcher
if (process.env.NODE_ENV === 'test' && !this.watcher.ready) {
await new Promise(resolve => this.watcher.once('ready', resolve));
}
this.watcher.on('change', this.onChange.bind(this));
}
if (this.options.hmr) {
this.hmr = new HMRServer();
this.options.hmrPort = await this.hmr.start(this.options);
}
this.farm = WorkerFarm.getShared(this.options);
}
async stop() {
if (this.watcher) {
this.watcher.stop();
}
if (this.hmr) {
this.hmr.stop();
}
// Watcher and hmr can cause workerfarm calls
// keep this as last to prevent unwanted errors
if (this.farm) {
await this.farm.end();
}
}
async getAsset(name, parent) {
let asset = await this.resolveAsset(name, parent);
this.buildQueue.add(asset);
await this.buildQueue.run();
return asset;
}
async resolveAsset(name, parent) {
let {path} = await this.resolver.resolve(name, parent);
return this.getLoadedAsset(path);
}
getLoadedAsset(path) {
if (this.loadedAssets.has(path)) {
return this.loadedAssets.get(path);
}
let asset = this.parser.getAsset(path, this.options);
this.loadedAssets.set(path, asset);
this.watch(path, asset);
return asset;
}
async watch(path, asset) {
if (!this.watcher) {
return;
}
path = await fs.realpath(path);
if (!this.watchedAssets.has(path)) {
this.watcher.watch(path);
this.watchedAssets.set(path, new Set());
}
this.watchedAssets.get(path).add(asset);
}
async unwatch(path, asset) {
path = await fs.realpath(path);
if (!this.watchedAssets.has(path)) {
return;
}
let watched = this.watchedAssets.get(path);
watched.delete(asset);
if (watched.size === 0) {
this.watchedAssets.delete(path);
this.watcher.unwatch(path);
}
}
async resolveDep(asset, dep, install = true) {
try {
if (dep.resolved) {
return this.getLoadedAsset(dep.resolved);
}
return await this.resolveAsset(dep.name, asset.name);
} catch (err) {
// If the dep is optional, return before we throw
if (dep.optional) {
return;
}
if (err.code === 'MODULE_NOT_FOUND') {
let isLocalFile = /^[/~.]/.test(dep.name);
let fromNodeModules = asset.name.includes(
`${Path.sep}node_modules${Path.sep}`
);
if (
!isLocalFile &&
!fromNodeModules &&
this.options.autoinstall &&
install
) {
return await this.installDep(asset, dep);
}
err.message = `Cannot resolve dependency '${dep.name}'`;
if (isLocalFile) {
const absPath = Path.resolve(Path.dirname(asset.name), dep.name);
err.message += ` at '${absPath}'`;
}
await this.throwDepError(asset, dep, err);
}
throw err;
}
}
async installDep(asset, dep) {
// Check if module exists, prevents useless installs
let resolved = await this.resolver.resolveModule(dep.name, asset.name);
// If the module resolved (i.e. wasn't a local file), but the module directory wasn't found, install it.
if (resolved.moduleName && !resolved.moduleDir) {
try {
await installPackage([resolved.moduleName], asset.name, {
saveDev: false
});
} catch (err) {
await this.throwDepError(asset, dep, err);
}
}
return await this.resolveDep(asset, dep, false);
}
async throwDepError(asset, dep, err) {
// Generate a code frame where the dependency was used
if (dep.loc) {
await asset.loadIfNeeded();
err.loc = dep.loc;
err = asset.generateErrorMessage(err);
}
err.fileName = asset.name;
throw err;
}
async processAsset(asset, isRebuild) {
if (isRebuild) {
asset.invalidate();
if (this.cache) {
this.cache.invalidate(asset.name);
}
}
await this.loadAsset(asset);
}
async loadAsset(asset) {
if (asset.processed) {
return;
}
if (!this.error) {
logger.progress(`Building ${asset.basename}...`);
}
// Mark the asset processed so we don't load it twice
asset.processed = true;
// First try the cache, otherwise load and compile in the background
asset.startTime = Date.now();
let processed = this.cache && (await this.cache.read(asset.name));
let cacheMiss = false;
if (!processed || asset.shouldInvalidate(processed.cacheData)) {
processed = await this.farm.run(asset.name);
cacheMiss = true;
}
asset.endTime = Date.now();
asset.buildTime = asset.endTime - asset.startTime;
asset.id = processed.id;
asset.generated = processed.generated;
asset.hash = processed.hash;
asset.cacheData = processed.cacheData;
// Call the delegate to get implicit dependencies
let dependencies = processed.dependencies;
if (this.delegate.getImplicitDependencies) {
let implicitDeps = await this.delegate.getImplicitDependencies(asset);
if (implicitDeps) {
dependencies = dependencies.concat(implicitDeps);
}
}
// Resolve and load asset dependencies
let assetDeps = await Promise.all(
dependencies.map(async dep => {
if (dep.includedInParent) {
// This dependency is already included in the parent's generated output,
// so no need to load it. We map the name back to the parent asset so
// that changing it triggers a recompile of the parent.
this.watch(dep.name, asset);
} else {
dep.parent = asset.name;
let assetDep = await this.resolveDep(asset, dep);
if (assetDep) {
await this.loadAsset(assetDep);
}
return assetDep;
}
})
);
// Store resolved assets in their original order
dependencies.forEach((dep, i) => {
asset.dependencies.set(dep.name, dep);
let assetDep = assetDeps[i];
if (assetDep) {
asset.depAssets.set(dep, assetDep);
dep.resolved = assetDep.name;
}
});
if (this.cache && cacheMiss) {
this.cache.write(asset.name, processed);
}
}
createBundleTree(asset, bundle, dep, parentBundles = new Set()) {
if (dep) {
asset.parentDeps.add(dep);
}
if (asset.parentBundle && !bundle.isolated) {
// If the asset is already in a bundle, it is shared. Move it to the lowest common ancestor.
if (asset.parentBundle !== bundle) {
let commonBundle = bundle.findCommonAncestor(asset.parentBundle);
// If the common bundle's type matches the asset's, move the asset to the common bundle.
// Otherwise, proceed with adding the asset to the new bundle below.
if (asset.parentBundle.type === commonBundle.type) {
this.moveAssetToBundle(asset, commonBundle);
return;
}
} else {
return;
}
// Detect circular bundles
if (parentBundles.has(asset.parentBundle)) {
return;
}
}
// Skip this asset if it's already in the bundle.
// Happens when circular dependencies are placed in an isolated bundle (e.g. a worker).
if (bundle.isolated && bundle.assets.has(asset)) {
return;
}
let isEntryAsset =
asset.parentBundle && asset.parentBundle.entryAsset === asset;
if ((dep && dep.dynamic) || !bundle.type) {
// If the asset is already the entry asset of a bundle, don't create a duplicate.
if (isEntryAsset) {
return;
}
// Create a new bundle for dynamic imports
bundle = bundle.createChildBundle(asset, dep);
} else if (asset.type && !this.packagers.has(asset.type)) {
// If the asset is already the entry asset of a bundle, don't create a duplicate.
if (isEntryAsset) {
return;
}
// No packager is available for this asset type. Create a new bundle with only this asset.
bundle.createSiblingBundle(asset);
} else {
// Add the asset to the common bundle of the asset's type
bundle.getSiblingBundle(asset.type).addAsset(asset);
}
// If the asset generated a representation for the parent bundle type, also add it there
if (asset.generated[bundle.type] != null) {
bundle.addAsset(asset);
}
// Add the asset to sibling bundles for each generated type
if (asset.type && asset.generated[asset.type]) {
for (let t in asset.generated) {
if (asset.generated[t]) {
bundle.getSiblingBundle(t).addAsset(asset);
}
}
}
asset.parentBundle = bundle;
parentBundles.add(bundle);
for (let [dep, assetDep] of asset.depAssets) {
this.createBundleTree(assetDep, bundle, dep, parentBundles);
}
parentBundles.delete(bundle);
return bundle;
}
moveAssetToBundle(asset, commonBundle) {
// Never move the entry asset of a bundle, as it was explicitly requested to be placed in a separate bundle.
if (
asset.parentBundle.entryAsset === asset ||
asset.parentBundle === commonBundle
) {
return;
}
for (let bundle of Array.from(asset.bundles)) {
if (!bundle.isolated) {
bundle.removeAsset(asset);
}
commonBundle.getSiblingBundle(bundle.type).addAsset(asset);
}
let oldBundle = asset.parentBundle;
asset.parentBundle = commonBundle;
// Move all dependencies as well
for (let child of asset.depAssets.values()) {
if (child.parentBundle === oldBundle) {
this.moveAssetToBundle(child, commonBundle);
}
}
}
*findOrphanAssets() {
for (let asset of this.loadedAssets.values()) {
if (!asset.parentBundle) {
yield asset;
}
}
}
unloadOrphanedAssets() {
for (let asset of this.findOrphanAssets()) {
this.unloadAsset(asset);
}
}
unloadAsset(asset) {
this.loadedAssets.delete(asset.name);
if (this.watcher) {
this.unwatch(asset.name, asset);
// Unwatch all included dependencies that map to this asset
for (let dep of asset.dependencies.values()) {
if (dep.includedInParent) {
this.unwatch(dep.name, asset);
}
}
}
}
async onChange(path) {
let assets = this.watchedAssets.get(path);
if (!assets || !assets.size) {
return;
}
logger.clear();
logger.progress(`Building ${Path.basename(path)}...`);
// Add the asset to the rebuild queue, and reset the timeout.
for (let asset of assets) {
this.buildQueue.add(asset, true);
}
clearTimeout(this.rebuildTimeout);
this.rebuildTimeout = setTimeout(async () => {
await this.bundle();
}, 100);
}
middleware() {
this.bundle();
return Server.middleware(this);
}
async serve(port = 1234, https = false) {
this.server = await Server.serve(this, port, https);
try {
await this.bundle();
} catch (e) {
// ignore: server can still work with errored bundler
}
return this.server;
}
}
module.exports = Bundler;
Bundler.Asset = require('./Asset');
Bundler.Packager = require('./packagers/Packager');