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);
76 this.loadSourceFile();
84 this.timer = new Date() * 1;
91 * @prop srcfiles {String} file containing a list of files/or classes to use.
96 * @prop files {Array} list of files to compress (must be full path)
100 * @prop target {String} target to write files to - must be full path.
104 * @prop debugTarget {String} target to write files debug version to (uncompacted)- must be full path.
106 debugTarget : '', // merged file without compression.
108 * @prop tmpDir {String} (optional) where to put the temporary files.
109 * if you set this, then files will not be cleaned up
113 translateJSON : '', // json based list of strings in all files.
116 * @prop cleanup {Boolean} (optional) clean up temp files after done -
117 * Defaults to false if you set tmpDir, otherwise true.
122 * @prop prefix {String} (optional) prefix of directory to be stripped of when
123 * Calculating md5 of filename
126 out : '', // if no target is specified - then this will contain the result
129 loadSourceFile : function()
131 var lines = File.read(this.srcfile).split("\n");
133 lines.forEach(function(f) {
135 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
138 if (/\.js$/.test(f)) {
139 _this.files.push( f);
144 //println("ADD"+ f.replace(/\./g, '/'));
145 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
146 if (_this.files.indexOf(f) > -1) {
149 _this.files.push( add );
155 packAll : function() // do the packing (run from constructor)
158 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
159 //File.write(this.transfile, "");
161 File.write(this.target, "");
164 if (this.debugTarget) {
165 File.write(this.debugTarget, "");
168 for(var i=0; i < this.files.length; i++) {
169 var file = this.files[i];
171 print("reading " +file );
172 if (!File.isFile(file)) {
173 print("SKIP (is not a file) " + file);
177 if (this.debugTarget) {
178 File.append(this.debugTarget, File.read(file));
180 // it's a good idea to check with 0 compression to see if the code can parse!!
183 //File.append(dout, str +"\n");
187 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
190 // let's see if we have a min file already?
191 // this might happen if tmpDir is set ..
192 if (true && File.exists(minfile)) {
193 var mt = File.mtime(minfile);
194 var ot = File.mtime(file);
195 print("compare : " + mt + "=>" + ot);
199 // then the min'files time is > than original..
200 var str = File.read(minfile);
201 print("using MIN FILE "+ minfile);
203 File.append(outpath, str + "\n");
212 print("COMPRESSING ");
213 //var codeComp = pack(str, 10, 0, 0);
214 if (File.exists(minfile)) {
215 File.remove(minfile);
217 var str = File.read(file);
218 var str = this.pack(str, file, minfile);
220 File.write(minfile, str);
226 if (this.translateJSON) {
229 print("MERGING LANGUAGE");
230 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
232 File.write(this.target, out);
239 File.write(this.translateJSON, "");
240 for(var i=0; i < this.files.length; i++) {
241 var file = this.files[i];
242 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
243 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
244 if (File.exists(transmd5)) {
245 var str = File.read(transmd5);
248 File.append(this.target, str + "\n");
250 this.out += str + "\n";
255 File.remove(transmd5);
258 if (File.exists(transfile)) {
259 var str = File.read(transfile);
261 File.append(this.translateJSON, str);
264 File.remove(transfile);
272 print("MERGING SOURCE");
274 for(var i=0; i < this.files.length; i++) {
275 var file = this.files[i];
276 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
279 if (!File.exists(minfile)) {
282 var str = File.read(minfile);
283 print("using MIN FILE "+ minfile);
286 File.append(this.target, str + "\n");
288 this.out += str + "\n";
293 File.remove(minfile);
303 * Core packing routine for a file
305 * @param str - str source text..
306 * @param fn - filename (for reference?)
307 * @param minfile - min file location...
311 pack : function (str,fn,minfile)
314 var tr = new TokenReader( {
319 collapseWhite : false
321 this.timerPrint("START" + fn);
323 // we can load translation map here...
325 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
327 // at this point we can write a language file...
328 if (this.translateJSON) {
330 this.writeTranslateFile(fn, minfile, toks);
333 this.activeFile = fn;
335 // and replace if we are generating a different language..
337 this.timerPrint("Tokenized");
338 //var ts = new TokenStream(toks);
339 //print(JSON.stringify(toks, null,4 )); Seed.quit();
340 var ts = new Collapse(toks);
341 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
343 var sp = new ScopeParser(ts);
344 this.timerPrint("Converted to Parser");
346 sp.buildSymbolTree();
347 this.timerPrint("Built Sym tree");
348 sp.mungeSymboltree();
349 this.timerPrint("Munged Sym tree");
350 print(sp.warnings.join("\n"));
353 //var out = CompressWhite(new TokenStream(toks), this, true); // do not kill whitespace..
354 var out = CompressWhite(new TokenStream(toks), this, false);
355 this.timerPrint("Compressed");
362 timerPrint: function (str) {
363 var ntime = new Date() * 1;
364 var tdif = ntime -this.timer;
366 print('['+tdif+']'+str);
371 * Translation concept...
372 * -> replace text strings with _T....
373 * -> this file will need inserting at the start of the application....
374 * -> we need to generate 2 files,
375 * -> a reference used to do the translation, and the _T file..
379 writeTranslateFile : function(fn, minfile, toks)
384 toks.forEach(function (t) {
385 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
386 var sval = t.data.substring(1,t.data.length-1);
387 var ffn = fn.substring(_this.prefix.length);
388 map[sval] = _this.md5(ffn + '-' + sval);
392 var transfile = minfile + '.lang.trans';
393 var transmd5 = minfile + '.lang';
394 print("writeTranslateFile " + transfile);
397 if (File.exists(transfile)) {
398 File.remove(transfile);
400 if (File.exists(transmd5)) {
401 File.remove(transmd5);
403 for(v in map) { i++; break };
405 return; // no strings in file...
407 var ffn = fn.substring(this.prefix.length);
410 File.write(transfile, "\n'" + ffn + "' : {");
414 File.write(transmd5, '');
416 File.append(transfile, l + "\n\t \"" + v + '" : "' + v + '"');
418 // strings are raw... - as the where encoded to start with!!!
419 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]="'+v+"\";\n");
421 File.append(transfile, "\n},"); // always one trailing..
425 md5 : function (string)
428 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
431 stringHandler : function(tok)
433 //print("STRING HANDLER");
434 // callback when outputing compressed file,
436 if (!this.translateJSON) {
437 // print("TURNED OFF");
440 if (tok.name == 'SINGLE_QUOTE') {
444 var sval = data.substring(1,data.length-1);
445 // we do not clean up... quoting here!??!!?!?!?!?
448 // blank with tabs or spaces..
449 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
450 // return tok.outData;
453 var sval = tok.data.substring(1,data.length-1);
454 var fn = this.activeFile.substring(this.prefix.length);
457 return '_T["' + this.md5(fn + '-' + sval) + '"]';