1 // <script type="text/javascript">
2 XObject = imports.XObject.XObject;
3 File = imports.File.File;
5 TextStream = imports.TextStream ? imports.TextStream.TextStream : imports.JSDOC.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;
25 Packer = imports['JSDOC/Packer.js'].Packer;
28 files : [ "/location/of/file1.js", "/location/of/file2.js", ... ],
29 target : "/tmp/output.js",
30 debugTarget : "/tmp/output.debug.js", // merged file without compression.
31 translateJSON: "/tmp/translate.json",
36 "/location/of/temp_batch_dir",
37 "/location/of/output-compacted-file.js",
38 "/location/of/output-debug-merged-file.js"
43 * Notes for improving compacting:
44 * if you add a jsdoc comment
51 * directly before an eval statement, it will compress all the code around the eval,
52 * and not rename the variables 'avarname'
54 * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
55 * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
59 * Notes for translation
60 * - translation relies on you using double quotes for strings if they need translating
61 * - single quoted strings are ignored.
63 * Generation of indexFiles
64 * - translateIndex = the indexfile
71 Packer = function(cfg)
74 XObject.extend(this, cfg);
76 if (this.srcfiles && this.srcfiles.length) {
77 this.srcfiles.forEach(function(f) {
78 _this.loadSourceFile(f);
90 function dateString(d){
91 function pad(n){return n<10 ? '0'+n : n}
92 return d.getFullYear() +
103 this.files.forEach(function(f) {
104 version = Math.max(File.mtime(f), version);
106 var version = dateString(new Date(version));
108 var dirname = GLib.path_get_dirname(this.files[0]);
109 var outname = this.module ? this.module : GLib.path_get_basename(dirname);
110 this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
111 if (File.exists(this.target)) {
112 print("Target file already exists: " + this.target);
115 this.prefix = dirname +'/';
116 this.translateJSON = dirname + '/compiled/_translation_.js';
120 print(this.translateJSON);
121 this.timer = new Date() * 1;
130 * @cfg {String} srcfiles file containing a list of files/or classes to use.
135 * @cfg {Array} files list of files to compress (must be full path)
139 * @cfg {String} target to write files to - must be full path.
143 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
144 * and enables translation toolkit.
148 * @cfg {String} module used with autoBuild to force a file name
152 * @cfg {String} debugTargettarget to write files debug version to (uncompacted)- must be full path.
154 debugTarget : '', // merged file without compression.
156 * @cfg {String} tmpDir (optional) where to put the temporary files.
157 * if you set this, then files will not be cleaned up
161 translateJSON : '', // json based list of strings in all files.
164 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
165 * Defaults to false if you set tmpDir, otherwise true.
169 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
170 * usefull for debugging compressed files.
176 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
177 * Calculating md5 of filename
180 out : '', // if no target is specified - then this will contain the result
183 * load a dependancy list -f option
184 * @param {String} srcfile sourcefile to parse
188 loadSourceFile : function(srcfile)
190 var lines = File.read(srcfile).split("\n");
192 lines.forEach(function(f) {
194 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
197 if (/\.js$/.test(f)) {
198 _this.files.push( f);
203 //println("ADD"+ f.replace(/\./g, '/'));
204 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
205 if (_this.files.indexOf(f) > -1) {
208 _this.files.push( add );
214 packAll : function() // do the packing (run from constructor)
217 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
218 //File.write(this.transfile, "");
220 File.write(this.target, "");
223 if (this.debugTarget) {
224 File.write(this.debugTarget, "");
227 for(var i=0; i < this.files.length; i++) {
228 var file = this.files[i];
230 print("reading " +file );
231 if (!File.isFile(file)) {
232 print("SKIP (is not a file) " + file);
236 if (this.debugTarget) {
237 File.append(this.debugTarget, File.read(file));
239 // it's a good idea to check with 0 compression to see if the code can parse!!
242 //File.append(dout, str +"\n");
246 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
249 // let's see if we have a min file already?
250 // this might happen if tmpDir is set ..
251 if (true && File.exists(minfile)) {
252 var mt = File.mtime(minfile);
253 var ot = File.mtime(file);
254 print("compare : " + mt + "=>" + ot);
258 // then the min'files time is > than original..
259 var str = File.read(minfile);
260 print("using MIN FILE "+ minfile);
262 File.append(outpath, str + "\n");
271 print("COMPRESSING ");
272 //var codeComp = pack(str, 10, 0, 0);
273 if (File.exists(minfile)) {
274 File.remove(minfile);
276 var str = File.read(file);
277 var str = this.pack(str, file, minfile);
279 File.write(minfile, str);
285 if (this.translateJSON) {
288 print("MERGING LANGUAGE");
289 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
291 File.write(this.target, out);
298 File.write(this.translateJSON, "");
299 for(var i=0; i < this.files.length; i++) {
300 var file = this.files[i];
301 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
302 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
303 if (File.exists(transmd5)) {
304 var str = File.read(transmd5);
307 File.append(this.target, str + "\n");
309 this.out += str + "\n";
314 File.remove(transmd5);
317 if (File.exists(transfile)) {
318 var str = File.read(transfile);
320 File.append(this.translateJSON, str);
323 File.remove(transfile);
331 print("MERGING SOURCE");
333 for(var i=0; i < this.files.length; i++) {
334 var file = this.files[i];
335 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
338 if (!File.exists(minfile)) {
341 var str = File.read(minfile);
342 print("using MIN FILE "+ minfile);
345 File.append(this.target, str + "\n");
347 this.out += str + "\n";
352 File.remove(minfile);
356 print("Output file: " + this.target);
357 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
364 * Core packing routine for a file
366 * @param str - str source text..
367 * @param fn - filename (for reference?)
368 * @param minfile - min file location...
372 pack : function (str,fn,minfile)
375 var tr = new TokenReader( {
380 collapseWhite : false,
383 this.timerPrint("START" + fn);
385 // we can load translation map here...
387 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
389 // at this point we can write a language file...
390 if (this.translateJSON) {
392 this.writeTranslateFile(fn, minfile, toks);
395 this.activeFile = fn;
397 // and replace if we are generating a different language..
399 this.timerPrint("Tokenized");
400 //var ts = new TokenStream(toks);
401 //print(JSON.stringify(toks, null,4 )); Seed.quit();
402 var ts = new Collapse(toks);
403 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
405 var sp = new ScopeParser(ts);
406 this.timerPrint("Converted to Parser");
408 sp.buildSymbolTree();
409 this.timerPrint("Built Sym tree");
410 sp.mungeSymboltree();
411 this.timerPrint("Munged Sym tree");
412 print(sp.warnings.join("\n"));
415 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
418 this.timerPrint("Compressed");
425 timerPrint: function (str) {
426 var ntime = new Date() * 1;
427 var tdif = ntime -this.timer;
429 print('['+tdif+']'+str);
434 * Translation concept...
435 * -> replace text strings with _T....
436 * -> this file will need inserting at the start of the application....
437 * -> we need to generate 2 files,
438 * -> a reference used to do the translation, and the _T file..
442 writeTranslateFile : function(fn, minfile, toks)
447 toks.forEach(function (t) {
448 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
449 var sval = t.data.substring(1,t.data.length-1);
450 var ffn = fn.substring(_this.prefix.length);
451 map[sval] = _this.md5(ffn + '-' + sval);
455 var transfile = minfile + '.lang.trans';
456 var transmd5 = minfile + '.lang';
457 print("writeTranslateFile " + transfile);
460 if (File.exists(transfile)) {
461 File.remove(transfile);
463 if (File.exists(transmd5)) {
464 File.remove(transmd5);
466 for(v in map) { i++; break };
468 return; // no strings in file...
470 var ffn = fn.substring(this.prefix.length);
473 File.write(transfile, "\n'" + ffn + "' : {");
477 File.write(transmd5, '');
482 File.append(transfile, l + "\n\t" + JSON.stringify(v) + " : " + JSON.stringify(v));
484 // strings are raw... - as the where encoded to start with!!!
485 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]='+JSON.stringify(v)+";\n");
487 File.append(transfile, "\n},"); // always one trailing..
491 md5 : function (string)
494 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
497 stringHandler : function(tok)
499 //print("STRING HANDLER");
500 // callback when outputing compressed file,
502 if (!this.translateJSON) {
503 // print("TURNED OFF");
506 if (tok.name == 'SINGLE_QUOTE') {
510 var sval = data.substring(1,data.length-1);
511 // we do not clean up... quoting here!??!!?!?!?!?
514 // blank with tabs or spaces..
515 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
516 // return tok.outData;
519 var sval = tok.data.substring(1,data.length-1);
520 var fn = this.activeFile.substring(this.prefix.length);
523 return '_T["' + this.md5(fn + '-' + sval) + '"]';