-
Notifications
You must be signed in to change notification settings - Fork 19
/
beautify-with-words.js
80 lines (70 loc) · 2.18 KB
/
beautify-with-words.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
'use strict';
var phonetic = require('phonetic');
var UglifyJS = require('uglify-js');
module.exports = function beautifyWithWords (contents, argv) {
// Default options to pass to the beautifier
var beautifyOptions = {
beautify: true
};
// Format options to pass to the beautifier
if (argv && argv.b) {
Array.isArray(argv.b) || (argv.b = [ argv.b ]);
argv.b.forEach(function(option) {
if (typeof option !== 'string') return;
option = option.split('=');
option[0] = option[0].replace(/-/g, '_');
option[1] = option[1] === 'true' ? true :
option[1] === 'false' ? false :
option[1] === 'null' ? null :
!isNaN(option[1]) ? parseInt(option[1]) :
option[1];
beautifyOptions[option[0]] = option[1];
});
}
// Generate unique phonetic words to be used for variable names.
// Start with 2 syllable words, once we've somewhat exhausted that
// space, try 3 syllable words, and so on.
var getUniqueWord = (function() {
var options = { capFirst: false, syllables: 2 };
var used = {};
var keyCount = 0;
return function generate() {
var word = phonetic.generate(options);
if (!used[word]) {
used[word] = true;
return word;
}
var currKeyCount = Object.keys(used).length;
if (currKeyCount === keyCount) {
keyCount = 0;
options.syllables++;
} else {
keyCount = currKeyCount;
}
return generate();
};
})();
// Override `next_mangled` so it returns our words instead.
// mangle_names() -> mangle() -> next_mangled() in
// https://github.com/mishoo/UglifyJS2/blob/v2.4.11/lib/scope.js
UglifyJS.AST_Scope.prototype.next_mangled = function() {
var next;
while ((next = getUniqueWord())) {
if (!UglifyJS.is_identifier(next)) continue;
return next;
}
};
// "Mangle" names
var ast;
try {
ast = UglifyJS.parse(contents);
ast.figure_out_scope();
ast.mangle_names();
} catch(err) {
throw err;
}
// Beautify
var stream = UglifyJS.OutputStream(beautifyOptions);
ast.print(stream);
return stream.toString();
};