-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
103 lines (85 loc) · 2.11 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
'use strict';
var estraverse = require('estraverse')
, escodegen = require('escodegen')
, through = require('through2')
, esprima = require('esprima');
//
// Expose the plugin.
//
module.exports = deumdify;
/**
* Prune unwanted branches from the given source code.
*
* @param {String} code Source code to prune
* @returns {String} Pruned source code
* @api private
*/
function prune(code) {
var ast = esprima.parse(code);
estraverse.replace(ast, {
leave: function leave(node, parent) {
var ret;
if ('IfStatement' === node.type) {
if ('BinaryExpression' !== node.test.type) return;
if ('self' === node.test.left.argument.name) {
node.alternate = null;
} else if ('global' === node.test.left.argument.name) {
ret = node.alternate;
}
return ret;
}
if (
'BlockStatement' === node.type
&& 'FunctionExpression' === parent.type
) {
return node.body[0].alternate.alternate;
}
}
});
return escodegen.generate(ast, {
format: {
indent: { style: ' ' },
semicolons: false,
compact: true
}
});
}
/**
* Create a transform stream.
*
* @returns {Stream} Transform stream
* @api private
*/
function createStream() {
var firstChunk = true;
var stream = through(function transform(chunk, encoding, next) {
if (!firstChunk) return next(null, chunk);
firstChunk = false;
var regex = /^(.+?)(\(function\(\)\{)/
, pattern;
chunk = chunk.toString().replace(regex, function replacer(match, p1, p2) {
pattern = p1;
return p2;
});
this.push(prune(pattern) + chunk);
next();
});
stream.label = 'prune-umd';
return stream;
}
/**
* Prune the UMD pattern from a Browserify bundle stream.
*
* @param {Browserify} browserify Browserify instance
* @api public
*/
function deumdify(browserify) {
//
// Bail out if there is no UMD wrapper.
//
if (!browserify._options.standalone) return;
browserify.pipeline.push(createStream());
browserify.on('reset', function reset() {
browserify.pipeline.push(createStream());
});
}