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;
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 this.files.forEach(function(f) {
91 version = Math.max(File.mtime(f), version);
93 var dirname = GLib.path_get_dirname(this.files[0]);
94 var outname = this.module ? this.module : GLib.path_get_basename(dirname);
95 this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
96 if (File.exists(this.target)) {
97 print("Target file already exists");
100 this.prefix = dirname +'/';
101 this.translateJSON = dirname + '/compiled/_translation_.js';
105 print(this.translateJSON);
106 this.timer = new Date() * 1;
115 * @cfg {String} srcfiles file containing a list of files/or classes to use.
120 * @cfg {Array} files list of files to compress (must be full path)
124 * @cfg {String} target to write files to - must be full path.
128 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
129 * and enables translation toolkit.
133 * @cfg {String} module used with autoBuild to force a file name
137 * @cfg {String} debugTargettarget to write files debug version to (uncompacted)- must be full path.
139 debugTarget : '', // merged file without compression.
141 * @cfg {String} tmpDir (optional) where to put the temporary files.
142 * if you set this, then files will not be cleaned up
146 translateJSON : '', // json based list of strings in all files.
149 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
150 * Defaults to false if you set tmpDir, otherwise true.
154 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
155 * usefull for debugging compressed files.
161 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
162 * Calculating md5 of filename
165 out : '', // if no target is specified - then this will contain the result
168 * load a dependancy list -f option
169 * @param {String} srcfile sourcefile to parse
173 loadSourceFile : function(srcfile)
175 var lines = File.read(srcfile).split("\n");
177 lines.forEach(function(f) {
179 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
182 if (/\.js$/.test(f)) {
183 _this.files.push( f);
188 //println("ADD"+ f.replace(/\./g, '/'));
189 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
190 if (_this.files.indexOf(f) > -1) {
193 _this.files.push( add );
199 packAll : function() // do the packing (run from constructor)
202 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
203 //File.write(this.transfile, "");
205 File.write(this.target, "");
208 if (this.debugTarget) {
209 File.write(this.debugTarget, "");
212 for(var i=0; i < this.files.length; i++) {
213 var file = this.files[i];
215 print("reading " +file );
216 if (!File.isFile(file)) {
217 print("SKIP (is not a file) " + file);
221 if (this.debugTarget) {
222 File.append(this.debugTarget, File.read(file));
224 // it's a good idea to check with 0 compression to see if the code can parse!!
227 //File.append(dout, str +"\n");
231 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
234 // let's see if we have a min file already?
235 // this might happen if tmpDir is set ..
236 if (true && File.exists(minfile)) {
237 var mt = File.mtime(minfile);
238 var ot = File.mtime(file);
239 print("compare : " + mt + "=>" + ot);
243 // then the min'files time is > than original..
244 var str = File.read(minfile);
245 print("using MIN FILE "+ minfile);
247 File.append(outpath, str + "\n");
256 print("COMPRESSING ");
257 //var codeComp = pack(str, 10, 0, 0);
258 if (File.exists(minfile)) {
259 File.remove(minfile);
261 var str = File.read(file);
262 var str = this.pack(str, file, minfile);
264 File.write(minfile, str);
270 if (this.translateJSON) {
273 print("MERGING LANGUAGE");
274 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
276 File.write(this.target, out);
283 File.write(this.translateJSON, "");
284 for(var i=0; i < this.files.length; i++) {
285 var file = this.files[i];
286 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
287 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
288 if (File.exists(transmd5)) {
289 var str = File.read(transmd5);
292 File.append(this.target, str + "\n");
294 this.out += str + "\n";
299 File.remove(transmd5);
302 if (File.exists(transfile)) {
303 var str = File.read(transfile);
305 File.append(this.translateJSON, str);
308 File.remove(transfile);
316 print("MERGING SOURCE");
318 for(var i=0; i < this.files.length; i++) {
319 var file = this.files[i];
320 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
323 if (!File.exists(minfile)) {
326 var str = File.read(minfile);
327 print("using MIN FILE "+ minfile);
330 File.append(this.target, str + "\n");
332 this.out += str + "\n";
337 File.remove(minfile);
347 * Core packing routine for a file
349 * @param str - str source text..
350 * @param fn - filename (for reference?)
351 * @param minfile - min file location...
355 pack : function (str,fn,minfile)
358 var tr = new TokenReader( {
365 this.timerPrint("START" + fn);
367 print(JSON.stringify(tr null ,4 ));
368 // we can load translation map here...
370 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
372 // at this point we can write a language file...
373 if (this.translateJSON) {
375 this.writeTranslateFile(fn, minfile, toks);
378 this.activeFile = fn;
380 // and replace if we are generating a different language..
382 this.timerPrint("Tokenized");
383 //var ts = new TokenStream(toks);
384 //print(JSON.stringify(toks, null,4 )); Seed.quit();
385 var ts = new Collapse(toks);
386 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
388 var sp = new ScopeParser(ts);
389 this.timerPrint("Converted to Parser");
391 sp.buildSymbolTree();
392 this.timerPrint("Built Sym tree");
393 sp.mungeSymboltree();
394 this.timerPrint("Munged Sym tree");
395 print(sp.warnings.join("\n"));
398 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
400 this.timerPrint("Compressed");
407 timerPrint: function (str) {
408 var ntime = new Date() * 1;
409 var tdif = ntime -this.timer;
411 print('['+tdif+']'+str);
416 * Translation concept...
417 * -> replace text strings with _T....
418 * -> this file will need inserting at the start of the application....
419 * -> we need to generate 2 files,
420 * -> a reference used to do the translation, and the _T file..
424 writeTranslateFile : function(fn, minfile, toks)
429 toks.forEach(function (t) {
430 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
431 var sval = t.data.substring(1,t.data.length-1);
432 var ffn = fn.substring(_this.prefix.length);
433 map[sval] = _this.md5(ffn + '-' + sval);
437 var transfile = minfile + '.lang.trans';
438 var transmd5 = minfile + '.lang';
439 print("writeTranslateFile " + transfile);
442 if (File.exists(transfile)) {
443 File.remove(transfile);
445 if (File.exists(transmd5)) {
446 File.remove(transmd5);
448 for(v in map) { i++; break };
450 return; // no strings in file...
452 var ffn = fn.substring(this.prefix.length);
455 File.write(transfile, "\n'" + ffn + "' : {");
459 File.write(transmd5, '');
464 File.append(transfile, l + "\n\t" + JSON.stringify(v) + " : " + JSON.stringify(v));
466 // strings are raw... - as the where encoded to start with!!!
467 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]='+JSON.stringify(v)+";\n");
469 File.append(transfile, "\n},"); // always one trailing..
473 md5 : function (string)
476 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
479 stringHandler : function(tok)
481 //print("STRING HANDLER");
482 // callback when outputing compressed file,
484 if (!this.translateJSON) {
485 // print("TURNED OFF");
488 if (tok.name == 'SINGLE_QUOTE') {
492 var sval = data.substring(1,data.length-1);
493 // we do not clean up... quoting here!??!!?!?!?!?
496 // blank with tabs or spaces..
497 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
498 // return tok.outData;
501 var sval = tok.data.substring(1,data.length-1);
502 var fn = this.activeFile.substring(this.prefix.length);
505 return '_T["' + this.md5(fn + '-' + sval) + '"]';