1 // <script type="text/javascript">
2 const XObject = imports.XObject.XObject;
3 const File = imports.File.File;
5 const TextStream = imports.JSDOC.TextStream.TextStream ;
6 const TokenReader = imports.TokenReader.TokenReader;
7 const ScopeParser = imports.ScopeParser.ScopeParser;
8 const TokenStream = imports.TokenStream.TokenStream;
9 const CompressWhite = imports.CompressWhite.CompressWhite;
10 const Collapse = imports.Collapse.Collapse;
12 const GLib = imports.gi.GLib;
13 const Gio = imports.gi.Gio;
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 debugTranslateTarget : "/tmp/output.translate.js", // merged with translation
33 translateJSON: "/tmp/translate.json",
38 "/location/of/temp_batch_dir",
39 "/location/of/output-compacted-file.js",
40 "/location/of/output-debug-merged-file.js"
45 * Notes for improving compacting:
46 * if you add a jsdoc comment
53 * directly before an eval statement, it will compress all the code around the eval,
54 * and not rename the variables 'avarname'
56 * Dont try running this on a merged uncompressed large file - it's used to be horrifically slow. not sure about now..
57 * Best to use lot's of small classes, and use it to merge, as it will cache the compaction
61 * Notes for translation
62 * - translation relies on you using double quotes for strings if they need translating
63 * - single quoted strings are ignored.
65 * Generation of indexFiles
66 * - translateIndex = the indexfile
73 const Packer = function(cfg)
76 XObject.extend(this, cfg);
78 if (this.srcfiles && this.srcfiles.length) {
79 this.srcfiles.forEach(function(f) {
80 _this.loadSourceFile(f);
92 function dateString(d){
93 function pad(n){return n<10 ? '0'+n : n}
94 return d.getFullYear() +
105 this.files.forEach(function(f) {
106 version = Math.max(File.mtime(f), version);
108 var version = dateString(new Date(version));
110 var dirname = GLib.path_get_dirname(this.files[0]);
111 var outname = this.module ? this.module : GLib.path_get_basename(dirname);
112 this.target = dirname + '/compiled/' + outname + '-' + version + '.js';
113 if (File.exists(this.target)) {
114 print("Target file already exists: " + this.target);
117 this.prefix = dirname +'/';
118 this.translateJSON = dirname + '/compiled/_translation_.js';
122 print(this.translateJSON);
123 this.timer = new Date() * 1;
132 * @cfg {String} srcfiles file containing a list of files/or classes to use.
137 * @cfg {Array} files list of files to compress (must be full path)
141 * @cfg {String} target to write files to - must be full path.
145 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
146 * and enables translation toolkit.
150 * @cfg {String} module used with autoBuild to force a file name
154 * @cfg {String} debugTarget target to write files debug version to (uncompacted)- must be full path.
156 debugTarget : '', // merged file without compression.
158 * @cfg {String} debugTranslateTarget target to write files debug version
159 * to (uncompacted) but with translation- must be full path.
162 debugTranslateTarget : '',
165 * @cfg {String} tmpDir (optional) where to put the temporary files.
166 * if you set this, then files will not be cleaned up
170 translateJSON : '', // json based list of strings in all files.
173 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
174 * Defaults to false if you set tmpDir, otherwise true.
178 * @cfg {Boolean} keepWhite (optional) do not remove white space in output.
179 * usefull for debugging compressed files.
185 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
186 * Calculating md5 of filename
189 out : '', // if no target is specified - then this will contain the result
192 * load a dependancy list -f option
193 * @param {String} srcfile sourcefile to parse
197 loadSourceFile : function(srcfile)
199 var lines = File.read(srcfile).split("\n");
201 lines.forEach(function(f) {
203 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
206 if (/\.js$/.test(f)) {
207 _this.files.push( f);
212 //println("ADD"+ f.replace(/\./g, '/'));
213 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
214 if (_this.files.indexOf(f) > -1) {
217 _this.files.push( add );
223 packAll : function() // do the packing (run from constructor)
226 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
227 //File.write(this.transfile, "");
229 File.write(this.target, "");
232 if (this.debugTarget) {
233 File.write(this.debugTarget, "");
235 if (this.debugTranslateTarget) {
236 File.write(this.debugTarget, "");
239 for(var i=0; i < this.files.length; i++) {
240 var file = this.files[i];
242 print("reading " +file );
243 if (!File.isFile(file)) {
244 print("SKIP (is not a file) " + file);
250 if (this.debugTarget) {
251 File.append(this.debugTarget, File.read(file));
253 // it's a good idea to check with 0 compression to see if the code can parse!!
256 //File.append(dout, str +"\n");
260 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
263 // let's see if we have a min file already?
264 // this might happen if tmpDir is set ..
265 if (true && File.exists(minfile)) {
266 var mt = File.mtime(minfile);
267 var ot = File.mtime(file);
268 print("compare : " + mt + "=>" + ot);
276 print("COMPRESSING ");
277 //var codeComp = pack(str, 10, 0, 0);
278 if (File.exists(minfile)) {
279 File.remove(minfile);
281 var str = File.read(file);
284 var str = this.pack(str, file, minfile);
291 // if we are translating, write the translations strings at the top
294 if (this.translateJSON) {
297 print("MERGING LANGUAGE");
298 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
300 File.write(this.target, out);
305 File.write(this.translateJSON, "");
306 for(var i=0; i < this.files.length; i++) {
307 var file = this.files[i];
308 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
309 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
310 if (File.exists(transmd5)) {
311 var str = File.read(transmd5);
314 File.append(this.target, str + "\n");
316 this.out += str + "\n";
321 File.remove(transmd5);
324 if (File.exists(transfile)) {
325 var str = File.read(transfile);
327 File.append(this.translateJSON, str);
330 File.remove(transfile);
338 print("MERGING SOURCE");
340 for(var i=0; i < this.files.length; i++) {
341 var file = this.files[i];
342 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
345 if (!File.exists(minfile)) {
348 var str = File.read(minfile);
349 print("using MIN FILE "+ minfile);
352 File.append(this.target, '//' + file + "\n");
353 File.append(this.target, str + "\n");
355 this.out += '//' + file + "\n";
356 this.out += str + "\n";
361 File.remove(minfile);
365 print("Output file: " + this.target);
366 if (this.debugTarget) print("Output debug file: " + this.debugTarget);
373 * Core packing routine for a file
375 * @param str - str source text..
376 * @param fn - filename (for reference?)
377 * @param minfile - min file location...
381 pack : function (str,fn,minfile)
384 var tr = new TokenReader( {
389 collapseWhite : false,
392 this.timerPrint("START" + fn);
394 // we can load translation map here...
396 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
398 // at this point we can write a language file...
399 if (this.translateJSON) {
401 this.writeTranslateFile(fn, minfile, toks);
404 this.activeFile = fn;
406 // and replace if we are generating a different language..
408 this.timerPrint("Tokenized tokens:" + toks.length);
409 //var ts = new TokenStream(toks);
410 //print(JSON.stringify(toks, null,4 )); Seed.quit();
411 var ts = new Collapse(toks);
412 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
414 var sp = new ScopeParser(ts);
415 this.timerPrint("Converted to Parser");
417 sp.buildSymbolTree();
418 this.timerPrint("Built Sym tree");
419 sp.mungeSymboltree();
420 this.timerPrint("Munged Sym tree");
421 print(sp.warnings.join("\n"));
422 this.timerPrint("Compressed");
424 var out = CompressWhite(new TokenStream(toks), this, this.keepWhite); // do not kill whitespace..
427 this.timerPrint("Compressed");
430 File.write(minfile, out);
431 this.timerPrint("Write (" + out.length + "bytes) " + minfile);
440 timerPrint: function (str) {
441 var ntime = new Date() * 1;
442 var tdif = ntime -this.timer;
444 print('['+tdif+']'+str);
449 * Translation concept...
450 * -> replace text strings with _T....
451 * -> this file will need inserting at the start of the application....
452 * -> we need to generate 2 files,
453 * -> a reference used to do the translation, and the _T file..
456 * We store the trsum on the token...
460 writeTranslateFile : function(fn, minfile, toks)
463 var map = {}; // 'string=> md5sum'
468 var tokfind = function (j,dir) {
470 if ((dir < 0) && (j < 0)) {
473 if ((dir > 0) && (j >= toks.length)) {
477 if (toks[j].type != 'WHIT') {
486 for (var i=0;i<toks.length;i++) {
489 if (t.type != 'STRN') {
492 if (t.name != 'DOUBLE_QUOTE') {
496 last = tokfind(i,-1);
497 next = tokfind(i,+1);
499 // we have to ignore key values on objects
502 // last == '{' or ',' and
506 next.type == 'PUNC' &&
509 last.type == 'PUNC' &&
510 (last.data == ',' || last.data == '{')
512 continue; // found object key... - we can not translate these
515 var sval = t.data.substring(1,t.data.length-1);
516 var ffn = fn.substring(_this.prefix.length);
518 t.trsum = _this.md5(ffn + '-' + sval);
526 var transfile = minfile + '.lang.trans';
527 var transmd5 = minfile + '.lang';
528 print("writeTranslateFile " + transfile);
531 if (File.exists(transfile)) {
532 File.remove(transfile);
534 if (File.exists(transmd5)) {
535 File.remove(transmd5);
537 for(v in map) { i++; break };
539 return; // no strings in file...
541 var ffn = fn.substring(this.prefix.length);
544 File.write(transfile, "\n'" + ffn + "' : {");
548 File.write(transmd5, '');
553 File.append(transfile, l + "\n\t\"" + v + "\" : \"" + v +"\"");
555 // strings are raw... - as the where encoded to start with!!!
556 // so we should not need to encode them again.. - just wrap with "
557 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
559 File.append(transfile, "\n},"); // always one trailing..
563 md5 : function (string)
566 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
569 stringHandler : function(tok)
571 //print("STRING HANDLER");
572 // callback when outputing compressed file,
574 if (!this.translateJSON) {
575 // print("TURNED OFF");
578 if (tok.name == 'SINGLE_QUOTE') {
582 if (typeof(tok.trsum) == 'undefined') {
586 return '_T["' + tok.trsum + '"]';
588 var sval = data.substring(1,data.length-1);
589 // we do not clean up... quoting here!??!!?!?!?!?
592 // blank with tabs or spaces..
593 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
594 // return tok.outData;
597 var sval = tok.data.substring(1,data.length-1);
598 var fn = this.activeFile.substring(this.prefix.length);
601 return '_T["' + this.md5(fn + '-' + sval) + '"]';