-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
834 lines (662 loc) · 19.6 KB
/
index.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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
var builtins = require('browserify/lib/builtins');
var fs = require('fs');
var path = require('path');
var forEach = require('lodash/collection/forEach');
var sum = require('lodash/collection/sum');
var reduce = require('lodash/collection/reduce');
var pluck = require('lodash/collection/pluck');
var union = require('lodash/array/union');
var last = require('lodash/array/last');
var pull = require('lodash/array/pull');
var assign = require('lodash/object/assign');
var encodeBits = require('./lib/encode-bits');
var md5 = require('./lib/md5');
var commondir = require('commondir');
var Module = require('./lib/module');
var inherits = require('inherits');
var Transform = require('readable-stream').Transform;
var Writable = require('readable-stream').Writable;
var Readable = require('readable-stream').Readable;
var File = require('vinyl');
inherits(Dynapack, Transform);
function Dynapack(opts) {
if (!(this instanceof Dynapack)) {
return new Dynapack(opts);
}
Transform.call(this, {objectMode: true});
/**
* A mapping between module path and loaded and parsed modules. Once in this
* object a module is ready to be bundled (but may be replaced before bundling
* if the same module is visited in another dependency tree.
*/
this.modules = {};
/**
* For reusing module sources. These are the modification times for loaded
* modules.
*/
this._mtimes = {};
/**
* An array of paths to entry modules. Entries are special because they can be
* any module in the dependency graph. The entryNames are derived from the entry
* path.
*/
this.entryPaths = [];
this.entryNames = [];
this.opts = assign(
{
builtins: builtins
},
opts
);
/**
* When a new entry is given to dynapack (or an old one is replaced), we need
* to know which modules come from its dependency tree. When the entire tree
* has been discovered, processing of the entry is considered finished.
*
* We need to following dependencies on their way through
* the stream from dep id to transformed source. Every time we
* encounter a dependency, tag it in a processing hash. When
* the hash is empty, we are done processing dependencies.
*/
this._loading = {};
this._initDeps();
this._initMods();
/**
* Dynapack pushes deps to deps through stream, which pushes filepaths
* to the default loader, which sends sources to dynapack.
*/
this._deps.pipe(this._mods);
return this;
}
Dynapack.prototype.traverse = function(iterator) {
var visited = [];
var modules = this.modules;
forEach(this.entryPaths, visitModule);
function visitModule(id) {
var module = modules[id];
if (!module) {
throw new Error('TODO: What if module does not exist on traverse?');
}
else {
visited.push(module);
iterator(visited);
}
module.deps.set.forEach(function(depPath) {
var dep = modules[depPath];
if (!dep || visited.indexOf(dep) < 0) {
visitModule(depPath);
}
});
visited.pop();
}
};
/**
* Returns javascript for bundle, which includes module sources, and
* pulled in roots.
*/
Dynapack.prototype.renderBundle = function(bundle) {
var pack = this;
var newRoots = {};
forEach(pack.getBundleNewRoots(bundle), function(rootBundles, rootPath) {
newRoots[pack.ids[rootPath]] = pluck(rootBundles, 'name');
});
if (!pack.bundleHeader) {
pack.bundleHeader = fs.readFileSync(__dirname + '/browser/bundle.js');
}
return (
pack.bundleHeader + '("' + bundle.name + '", [{' +
bundle.modules.map(function(path) {
return (
'"' + pack.ids[path] + '":' +
pack.renderModule(path)
);
}).join(',') + '},' +
JSON.stringify(newRoots) +
']);'
);
};
/**
* @param {String} entryPath Module path; it better be from dynapack.entries sucka.
*/
Dynapack.prototype.renderEntry = function(entryPath, bundles) {
if (!this._entryHeader) {
this._entryHeader = fs.readFileSync(__dirname + '/browser/entry.min.js');
}
return (
this._entryHeader +
'("' + this.ids[entryPath] + '",' +
JSON.stringify(
pluck(bundles, 'name')
) + ',' +
JSON.stringify({
prefix: this.opts.prefix || '/'
}) +
');'
);
};
Dynapack.prototype.entryScripts = function(entryName) {
var index = this.entryNames.indexOf(entryName);
var entryPath = this.entryPaths[index];
var entryBundles = this.requiredBundles(entryPath);
var prefix = this.opts.prefix || '/';
var scripts = '';
//var scripts = '<script async src="' + prefix + entryName + '.entry.js"></script>';
entryBundles.forEach(function(bundle) {
scripts += '<script async src="' + prefix + bundle.name + '"></script>';
});
return scripts;
};
Dynapack.prototype.bundle = function(opts) {
var pack = this;
var roots = {};
var bundle;
var bundles;
var index = 0;
var cwd = process.cwd();
// Graph metadata all in one place.
var graph = {
modules: {}, // maps source ids to input ids (i.e. filenames)
bundles: {}, // maps bundle ids to module id arrays.
entries: {} // maps entry ids to bundle id arrays.
};
// Consistent id'ing of modules uses its relative path. Watch out
// for dependencies that go outside project directory.
var basePath = commondir(
Object.keys(pack.modules)
);
if (cwd.indexOf(basePath) === 0 && cwd.length > basePath.length) {
// basePath is a parent directory of cwd
console.warn(
'The directory common to all modules in the dependency',
'graph is', basePath, ', but the current working directory',
'is', cwd + '.', 'If you are working from the root of your',
'project directory, this means your bundle names may vary',
'depending on your development machine, which is bad. Maybe',
'a global module is being required somehow?'
);
}
pack.traverse(function(visited) {
var module = last(visited);
var root;
var parent;
if (module.index === undefined) {
module.index = index++;
}
// Find closest ancestor that is a root.
for (var len = visited.length, i = len - 1; i > 0; i--) {
parent = visited[i - 1];
if (visited[i].isDynamicDependencyOf(parent)) {
root = visited[i];
break;
}
}
root = root || visited[0];
module.roots = union([root.path], module.roots);
if (root.path === module.path) {
roots[module.path] = 1;
}
});
roots = pack.roots = Object.keys(roots).sort();
bundles = pack.bundles = {};
ids = pack.ids = {};
/**
* Form the bundles. Shorten the module ids.
*/
forEach(pack.modules, function(module) {
var bundle;
var bundleId;
var relPath = module.path.slice(basePath.length + 1); // remove leading slash.
module.relPath = relPath;
// Consistent id'ing of modules uses its relative path.
ids[module.path] = pack.opts.debug ? relPath : md5(relPath);
graph.modules[ids[module.path]] = module.path;
// Push module into a bundle based on its roots.
bundleId = (
pack.opts.debug ?
ids[module.path] :
(
md5(
module.roots.sort().join('')
) +
'.js'
)
);
bundle = bundles[bundleId] || {id: bundleId, modules: []};
bundle.modules.push(module.path);
if (!module.bundled) {
bundle.render = true;
module.bundled = true;
}
bundles[bundleId] = bundle;
});
/**
* Sort modules in all bundles and name the bundle by its contents
* before rendering.
*/
forEach(bundles, function(bundle) {
bundle.modules.sort();
bundle.name = md5(bundle.modules.join(''), 8) + '.js';
graph.bundles[bundle.id] = bundle.modules.concat();
});
/**
* Output the graph if we have graphviz.
*/
try {
var graphviz = require('graphviz');
var g = graphviz.digraph('app');
var bundleColors = {};
var currentColor = 0;
var graphOpts = pack.opts.graph || {};
var colorscheme = graphOpts.colorscheme || 'brbg11';
forEach(pack.bundles, function(bundle) {
var color = ((currentColor++ % 11) + 1).toString();
var cluster = g.addCluster('"cluster-' + bundle.name + '"');
forEach(bundle.modules, function(path) {
var module = pack.modules[path];
var n = cluster.addNode(module.relPath, {
//group: bundle.id,
colorscheme: colorscheme,
color: color,
style: 'filled'
});
});
});
forEach(pack.modules, function(module) {
module.deps.static.forEach(function(depPath) {
var dep = pack.modules[depPath];
var edge = g.addEdge(module.relPath, dep.relPath);
edge.set('style', 'solid');
});
module.deps.dynamic.forEach(function(depPath) {
var dep = pack.modules[depPath];
var edge = g.addEdge(module.relPath, dep.relPath);
edge.set('style', 'dashed');
});
});
pack.emit('graph', g);
}
catch (e) {
console.log(e.message);
}
/**
* Push only the bundles that need to be rendered.
*/
forEach(bundles, function(bundle) {
if (bundle.render) {
pack.push(
new File({
path: path.join(process.cwd(), bundle.name),
base: process.cwd(),
modules: bundle.modules,
contents: new Buffer(
pack.renderBundle(bundle)
)
})
);
}
});
/**
* Push only the entries that depend on bundles that have been
* rerendered or rendered for the first time.
*/
//pack.entryPaths.forEach(function(entryPath, index) {
// var name = pack.entryNames[index];
// var entryBundles = pack.requiredBundles(entryPath);
// var filename = name + '.entry.js';
// var render;
// graph.entries[name] = [filename].concat(entryBundles);
// entryBundles.forEach(function(bundleId) {
// if (bundles[bundleId].render) {
// render = true;
// }
// });
// if (render) {
// pack.push(
// new File({
// path: path.join(process.cwd(), filename),
// base: process.cwd(),
// contents: new Buffer(
// pack.renderEntry(entryPath, entryBundles)
// )
// })
// );
// }
//});
pack.emit('bundled', graph);
};
/**
* A bundle root is defined as the path of the module that
* is contained in the bundle that is not a static dependency of any other
* module in the same bundle; i.e. the root of the bundle graph.
*/
Dynapack.prototype.setBundleName = function(bundle) {
var pack = this;
var roots = bundle.modules.concat();
bundle.modules.forEach(function(modulePath) {
var module = pack.modules[modulePath];
module.deps.static.forEach(function(depPath) {
pull(roots, depPath);
});
});
if (roots.length !== 1) {
throw new Error('Bundle has more than one root! How?', roots);
}
return roots[0];
};
/**
* Return a stream that receives a mapping between dynapack-generated
* bundle ids and custom ids (such as those generated by revving) and
* returns the string of html that should be included in each entry
* page.
*/
Dynapack.prototype.scripts = function() {
var pack = this;
var stream = new Transform({objectMode: true});
stream._transform = function(file, enc, callback) {
this._mapping = file.contents ?
JSON.parse(file.contents.toString()) :
file;
callback();
};
stream._flush = function(callback) {
var aliases = '';
var scripts = {};
var mapping = this._mapping;
if (mapping) {
// Generate the inline script that sets dynapackAliases.
aliases = 'window["dynapackAliases"]=' + JSON.stringify(mapping) + ';';
}
pack.entryNames.forEach(function(entryName, index) {
var entryPath = pack.entryPaths[index];
var entryBundles = pack.requiredBundles(entryPath);
var html = '<script>' + aliases + pack.renderEntry(entryPath, entryBundles) + '</script>';
//var html = scripts[entryName] = aliases + reduce(
html += reduce(
mapping,
iterator,
pack.entryScripts(entryName)
);
stream.push(
new File({
path: path.join(process.cwd(), entryName + '.html'),
contents: new Buffer(html)
})
);
function iterator(html, newBundleId, bundleId) {
return html.replace('/' + bundleId + '"', '/' + newBundleId + '"');
}
});
//this.push(
// new File({
// path: path.join(process.cwd(), 'dynapack-scripts.json'),
// contents: new Buffer(
// JSON.stringify(scripts)
// )
// })
//);
callback();
};
return stream;
};
/**
* Module has been transformed and saved to the modules hash; we are
* done with it until the next modification.
*/
Dynapack.prototype._finalize = function(path) {
this._loading[path]--;
if (sum(this._loading) === 0) {
this.bundle();
}
};
/**
* Inherit configuration options from pack.
*/
Dynapack.prototype.createModule = function(file) {
return new Module(
assign({file: file}, this.opts)
);
};
/**
* The module stream accepts finalized module sources.
*/
Dynapack.prototype.mods = function() {
return this._mods;
};
Dynapack.prototype._initMods = function() {
var pack = this;
var mods = pack._mods = new Writable({objectMode: true});
mods._write = function(module, encoding, callback) {
var old;
//console.log('received module', module);
if (typeof module.isNull !== 'function') {
return pack.emit(
'error',
new Error(
'Mods stream accepts only vinyl File objects.'
)
);
}
module = pack.createModule(module);
old = pack.modules[module.path];
pack.modules[module.path] = module;
module.parse(function(err) {
if (!err) {
var newDeps = old ? module.subtractDeps(old) : module.deps;
var removedDeps = old && old.subtractDeps(module);
newDeps.set.forEach(function(depPath) {
pack._deps.write(
new File({path: depPath})
);
});
if (removedDeps && removedDeps.set.length > 0) {
pack.clean();
}
//console.log('finalize from mods on', module.path);
pack._finalize(module.path);
}
callback(err);
});
};
mods.on(
'error',
pack.emit.bind(pack, 'error')
);
};
/**
* The deps stream is a ReadableStream that emits full file
* paths to modules that will be included in the pack. Load
* these modules and send them back in to Dynapack stream with
* their sources attached.
*/
Dynapack.prototype.deps = function() {
this._deps.unpipe(this._mods);
return this._deps;
};
/**
* Create the transform stream that loads dependencies and sends them
* to the dynapack mods stream (default) or to a custom transform stream.
* The deps stream takes in a vinyl File.
*
*/
Dynapack.prototype._initDeps = function() {
var pack = this;
var deps = pack._deps = new Transform({objectMode: true});
deps.write = function(dep, encoding, callback) {
var path = dep.path;
//console.log('dep', dep);
if (path in pack._loading) {
pack._loading[path]++;
}
else {
pack._loading[path] = 1;
}
Transform.prototype.write.call(this, dep, encoding, callback);
};
deps._transform = function(dep, encoding, callback) {
var path = dep.path;
if (!dep.isNull()) {
// Always replace previous version since source is provided.
return push();
}
fs.stat(path, function(err, stats) {
if (err) callback(err);
else {
var cachedMtime = pack._mtimes[path] || 0;
var mtime = pack._mtimes[path] = stats.mtime.getTime();
if (mtime > cachedMtime) {
load();
}
else {
pack._finalize(path);
callback(); // Use the cache, don't push anything to mods.
}
}
});
function load() {
fs.readFile(path, function(err, source) {
if (err) {
pack._loading[path]--;
callback(err);
}
else {
//console.log('loaded', id);
dep.contents = source;
push();
}
});
}
function push() {
deps.push(dep);
callback();
}
};
deps.once(
'error',
pack.emit.bind(pack, 'error')
);
};
/**
* Send in entry modules to dynapack. The dependency graph will be
* discovered, and each new dependency (and its source) will be emitted
* on the deps stream.
*
* @param {String|Object|File} entry This should be a path string, or vinyl config
* object or instance.
*
*/
Dynapack.prototype._transform = function(entry, encoding, callback) {
//console.log('received entry', entry);
if (typeof entry === 'string') {
entry = {path: entry};
}
if (this.entryPaths.indexOf(entry.path) < 0) {
this.entryNames.push(path.basename(entry.path).replace(/\.js$/, ''));
this.entryPaths.push(entry.path);
}
if (typeof entry.isNull !== 'function') {
entry = new File(entry);
}
this._deps.write(entry);
callback();
};
Dynapack.prototype._flush = function(callback) {
var pack = this;
pack.on('bundled', maybeFlush);
maybeFlush();
function maybeFlush() {
if (sum(pack._loading) === 0) {
pack.removeListener('bundled', maybeFlush);
callback();
}
}
};
Dynapack.prototype.clean = function() {
var modules = this.modules;
var clean = Object.keys(modules);
pack.traverse(function(visited) {
var module = last(visited);
pull(clean, module.path);
});
clean.forEach(function(id) {
delete modules[id];
});
};
function replaceAll(src, remove, insert) {
var re = new RegExp(
remove.replace(/\\/g, '\\\\')
.replace(/\./g, '\\.')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]'),
'g'
);
return src.replace(re, insert);
}
function replaceAllString(src, remove, insert) {
insert = '"' + insert + '"';
src = replaceAll(src, '\'' + remove + '\'', insert);
src = replaceAll(src, '"' + remove + '"', insert);
return src;
}
/**
* When a module is required asynchronously, all of the bundles on which it
* depends (statically) must be downloaded immediately by the client. This
* function finds those bundles given a root module.
*
* @returns {Array<Bundle>} The set of bundles required by the given
* root module.
*/
Dynapack.prototype.requiredBundles = function(rootPath) {
var pack = this;
var required = [];
if (pack.roots.indexOf(rootPath) < 0) {
throw new Error(rootPath, 'is not in the roots list.');
}
forEach(pack.bundles, function(bundle) {
// Grab random module in bundle, all modules in bundle will have
// same 'roots' property. That's what defines a bundle. :|
var module = pack.modules[bundle.modules[0]];
if (module.roots.indexOf(rootPath) >= 0) {
required.push(bundle);
}
});
return required;
};
Dynapack.prototype.renderModule = function(path) {
var pack = this;
var module = pack.modules[path];
var source = module.source;
module.deps.set.forEach(function(depPath) {
source = replaceAllString(
source,
module.refs[depPath],
pack.ids[depPath]
);
});
return (
'function(module, exports, require) {' +
source +
'}'
);
};
/**
* A bundle brings with it a set of dynamic deps (roots). The client must be
* informed of the new bundles these dynamic deps would introduce if
* asynchronously required. 'roots' is a mapping from root module path to an
* array of bundles.
*
* @param {Bundle} bundle
*
* @returns {Object<String, Bundle>}
*/
Dynapack.prototype.getBundleNewRoots = function(bundle) {
var pack = this;
var roots = {};
bundle.modules.forEach(function(path) {
var module = pack.modules[path];
module.deps.dynamic.forEach(function(depPath) {
roots[depPath] = pack.requiredBundles(depPath);
});
});
return roots;
};
module.exports = Dynapack;