This repository has been archived by the owner on Jun 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
ClosureCompiler.js
328 lines (297 loc) · 11.7 KB
/
ClosureCompiler.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
/*
Copyright 2013 Daniel Wirtz <dcode@dcode.io>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @license ClosureCompiler.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
* Released under the Apache License, Version 2.0
* see: https://github.com/dcodeIO/ClosureCompiler.js for details
*/
(function(global) {
if (typeof require != 'function' || !module || !module.exports || !process) {
throw(new Error("ClosureCompiler.js can only be used within node.js"));
}
// Dependencies
var path = require("path"),
fs = require("fs"),
child_process = require("child_process"),
concat = require('bl');
if (!fs.existsSync) fs.existsSync = path.existsSync; // node < 0.8
/**
* Constructs a new ClosureCompiler instance.
* @exports ClosureCompiler
* @class Closure Compiler binding.
* @param {Object.<string,*>=} options Compilation options
* @constructor
*/
var ClosureCompiler = function(options) {
/**
* Compilation options.
* @type {Object.<string, *>}
*/
this.options = typeof options === 'object' && options ? options : {};
};
/**
* Validates an option.
* @param {string} name Option name
* @param {string} actual Actual value
* @param {Array} expected Expected values
* @throw {Error} If the option is invalid
* @private
*/
ClosureCompiler._assertOption = function(name, actual, expected) {
if (expected.indexOf(actual) < 0) {
throw("Illegal "+name+" value: "+actual+" ("+expected+" expected)");
}
};
/**
* Java extension, e.g. '.exe' on windows.
* @type {string}
*/
ClosureCompiler.JAVA_EXT = process.platform == 'win32' ? '.exe' : '';
/**
* Gets the path of the global java executable.
* @return {string} Absolute path to or "java(.exe)" if not determinable
*/
ClosureCompiler.getGlobalJava = function() {
var java = null;
if (process.env["JAVA_HOME"]) {
java = path.join(process.env["JAVA_HOME"], "bin", "java"+ClosureCompiler.JAVA_EXT);
if (!fs.existsSync(java)) {
java = null;
}
}
if (!java) {
java = "java";
}
return java;
};
/**
* Gets the path of the bundled java executable.
* @return {string} Absolute path to "java(.exe)"
*/
ClosureCompiler.getBundledJava = function() {
return path.normalize(path.join(__dirname, "jre", "bin", "java"+ClosureCompiler.JAVA_EXT));
};
/**
* Tests if java is callable.
* @param {string} java Path to java
* @param {function(boolean, Error)} callback Callback function
*/
ClosureCompiler.testJava = function(java, callback) {
child_process.exec('"'+java+'" -version', {}, function(error, stdout, stderr) {
stderr += "";
if (stderr.match(/1\.[7-8]+/)) {
callback(true, null);
} else if (stderr.indexOf("version \"") >= 0) {
callback(false, new Error("Not Java 7"));
} else {
callback(false, error);
}
});
};
/**
* Compiles one or more scripts through a new instance of ClosureCompiler.
* @param {string|Array.<string>} files File or an array of files to compile
* @param {Object.<string,*|Array>} options Any options Closure Compiler supports. If an option can occur
* multiple times, simply supply an array. Externs can additionally point to a directory to include all *.js files
* in it.
* @param {ReadStream} stdin Optional read stream to use as stdin for closure compiler
* @param {function(Error,string)} callback Callback called with the error, if any, and the compiled code
* @throws {Error} If the file cannot be compiled
*/
ClosureCompiler.compile = function(files, options, stdin, callback) {
if (arguments.length < 4) {
callback = stdin;
stdin = null;
}
new ClosureCompiler(options).compile(files, stdin, callback);
};
/**
* Compiles one or more scripts through this instance of ClosureCompiler.
* @param {string|Array.<string>} files File or an array of files to compile
* @param {ReadStream} stdin Optional read stream to use as stdin for closure compiler
* @param {function((Error|string),string)} callback Callback called with the error, if any, and the compiled code.
* If no error occurred, error contains the string output from stderr besides the result.
* @throws {Error} If the file cannot be compiled
*/
ClosureCompiler.prototype.compile = function(files, stdin, callback) {
if (arguments.length < 3) {
callback = stdin;
stdin = null;
}
// Convert all option keys to lower case
var options = {};
var keys = Object.keys(this.options);
for (var i=0; i<keys.length; i++) {
options[keys[i].toLowerCase()] = this.options[keys[i]];
}
delete options["js"];
delete options["js_output_file"];
var xms = options["xms"] || null,
xmx = options["xmx"] || "1024m";
delete options["xms"];
delete options["xmx"];
var jarFilePath;
if (options['compiler_jar']) {
jarFilePath = options['compiler_jar'];
delete options['compiler_jar'];
} else {
var jarDir = __dirname + '/compiler';
fs.readdirSync(jarDir).forEach(function(file) {
if (file.indexOf('closure-compiler') !== -1) {
jarFilePath = jarDir + "/" + file;
}
});
}
// -XX:+TieredCompilation speeds up compilation for Java 1.7.
// Previous -d32 was for Java 1.6 only.
// Compiler now requires Java 1.7 and this flag does not need detection.
var args = ['-XX:+TieredCompilation'];
if (xms) args.push('-Xms'+xms);
args.push(
'-Xmx'+xmx,
'-jar', jarFilePath
);
// Source files
if (!(files instanceof Array)) {
files = [files];
}
for (i=0; i<files.length; i++) {
if (typeof files[i] != 'string') {
throw(new Error("Illegal source file: "+files[i]));
}
if (files[i].indexOf('"') >= 0) {
args.push('--js=' + files[i]);
} else {
stat = fs.statSync(files[i]);
if (!stat.isFile()) {
throw (new Error("Source file not found: " + files[i]));
}
args.push('--js', files[i]);
}
}
// Externs files
if (!options.externs) options.externs = [];
if (!(options.externs instanceof Array)) {
options.externs = [options.externs];
}
var externs = [];
var j, stat;
for (i=0; i<options.externs.length; i++) {
if (typeof options.externs[i] != 'string' || options.externs[i] == "") {
throw(new Error("Externs directive does not point to a file or directory: "+options.externs[i]));
}
if (options.externs[i].toLowerCase() == "node") {
options.externs[i] = __dirname+"/node_modules/closurecompiler-externs";
}
stat = fs.statSync(options.externs[i]);
if (stat.isDirectory()) {
// Use all files in that directory
var dfiles = fs.readdirSync(options.externs[i]);
for (j=0; j<dfiles.length; j++) {
var fname = options.externs[i]+"/"+dfiles[j];
var fstats = fs.statSync(fname);
if (fstats.isFile() && path.extname(fname).toLowerCase() == '.js') {
externs.push(fname);
}
}
} else if (stat.isFile()) {
externs.push(options.externs[i]);
} else {
throw(new Error("Externs file not found: "+options.externs[i]));
}
}
delete options["externs"];
for (i=0; i<externs.length; i++) {
args.push('--externs', externs[i]);
}
// Convert any other options to command line arguments
keys = Object.keys(options);
for (i=0; i<keys.length; i++) {
var key = keys[i];
var value = options[keys[i]];
if (!/[a-zA-Z0-9_]+/.test(key)) {
throw(new Error("Illegal option: "+key));
}
if (value === true) { // Only once
args.push('--'+key);
} else if (value === false) {
// Skip
} else { // Multiple times
if (!(value instanceof Array)) {
value = [value];
}
for (j=0; j<value.length; j++) {
if (!/[^\s]*/.test(value[j])) {
throw(new Error("Illegal value for option "+key+": "+value[j]));
}
args.push('--'+key, value[j]);
}
}
}
// Executes a command
function exec(cmd, args, stdin, callback) {
var stdout = concat();
var stderr = concat();
var process = child_process.spawn(cmd, args, {
stdio: [stdin || 'ignore', 'pipe', 'pipe']
});
process.stdout.pipe(stdout);
process.stderr.pipe(stderr);
process.on('exit', function(code, signal) {
var err;
if (code) {
err = new Error(code);
err.code = code;
err.signal = signal;
}
callback(err, stdout, stderr);
});
process.on('error', function (err) {
callback(err, stdout, stderr);
});
}
// Run it
function run(java, args) {
exec(java, args, stdin, function(error, stdout, stderr) {
if (stdout.length > 0 || stderr.length > 0) { // If we get output, error basically just contains a copy of stderr
callback(stderr+"", stdout+"");
} else {
callback(error, null);
}
});
}
// Try any other global java
ClosureCompiler.testJava(ClosureCompiler.getGlobalJava(), function(ok) {
if (ok) {
run(ClosureCompiler.getGlobalJava(), args);
} else {
// If there is no global java, try the bundled one
ClosureCompiler.testJava(ClosureCompiler.getBundledJava(), function(ok) {
if (ok) {
run(ClosureCompiler.getBundledJava(), args);
} else {
throw(new Error("Java is not available, neither the bundled nor a global one."));
}
});
}
});
};
/**
* Returns a string representation of this object.
* @returns {string} String representation as of "ClosureCompiler"
*/
ClosureCompiler.prototype.toString = function() {
return "ClosureCompiler";
};
module["exports"] = ClosureCompiler;
})(this);