/
index.js
340 lines (290 loc) · 9.36 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
"use strict";
const {
markEvalScopes,
isMarked: isEvalScopesMarked,
hasEval,
} = require("babel-helper-mark-eval-scopes");
const PATH_RENAME_MARKER = Symbol("PATH_RENAME_MARKER");
module.exports = ({ types: t, traverse }) => {
const hop = Object.prototype.hasOwnProperty;
class Mangler {
constructor(charset, program, {
blacklist = {},
keepFnName = false,
eval: _eval = false,
topLevel = false,
keepClassName = false,
} = {}) {
this.charset = charset;
this.program = program;
this.blacklist = blacklist;
this.keepFnName = keepFnName;
this.keepClassName = keepClassName;
this.eval = _eval;
this.topLevel = topLevel;
this.unsafeScopes = new Set;
this.visitedScopes = new Set;
this.referencesToUpdate = new Map;
}
run() {
this.cleanup();
this.collect();
this.charset.sort();
this.mangle();
}
cleanup() {
traverse.clearCache();
this.program.scope.crawl();
}
isBlacklist(name) {
if (Array.isArray(this.blacklist)) {
return this.blacklist.indexOf(name) !== -1;
}
return hop.call(this.blacklist, name) && this.blacklist[name];
}
markUnsafeScopes(scope) {
let evalScope = scope;
do {
this.unsafeScopes.add(evalScope);
} while (evalScope = evalScope.parent);
}
collect() {
const mangler = this;
if (!isEvalScopesMarked(mangler.program.scope)) {
markEvalScopes(mangler.program);
}
if (this.charset.shouldConsider) {
const collectVisitor = {
Identifier(path) {
const { node } = path;
if ((path.parentPath.isMemberExpression({ property: node })) ||
(path.parentPath.isObjectProperty({ key: node }))
) {
mangler.charset.consider(node.name);
}
},
Literal({ node }) {
mangler.charset.consider(String(node.value));
}
};
mangler.program.traverse(collectVisitor);
}
}
mangle() {
const mangler = this;
this.program.traverse({
Scopable(path) {
const {scope} = path;
if (!mangler.eval && hasEval(scope)) return;
if (mangler.visitedScopes.has(scope)) return;
mangler.visitedScopes.add(scope);
function hasOwnBinding(name) {
if (scope.parent !== mangler.program.scope) {
return scope.hasOwnBinding(name);
}
return mangler.program.scope.hasOwnBinding(name) || scope.hasOwnBinding(name);
}
let i = 0;
function getNext() {
return mangler.charset.getIdentifier(i++);
}
// This is useful when we have vars of single character
// => var a, ...z, A, ...Z, $, _;
// to
// => var aa, a, b ,c;
// instead of
// => var aa, ab, ...;
// TODO:
// Re-enable after enabling this feature
// This doesn't work right now as we are concentrating
// on performance improvements
// function resetNext() {
// i = 0;
// }
const bindings = scope.getAllBindings();
const names = Object.keys(bindings);
for (let i = 0; i < names.length; i++) {
const oldName = names[i];
const binding = bindings[oldName];
const isTopLevel = mangler.program.scope.bindings[oldName] === binding;
if (
// already renamed bindings
binding.renamed
// arguments
|| oldName === "arguments"
// globals
|| (mangler.topLevel ? false : isTopLevel)
// other scope bindings
|| !hasOwnBinding(oldName)
// labels
|| binding.path.isLabeledStatement()
// blacklisted
|| mangler.isBlacklist(oldName)
// function names
|| (mangler.keepFnName ? isFunction(binding.path) : false)
// class names
|| (mangler.keepClassName ? isClass(binding.path) : false)
) {
continue;
}
let next;
do {
next = getNext();
} while (
!t.isValidIdentifier(next)
|| hop.call(bindings, next)
|| scope.hasGlobal(next)
|| scope.hasReference(next)
);
// TODO:
// re-enable this - check above
// resetNext();
mangler.rename(scope, oldName, next);
if (isTopLevel) {
mangler.rename(mangler.program.scope, oldName, next);
}
// mark the binding as renamed
binding.renamed = true;
}
}
});
// TODO:
// re-enable
// check above
// this.updateReferences();
}
rename(scope, oldName, newName) {
const binding = scope.getBinding(oldName);
// rename at the declaration level
const bindingPaths = binding.path.getBindingIdentifierPaths(true, false);
// we traverse through all bindingPaths because,
// there is no binding.identifierPath in babel
for (const name in bindingPaths) {
if (name !== oldName) continue;
for (const idPath of bindingPaths[name]) {
if (binding.identifier === idPath.node) {
idPath.replaceWith(t.identifier(newName));
binding.identifier = idPath.node;
idPath[PATH_RENAME_MARKER] = true;
}
}
}
const {bindings} = scope;
bindings[newName] = binding;
delete bindings[oldName];
// update all constant violations & redeclarations
const violations = binding.constantViolations;
for (let i = 0; i < violations.length; i++) {
if (violations[i].isLabeledStatement()) continue;
const bindings = violations[i].getBindingIdentifierPaths();
Object
.keys(bindings)
.map((b) => {
if (b === oldName && !bindings[b][PATH_RENAME_MARKER]) {
bindings[b].replaceWith(t.identifier(newName));
bindings[b][PATH_RENAME_MARKER] = true;
}
});
}
// update all referenced places
const refs = binding.referencePaths;
for (let i = 0; i < refs.length; i++) {
const path = refs[i];
if (path[PATH_RENAME_MARKER]) continue;
const {node} = path;
if (!path.isIdentifier()) {
// Ideally, this should not happen
// it happens in these places now -
// case 1: Export Statements
// This is a bug in babel
// https://github.com/babel/babel/pull/3629
// case 2: Replacements in other plugins
// eg: https://github.com/babel/babili/issues/122
// replacement in dce from `x` to `!x` gives referencePath as `!x`
path.traverse({
ReferencedIdentifier(refPath) {
if (refPath.node.name === oldName && refPath.scope === scope && !refPath[PATH_RENAME_MARKER]) {
refPath.node.name = newName;
}
}
});
} else if (!isLabelIdentifier(path)) {
node.name = newName;
}
}
}
}
return {
name: "minify-mangle-names",
visitor: {
Program(path) {
// If the source code is small then we're going to assume that the user
// is running on this on single files before bundling. Therefore we
// need to achieve as much determinisim and we will not do any frequency
// sorting on the character set. Currently the number is pretty arbitrary.
const shouldConsiderSource = path.getSource().length > 70000;
const charset = new Charset(shouldConsiderSource);
const mangler = new Mangler(charset, path, this.opts);
mangler.run();
},
},
};
};
const CHARSET = ("abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ$_").split("");
class Charset {
constructor(shouldConsider) {
this.shouldConsider = shouldConsider;
this.chars = CHARSET.slice();
this.frequency = {};
this.chars.forEach((c) => { this.frequency[c] = 0; });
this.finalized = false;
}
consider(str) {
if (!this.shouldConsider) {
return;
}
str.split("").forEach((c) => {
if (this.frequency[c] != null) {
this.frequency[c]++;
}
});
}
sort() {
if (this.shouldConsider) {
this.chars = this.chars.sort(
(a, b) => this.frequency[b] - this.frequency[a]
);
}
this.finalized = true;
}
getIdentifier(num) {
if (!this.finalized) {
throw new Error("Should sort first");
}
let ret = "";
num++;
do {
num--;
ret += this.chars[num % this.chars.length];
num = Math.floor(num / this.chars.length);
} while (num > 0);
return ret;
}
}
// for keepFnName
function isFunction(path) {
return path.isFunctionExpression()
|| path.isFunctionDeclaration();
}
// for keepClassName
function isClass(path) {
return path.isClassExpression()
|| path.isClassDeclaration();
}
function isLabelIdentifier(path) {
const {node} = path;
return path.parentPath.isLabeledStatement({ label: node })
|| path.parentPath.isBreakStatement({ label: node })
|| path.parentPath.isContinueStatement({ label: node });
}