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);
89 function dateString(d){
90 function pad(n){return n<10 ? '0'+n : n}
91 return d.getFullYear() +
102 this.files.forEach(function(f) {
103 version = Math.max(File.mtime(f), version);
105 var version = dateString(new Date(version));
107 var dirname = GLib.path_get_dirname(this.files[0]);
108 var outname = this.module ? this.module : GLib.path_get_basename(dirname);
109 this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
110 if (File.exists(this.target)) {
111 print("Target file already exists: " + this.target);
114 this.prefix = dirname +'/';
115 this.translateJSON = dirname + '/compiled/_translation_.js';
119 print(this.translateJSON);
120 this.timer = new Date() * 1;
129 * @prop srcfiles {String} file containing a list of files/or classes to use.
134 * @prop files {Array} list of files to compress (must be full path)
138 * @prop target {String} target to write files to - must be full path.
142 * @prop debugTarget {String} target to write files debug version to (uncompacted)- must be full path.
144 debugTarget : '', // merged file without compression.
146 * @prop tmpDir {String} (optional) where to put the temporary files.
147 * if you set this, then files will not be cleaned up
151 translateJSON : '', // json based list of strings in all files.
154 * @prop cleanup {Boolean} (optional) clean up temp files after done -
155 * Defaults to false if you set tmpDir, otherwise true.
160 * @prop prefix {String} (optional) prefix of directory to be stripped of when
161 * Calculating md5 of filename
164 out : '', // if no target is specified - then this will contain the result
167 loadSourceFile : function(srcfile)
169 var lines = File.read(srcfile).split("\n");
171 lines.forEach(function(f) {
173 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
176 if (/\.js$/.test(f)) {
177 _this.files.push( f);
182 //println("ADD"+ f.replace(/\./g, '/'));
183 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
184 if (_this.files.indexOf(f) > -1) {
187 _this.files.push( add );
193 packAll : function() // do the packing (run from constructor)
196 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
197 //File.write(this.transfile, "");
199 File.write(this.target, "");
202 if (this.debugTarget) {
203 File.write(this.debugTarget, "");
206 for(var i=0; i < this.files.length; i++) {
207 var file = this.files[i];
209 print("reading " +file );
210 if (!File.isFile(file)) {
211 print("SKIP (is not a file) " + file);
215 if (this.debugTarget) {
216 File.append(this.debugTarget, File.read(file));
218 // it's a good idea to check with 0 compression to see if the code can parse!!
221 //File.append(dout, str +"\n");
225 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
228 // let's see if we have a min file already?
229 // this might happen if tmpDir is set ..
230 if (true && File.exists(minfile)) {
231 var mt = File.mtime(minfile);
232 var ot = File.mtime(file);
233 print("compare : " + mt + "=>" + ot);
237 // then the min'files time is > than original..
238 var str = File.read(minfile);
239 print("using MIN FILE "+ minfile);
241 File.append(outpath, str + "\n");
250 print("COMPRESSING ");
251 //var codeComp = pack(str, 10, 0, 0);
252 if (File.exists(minfile)) {
253 File.remove(minfile);
255 var str = File.read(file);
256 var str = this.pack(str, file, minfile);
258 File.write(minfile, str);
264 if (this.translateJSON) {
267 print("MERGING LANGUAGE");
268 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
270 File.write(this.target, out);
277 File.write(this.translateJSON, "");
278 for(var i=0; i < this.files.length; i++) {
279 var file = this.files[i];
280 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
281 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
282 if (File.exists(transmd5)) {
283 var str = File.read(transmd5);
286 File.append(this.target, str + "\n");
288 this.out += str + "\n";
293 File.remove(transmd5);
296 if (File.exists(transfile)) {
297 var str = File.read(transfile);
299 File.append(this.translateJSON, str);
302 File.remove(transfile);
310 print("MERGING SOURCE");
312 for(var i=0; i < this.files.length; i++) {
313 var file = this.files[i];
314 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
317 if (!File.exists(minfile)) {
320 var str = File.read(minfile);
321 print("using MIN FILE "+ minfile);
324 File.append(this.target, str + "\n");
326 this.out += str + "\n";
331 File.remove(minfile);
341 * Core packing routine for a file
343 * @param str - str source text..
344 * @param fn - filename (for reference?)
345 * @param minfile - min file location...
349 pack : function (str,fn,minfile)
352 var tr = new TokenReader( {
357 collapseWhite : false
359 this.timerPrint("START" + fn);
361 // we can load translation map here...
363 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
365 // at this point we can write a language file...
366 if (this.translateJSON) {
368 this.writeTranslateFile(fn, minfile, toks);
371 this.activeFile = fn;
373 // and replace if we are generating a different language..
375 this.timerPrint("Tokenized");
376 //var ts = new TokenStream(toks);
377 //print(JSON.stringify(toks, null,4 )); Seed.quit();
378 var ts = new Collapse(toks);
379 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
381 var sp = new ScopeParser(ts);
382 this.timerPrint("Converted to Parser");
384 sp.buildSymbolTree();
385 this.timerPrint("Built Sym tree");
386 sp.mungeSymboltree();
387 this.timerPrint("Munged Sym tree");
388 print(sp.warnings.join("\n"));
391 //var out = CompressWhite(new TokenStream(toks), this, true); // do not kill whitespace..
392 var out = CompressWhite(new TokenStream(toks), this, false);
393 this.timerPrint("Compressed");
400 timerPrint: function (str) {
401 var ntime = new Date() * 1;
402 var tdif = ntime -this.timer;
404 print('['+tdif+']'+str);
409 * Translation concept...
410 * -> replace text strings with _T....
411 * -> this file will need inserting at the start of the application....
412 * -> we need to generate 2 files,
413 * -> a reference used to do the translation, and the _T file..
417 writeTranslateFile : function(fn, minfile, toks)
422 toks.forEach(function (t) {
423 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
424 var sval = t.data.substring(1,t.data.length-1);
425 var ffn = fn.substring(_this.prefix.length);
426 map[sval] = _this.md5(ffn + '-' + sval);
430 var transfile = minfile + '.lang.trans';
431 var transmd5 = minfile + '.lang';
432 print("writeTranslateFile " + transfile);
435 if (File.exists(transfile)) {
436 File.remove(transfile);
438 if (File.exists(transmd5)) {
439 File.remove(transmd5);
441 for(v in map) { i++; break };
443 return; // no strings in file...
445 var ffn = fn.substring(this.prefix.length);
448 File.write(transfile, "\n'" + ffn + "' : {");
452 File.write(transmd5, '');
454 File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
456 // strings are raw... - as the where encoded to start with!!!
457 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
459 File.append(transfile, "\n},"); // always one trailing..
463 md5 : function (string)
466 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
469 stringHandler : function(tok)
471 //print("STRING HANDLER");
472 // callback when outputing compressed file,
474 if (!this.translateJSON) {
475 // print("TURNED OFF");
478 if (tok.name == 'SINGLE_QUOTE') {
482 var sval = data.substring(1,data.length-1);
483 // we do not clean up... quoting here!??!!?!?!?!?
486 // blank with tabs or spaces..
487 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
488 // return tok.outData;
491 var sval = tok.data.substring(1,data.length-1);
492 var fn = this.activeFile.substring(this.prefix.length);
495 return '_T["' + this.md5(fn + '-' + sval) + '"]';