xonecas.io
818
Du

dustymarkdown / files

dustymarkdown / node_modules / uglify-js / bin / uglifyjs

11.0 KB
1#! /usr/bin/env node
2// -*- js -*-
3
4global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util");
5var fs = require("fs");
6var uglify = require("uglify-js"), // symlink ~/.node_libraries/uglify-js.js to ../uglify-js.js
7    jsp = uglify.parser,
8    pro = uglify.uglify;
9
10var options = {
11        ast: false,
12        mangle: true,
13        mangle_toplevel: false,
14        squeeze: true,
15        make_seqs: true,
16        dead_code: true,
17        verbose: false,
18        show_copyright: true,
19        out_same_file: false,
20        max_line_length: 32 * 1024,
21        unsafe: false,
22        reserved_names: null,
23        defines: { },
24        codegen_options: {
25                ascii_only: false,
26                beautify: false,
27                indent_level: 4,
28                indent_start: 0,
29                quote_keys: false,
30                space_colon: false
31        },
32        make: false,
33        output: true            // stdout
34};
35
36var args = jsp.slice(process.argv, 2);
37var filename;
38
39out: while (args.length > 0) {
40        var v = args.shift();
41        switch (v) {
42            case "-b":
43            case "--beautify":
44                options.codegen_options.beautify = true;
45                break;
46            case "-i":
47            case "--indent":
48                options.codegen_options.indent_level = args.shift();
49                break;
50            case "-q":
51            case "--quote-keys":
52                options.codegen_options.quote_keys = true;
53                break;
54            case "-mt":
55            case "--mangle-toplevel":
56                options.mangle_toplevel = true;
57                break;
58            case "--no-mangle":
59            case "-nm":
60                options.mangle = false;
61                break;
62            case "--no-squeeze":
63            case "-ns":
64                options.squeeze = false;
65                break;
66            case "--no-seqs":
67                options.make_seqs = false;
68                break;
69            case "--no-dead-code":
70                options.dead_code = false;
71                break;
72            case "--no-copyright":
73            case "-nc":
74                options.show_copyright = false;
75                break;
76            case "-o":
77            case "--output":
78                options.output = args.shift();
79                break;
80            case "--overwrite":
81                options.out_same_file = true;
82                break;
83            case "-v":
84            case "--verbose":
85                options.verbose = true;
86                break;
87            case "--ast":
88                options.ast = true;
89                break;
90            case "--unsafe":
91                options.unsafe = true;
92                break;
93            case "--max-line-len":
94                options.max_line_length = parseInt(args.shift(), 10);
95                break;
96            case "--reserved-names":
97                options.reserved_names = args.shift().split(",");
98                break;
99            case "-d":
100            case "--define":
101                 var defarg = args.shift();
102                 try {
103                     var defsym = function(sym) {
104                             // KEYWORDS_ATOM doesn't include NaN or Infinity - should we check
105                             // for them too ?? We don't check reserved words and the like as the
106                             // define values are only substituted AFTER parsing
107                             if (jsp.KEYWORDS_ATOM.hasOwnProperty(sym)) {
108                                 throw "Don't define values for inbuilt constant '"+sym+"'";
109                             }
110                             return sym;
111                         },
112                         defval = function(v) {
113                             if (v.match(/^"(.*)"$/) || v.match(/^'(.*)'$/)) {
114                                 return [ "string", RegExp.$1 ];
115                             }
116                             else if (!isNaN(parseFloat(v))) {
117                                 return [ "num", parseFloat(v) ];
118                             }
119                             else if (v.match(/^[a-z\$_][a-z\$_0-9]*$/i)) {
120                                 return [ "name", v ];
121                             }
122                             else if (!v.match(/"/)) {
123                                 return [ "string", v ];
124                             }
125                             else if (!v.match(/'/)) {
126                                 return [ "string", v ];
127                             }
128                             throw "Can't understand the specified value: "+v;
129                         };
130                     if (defarg.match(/^([a-z_\$][a-z_\$0-9]*)(=(.*))?$/i)) {
131                         var sym = defsym(RegExp.$1),
132                             val = RegExp.$2 ? defval(RegExp.$2.substr(1)) : [ 'name', 'true' ];
133                         options.defines[sym] = val;
134                     }
135                     else {
136                         throw "The --define option expects SYMBOL[=value]";
137                     }
138                 } catch(ex) {
139                     sys.print("ERROR: In option --define "+defarg+"\n"+ex+"\n");
140                     process.exit(1);
141                 }
142                 break;
143            case "--define-from-module":
144                var defmodarg = args.shift(),
145                    defmodule = require(defmodarg),
146                    sym,
147                    val;
148                for (sym in defmodule) {
149                    if (defmodule.hasOwnProperty(sym)) {
150                        options.defines[sym] = function(val) {
151                            if (typeof val == "string")
152                                return [ "string", val ];
153                            if (typeof val == "number")
154                                return [ "num", val ];
155                            if (val === true)
156                                return [ 'name', 'true' ];
157                            if (val === false)
158                                return [ 'name', 'false' ];
159                            if (val === null)
160                                return [ 'name', 'null' ];
161                            if (val === undefined)
162                                return [ 'name', 'undefined' ];
163                            sys.print("ERROR: In option --define-from-module "+defmodarg+"\n");
164                            sys.print("ERROR: Unknown object type for: "+sym+"="+val+"\n");
165                            process.exit(1);
166                            return null;
167                        }(defmodule[sym]);
168                    }
169                }
170                break;
171            case "--ascii":
172                options.codegen_options.ascii_only = true;
173                break;
174            case "--make":
175                options.make = true;
176                break;
177            default:
178                filename = v;
179                break out;
180        }
181}
182
183if (options.verbose) {
184        pro.set_logger(function(msg){
185                sys.debug(msg);
186        });
187}
188
189jsp.set_logger(function(msg){
190        sys.debug(msg);
191});
192
193if (options.make) {
194        options.out_same_file = false; // doesn't make sense in this case
195        var makefile = JSON.parse(fs.readFileSync(filename || "Makefile.uglify.js").toString());
196        output(makefile.files.map(function(file){
197                var code = fs.readFileSync(file.name);
198                if (file.module) {
199                        code = "(function(){return this}())." + file.module + " = (function(exports, global){" + code + "\n;return exports;})({}, (function(){return this}()));";
200                }
201                else if (file.hide) {
202                        code = "(function(){" + code + "}());";
203                }
204                return squeeze_it(code);
205        }).join("\n"));
206}
207else if (filename) {
208        fs.readFile(filename, "utf8", function(err, text){
209                if (err) throw err;
210                output(squeeze_it(text));
211        });
212}
213else {
214        var stdin = process.openStdin();
215        stdin.setEncoding("utf8");
216        var text = "";
217        stdin.on("data", function(chunk){
218                text += chunk;
219        });
220        stdin.on("end", function() {
221                output(squeeze_it(text));
222        });
223}
224
225function output(text) {
226        var out;
227        if (options.out_same_file && filename)
228                options.output = filename;
229        if (options.output === true) {
230                out = process.stdout;
231        } else {
232                out = fs.createWriteStream(options.output, {
233                        flags: "w",
234                        encoding: "utf8",
235                        mode: 0644
236                });
237        }
238        out.write(text);
239        if (options.output !== true) {
240                out.end();
241        }
242};
243
244// --------- main ends here.
245
246function show_copyright(comments) {
247        var ret = "";
248        for (var i = 0; i < comments.length; ++i) {
249                var c = comments[i];
250                if (c.type == "comment1") {
251                        ret += "//" + c.value + "\n";
252                } else {
253                        ret += "/*" + c.value + "*/";
254                }
255        }
256        return ret;
257};
258
259function squeeze_it(code) {
260        var result = "";
261        if (options.show_copyright) {
262                var tok = jsp.tokenizer(code), c;
263                c = tok();
264                result += show_copyright(c.comments_before);
265        }
266        try {
267                var ast = time_it("parse", function(){ return jsp.parse(code); });
268                if (options.mangle) ast = time_it("mangle", function(){
269                        return pro.ast_mangle(ast, {
270                                toplevel: options.mangle_toplevel,
271                                defines: options.defines,
272                                except: options.reserved_names
273                        });
274                });
275                if (options.squeeze) ast = time_it("squeeze", function(){
276                        ast = pro.ast_squeeze(ast, {
277                                make_seqs  : options.make_seqs,
278                                dead_code  : options.dead_code,
279                                keep_comps : !options.unsafe
280                        });
281                        if (options.unsafe)
282                                ast = pro.ast_squeeze_more(ast);
283                        return ast;
284                });
285                if (options.ast)
286                        return sys.inspect(ast, null, null);
287                result += time_it("generate", function(){ return pro.gen_code(ast, options.codegen_options) });
288                if (!options.codegen_options.beautify && options.max_line_length) {
289                        result = time_it("split", function(){ return pro.split_lines(result, options.max_line_length) });
290                }
291                return result;
292        } catch(ex) {
293                sys.debug(ex.stack);
294                sys.debug(sys.inspect(ex));
295                sys.debug(JSON.stringify(ex));
296        }
297};
298
299function time_it(name, cont) {
300        if (!options.verbose)
301                return cont();
302        var t1 = new Date().getTime();
303        try { return cont(); }
304        finally { sys.debug("// " + name + ": " + ((new Date().getTime() - t1) / 1000).toFixed(3) + " sec."); }
305};