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);
91 this.timer = new Date() * 1;
98 * @prop srcfiles {String} file containing a list of files/or classes to use.
103 * @prop files {Array} list of files to compress (must be full path)
107 * @cfg {String} target to write files to - must be full path.
111 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
112 * and enables translation toolkit.
116 * @prop debugTarget {String} target to write files debug version to (uncompacted)- must be full path.
118 debugTarget : '', // merged file without compression.
120 * @prop tmpDir {String} (optional) where to put the temporary files.
121 * if you set this, then files will not be cleaned up
125 translateJSON : '', // json based list of strings in all files.
128 * @prop cleanup {Boolean} (optional) clean up temp files after done -
129 * Defaults to false if you set tmpDir, otherwise true.
134 * @prop prefix {String} (optional) prefix of directory to be stripped of when
135 * Calculating md5 of filename
138 out : '', // if no target is specified - then this will contain the result
141 loadSourceFile : function(srcfile)
143 var lines = File.read(srcfile).split("\n");
145 lines.forEach(function(f) {
147 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
150 if (/\.js$/.test(f)) {
151 _this.files.push( f);
156 //println("ADD"+ f.replace(/\./g, '/'));
157 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
158 if (_this.files.indexOf(f) > -1) {
161 _this.files.push( add );
167 packAll : function() // do the packing (run from constructor)
170 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
171 //File.write(this.transfile, "");
173 File.write(this.target, "");
176 if (this.debugTarget) {
177 File.write(this.debugTarget, "");
180 for(var i=0; i < this.files.length; i++) {
181 var file = this.files[i];
183 print("reading " +file );
184 if (!File.isFile(file)) {
185 print("SKIP (is not a file) " + file);
189 if (this.debugTarget) {
190 File.append(this.debugTarget, File.read(file));
192 // it's a good idea to check with 0 compression to see if the code can parse!!
195 //File.append(dout, str +"\n");
199 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
202 // let's see if we have a min file already?
203 // this might happen if tmpDir is set ..
204 if (true && File.exists(minfile)) {
205 var mt = File.mtime(minfile);
206 var ot = File.mtime(file);
207 print("compare : " + mt + "=>" + ot);
211 // then the min'files time is > than original..
212 var str = File.read(minfile);
213 print("using MIN FILE "+ minfile);
215 File.append(outpath, str + "\n");
224 print("COMPRESSING ");
225 //var codeComp = pack(str, 10, 0, 0);
226 if (File.exists(minfile)) {
227 File.remove(minfile);
229 var str = File.read(file);
230 var str = this.pack(str, file, minfile);
232 File.write(minfile, str);
238 if (this.translateJSON) {
241 print("MERGING LANGUAGE");
242 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
244 File.write(this.target, out);
251 File.write(this.translateJSON, "");
252 for(var i=0; i < this.files.length; i++) {
253 var file = this.files[i];
254 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
255 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
256 if (File.exists(transmd5)) {
257 var str = File.read(transmd5);
260 File.append(this.target, str + "\n");
262 this.out += str + "\n";
267 File.remove(transmd5);
270 if (File.exists(transfile)) {
271 var str = File.read(transfile);
273 File.append(this.translateJSON, str);
276 File.remove(transfile);
284 print("MERGING SOURCE");
286 for(var i=0; i < this.files.length; i++) {
287 var file = this.files[i];
288 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
291 if (!File.exists(minfile)) {
294 var str = File.read(minfile);
295 print("using MIN FILE "+ minfile);
298 File.append(this.target, str + "\n");
300 this.out += str + "\n";
305 File.remove(minfile);
315 * Core packing routine for a file
317 * @param str - str source text..
318 * @param fn - filename (for reference?)
319 * @param minfile - min file location...
323 pack : function (str,fn,minfile)
326 var tr = new TokenReader( {
331 collapseWhite : false
333 this.timerPrint("START" + fn);
335 // we can load translation map here...
337 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
339 // at this point we can write a language file...
340 if (this.translateJSON) {
342 this.writeTranslateFile(fn, minfile, toks);
345 this.activeFile = fn;
347 // and replace if we are generating a different language..
349 this.timerPrint("Tokenized");
350 //var ts = new TokenStream(toks);
351 //print(JSON.stringify(toks, null,4 )); Seed.quit();
352 var ts = new Collapse(toks);
353 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
355 var sp = new ScopeParser(ts);
356 this.timerPrint("Converted to Parser");
358 sp.buildSymbolTree();
359 this.timerPrint("Built Sym tree");
360 sp.mungeSymboltree();
361 this.timerPrint("Munged Sym tree");
362 print(sp.warnings.join("\n"));
365 //var out = CompressWhite(new TokenStream(toks), this, true); // do not kill whitespace..
366 var out = CompressWhite(new TokenStream(toks), this, false);
367 this.timerPrint("Compressed");
374 timerPrint: function (str) {
375 var ntime = new Date() * 1;
376 var tdif = ntime -this.timer;
378 print('['+tdif+']'+str);
383 * Translation concept...
384 * -> replace text strings with _T....
385 * -> this file will need inserting at the start of the application....
386 * -> we need to generate 2 files,
387 * -> a reference used to do the translation, and the _T file..
391 writeTranslateFile : function(fn, minfile, toks)
396 toks.forEach(function (t) {
397 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
398 var sval = t.data.substring(1,t.data.length-1);
399 var ffn = fn.substring(_this.prefix.length);
400 map[sval] = _this.md5(ffn + '-' + sval);
404 var transfile = minfile + '.lang.trans';
405 var transmd5 = minfile + '.lang';
406 print("writeTranslateFile " + transfile);
409 if (File.exists(transfile)) {
410 File.remove(transfile);
412 if (File.exists(transmd5)) {
413 File.remove(transmd5);
415 for(v in map) { i++; break };
417 return; // no strings in file...
419 var ffn = fn.substring(this.prefix.length);
422 File.write(transfile, "\n'" + ffn + "' : {");
426 File.write(transmd5, '');
428 File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
430 // strings are raw... - as the where encoded to start with!!!
431 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
433 File.append(transfile, "\n},"); // always one trailing..
437 md5 : function (string)
440 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
443 stringHandler : function(tok)
445 //print("STRING HANDLER");
446 // callback when outputing compressed file,
448 if (!this.translateJSON) {
449 // print("TURNED OFF");
452 if (tok.name == 'SINGLE_QUOTE') {
456 var sval = data.substring(1,data.length-1);
457 // we do not clean up... quoting here!??!!?!?!?!?
460 // blank with tabs or spaces..
461 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
462 // return tok.outData;
465 var sval = tok.data.substring(1,data.length-1);
466 var fn = this.activeFile.substring(this.prefix.length);
469 return '_T["' + this.md5(fn + '-' + sval) + '"]';