1 | var through = require( 'through2' );
|
2 | var watchify = require( 'watchify' );
|
3 | var expand = require( 'glob-expand' );
|
4 | var trim = require( 'jq-trim' );
|
5 |
|
6 | module.exports = function ( browserifyOpts, opts, argv ) {
|
7 | browserifyOpts = browserifyOpts || { };
|
8 | opts = opts || { };
|
9 | var hash = require( 'hash-string' );
|
10 |
|
11 | var xtend = require( 'xtend' );
|
12 |
|
13 | var id = 'persistify_' + hash( process.cwd() + trim( opts.cacheId ) );
|
14 | var depsCacheId = 'deps-cx-' + id;
|
15 |
|
16 | var flatCache = require( 'flat-cache' );
|
17 | var fileEntryCache = require( 'file-entry-cache' );
|
18 |
|
19 | if ( opts.recreate ) {
|
20 | flatCache.clearCacheById( id );
|
21 | flatCache.clearCacheById( depsCacheId );
|
22 | }
|
23 |
|
24 | var cache = flatCache.load( id );
|
25 |
|
26 |
|
27 |
|
28 | var depsCacheFile = fileEntryCache.create( depsCacheId );
|
29 |
|
30 | var persistifyCache = cache.getKey( 'persistifyArgs' ) || {
|
31 | cache: {}, packageCache: {}
|
32 | };
|
33 |
|
34 |
|
35 |
|
36 | browserifyOpts.cache = persistifyCache.cache;
|
37 | browserifyOpts.packageCache = persistifyCache.packageCache;
|
38 | var fromArgs = require( 'browserify/bin/args' );
|
39 |
|
40 | var b = argv ? fromArgs( argv, browserifyOpts ) : require( 'browserify' )( browserifyOpts );
|
41 |
|
42 | var depFiles = expand( Object.keys( persistifyCache.cache ) );
|
43 |
|
44 | var changedFiles = depsCacheFile.getUpdatedFiles( depFiles );
|
45 | if ( changedFiles.length > 0 ) {
|
46 | changedFiles.forEach( function ( file ) {
|
47 | delete persistifyCache.cache[ file ];
|
48 | } );
|
49 | }
|
50 |
|
51 | function collect() {
|
52 | b.pipeline.get( 'deps' ).push( through.obj( function ( row, enc, next ) {
|
53 | var file = row.expose ? b._expose[ row.id ] : row.file;
|
54 | persistifyCache.cache[ file ] = {
|
55 | source: row.source,
|
56 | deps: xtend( { }, row.deps )
|
57 | };
|
58 | this.push( row );
|
59 | next();
|
60 | } ) );
|
61 | }
|
62 |
|
63 | if ( opts.watch ) {
|
64 | b = watchify( b );
|
65 | } else {
|
66 | collect();
|
67 | b.on( 'reset', collect );
|
68 | }
|
69 |
|
70 | var oldBundle = b.bundle;
|
71 | b.bundle = function () {
|
72 | var start = Date.now();
|
73 | var stream;
|
74 | try {
|
75 | stream = oldBundle.apply( b, arguments );
|
76 | stream.on( 'error', function ( err ) {
|
77 | console.error( err );
|
78 | } );
|
79 | stream.on( 'end', function () {
|
80 | setTimeout( function () {
|
81 | cache.setKey( 'persistifyArgs', persistifyCache );
|
82 | depsCacheFile.getUpdatedFiles( expand( Object.keys( persistifyCache.cache ) ) );
|
83 | depsCacheFile.reconcile();
|
84 | cache.save();
|
85 | }, 0 );
|
86 |
|
87 | var end = Date.now() - start;
|
88 | b.emit( 'bundle:done', end );
|
89 | } );
|
90 | } catch (ex) {
|
91 | console.error( ex );
|
92 | }
|
93 |
|
94 | return stream;
|
95 | };
|
96 |
|
97 | return b;
|
98 | };
|