1 // <script type="text/javascript">
2 XObject = imports.XObject.XObject;
3 File = imports.File.File;
5 TextStream = imports.TextStream.TextStream;
6 TokenReader = imports.TokenReader.TokenReader;
7 ScopeParser = imports.ScopeParser.ScopeParser;
8 TokenStream = imports.TokenStream.TokenStream;
9 CompressWhite = imports.CompressWhite.CompressWhite;
10 Collapse = imports.Collapse.Collapse;
12 GLib = imports.gi.GLib;
24 Packer = imports['JSDOC/Packer.js'].Packer;
27 files : [ "/location/of/file1.js", "/location/of/file2.js", ... ],
28 target : "/tmp/output.js",
29 debugTarget : "/tmp/output.debug.js", // merged file without compression.
30 translateJSON: "/tmp/translate.json",
35 "/location/of/temp_batch_dir",
36 "/location/of/output-compacted-file.js",
37 "/location/of/output-debug-merged-file.js"
42 * Notes for improving compacting:
43 * if you add a jsdoc comment
50 * directly before an eval statement, it will compress all the code around the eval,
51 * and not rename the variables 'avarname'
53 * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
54 * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
58 * Notes for translation
59 * - translation relies on you using double quotes for strings if they need translating
60 * - single quoted strings are ignored.
62 * Generation of indexFiles
63 * - translateIndex = the indexfile
70 Packer = function(cfg)
73 XObject.extend(this, cfg);
75 if (this.srcfiles && this.srcfiles.length) {
76 this.srcfiles.forEach(function(f) {
77 _this.loadSourceFile(f);
87 this.timer = new Date() * 1;
94 * @prop srcfiles {String} file containing a list of files/or classes to use.
99 * @prop files {Array} list of files to compress (must be full path)
103 * @prop target {String} target to write files to - must be full path.
107 * @prop debugTarget {String} target to write files debug version to (uncompacted)- must be full path.
109 debugTarget : '', // merged file without compression.
111 * @prop tmpDir {String} (optional) where to put the temporary files.
112 * if you set this, then files will not be cleaned up
116 translateJSON : '', // json based list of strings in all files.
119 * @prop cleanup {Boolean} (optional) clean up temp files after done -
120 * Defaults to false if you set tmpDir, otherwise true.
125 * @prop prefix {String} (optional) prefix of directory to be stripped of when
126 * Calculating md5 of filename
129 out : '', // if no target is specified - then this will contain the result
132 loadSourceFile : function(srcfile)
134 var lines = File.read(srcfile).split("\n");
136 lines.forEach(function(f) {
138 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
141 if (/\.js$/.test(f)) {
142 _this.files.push( f);
147 //println("ADD"+ f.replace(/\./g, '/'));
148 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
149 if (_this.files.indexOf(f) > -1) {
152 _this.files.push( add );
158 packAll : function() // do the packing (run from constructor)
161 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
162 //File.write(this.transfile, "");
164 File.write(this.target, "");
167 if (this.debugTarget) {
168 File.write(this.debugTarget, "");
171 for(var i=0; i < this.files.length; i++) {
172 var file = this.files[i];
174 print("reading " +file );
175 if (!File.isFile(file)) {
176 print("SKIP (is not a file) " + file);
180 if (this.debugTarget) {
181 File.append(this.debugTarget, File.read(file));
183 // it's a good idea to check with 0 compression to see if the code can parse!!
186 //File.append(dout, str +"\n");
190 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
193 // let's see if we have a min file already?
194 // this might happen if tmpDir is set ..
195 if (true && File.exists(minfile)) {
196 var mt = File.mtime(minfile);
197 var ot = File.mtime(file);
198 print("compare : " + mt + "=>" + ot);
202 // then the min'files time is > than original..
203 var str = File.read(minfile);
204 print("using MIN FILE "+ minfile);
206 File.append(outpath, str + "\n");
215 print("COMPRESSING ");
216 //var codeComp = pack(str, 10, 0, 0);
217 if (File.exists(minfile)) {
218 File.remove(minfile);
220 var str = File.read(file);
221 var str = this.pack(str, file, minfile);
223 File.write(minfile, str);
229 if (this.translateJSON) {
232 print("MERGING LANGUAGE");
233 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
235 File.write(this.target, out);
242 File.write(this.translateJSON, "");
243 for(var i=0; i < this.files.length; i++) {
244 var file = this.files[i];
245 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
246 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
247 if (File.exists(transmd5)) {
248 var str = File.read(transmd5);
251 File.append(this.target, str + "\n");
253 this.out += str + "\n";
258 File.remove(transmd5);
261 if (File.exists(transfile)) {
262 var str = File.read(transfile);
264 File.append(this.translateJSON, str);
267 File.remove(transfile);
275 print("MERGING SOURCE");
277 for(var i=0; i < this.files.length; i++) {
278 var file = this.files[i];
279 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
282 if (!File.exists(minfile)) {
285 var str = File.read(minfile);
286 print("using MIN FILE "+ minfile);
289 File.append(this.target, str + "\n");
291 this.out += str + "\n";
296 File.remove(minfile);
306 * Core packing routine for a file
308 * @param str - str source text..
309 * @param fn - filename (for reference?)
310 * @param minfile - min file location...
314 pack : function (str,fn,minfile)
317 var tr = new TokenReader( {
322 collapseWhite : false
324 this.timerPrint("START" + fn);
326 // we can load translation map here...
328 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
330 // at this point we can write a language file...
331 if (this.translateJSON) {
333 this.writeTranslateFile(fn, minfile, toks);
336 this.activeFile = fn;
338 // and replace if we are generating a different language..
340 this.timerPrint("Tokenized");
341 //var ts = new TokenStream(toks);
342 //print(JSON.stringify(toks, null,4 )); Seed.quit();
343 var ts = new Collapse(toks);
344 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
346 var sp = new ScopeParser(ts);
347 this.timerPrint("Converted to Parser");
349 sp.buildSymbolTree();
350 this.timerPrint("Built Sym tree");
351 sp.mungeSymboltree();
352 this.timerPrint("Munged Sym tree");
353 print(sp.warnings.join("\n"));
356 //var out = CompressWhite(new TokenStream(toks), this, true); // do not kill whitespace..
357 var out = CompressWhite(new TokenStream(toks), this, false);
358 this.timerPrint("Compressed");
365 timerPrint: function (str) {
366 var ntime = new Date() * 1;
367 var tdif = ntime -this.timer;
369 print('['+tdif+']'+str);
374 * Translation concept...
375 * -> replace text strings with _T....
376 * -> this file will need inserting at the start of the application....
377 * -> we need to generate 2 files,
378 * -> a reference used to do the translation, and the _T file..
382 writeTranslateFile : function(fn, minfile, toks)
387 toks.forEach(function (t) {
388 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
389 var sval = t.data.substring(1,t.data.length-1);
390 var ffn = fn.substring(_this.prefix.length);
391 map[sval] = _this.md5(ffn + '-' + sval);
395 var transfile = minfile + '.lang.trans';
396 var transmd5 = minfile + '.lang';
397 print("writeTranslateFile " + transfile);
400 if (File.exists(transfile)) {
401 File.remove(transfile);
403 if (File.exists(transmd5)) {
404 File.remove(transmd5);
406 for(v in map) { i++; break };
408 return; // no strings in file...
410 var ffn = fn.substring(this.prefix.length);
413 File.write(transfile, "\n'" + ffn + "' : {");
417 File.write(transmd5, '');
419 File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
421 // strings are raw... - as the where encoded to start with!!!
422 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
424 File.append(transfile, "\n},"); // always one trailing..
428 md5 : function (string)
431 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
434 stringHandler : function(tok)
436 //print("STRING HANDLER");
437 // callback when outputing compressed file,
439 if (!this.translateJSON) {
440 // print("TURNED OFF");
443 if (tok.name == 'SINGLE_QUOTE') {
447 var sval = data.substring(1,data.length-1);
448 // we do not clean up... quoting here!??!!?!?!?!?
451 // blank with tabs or spaces..
452 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
453 // return tok.outData;
456 var sval = tok.data.substring(1,data.length-1);
457 var fn = this.activeFile.substring(this.prefix.length);
460 return '_T["' + this.md5(fn + '-' + sval) + '"]';