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 link = dirname + '/compiled/' + outname + '.js';
97 if (File.exists(this.target)) {
98 print("Target file already exists");
101 this.prefix = dirname +'/';
102 this.translateJSON = dirname + '/compiled/_translation_.js';
107 this.timer = new Date() * 1;
111 if (File.exists(link)) {
114 var f = Gio.file_new_for_path(this.target);
115 f.create_symbolic_link(link);
123 * @cfg {String} srcfiles file containing a list of files/or classes to use.
128 * @cfg {Array} files list of files to compress (must be full path)
132 * @cfg {String} target to write files to - must be full path.
136 * @cfg {Boolean} autoBuild - turn on autobuild feature (puts files in compiled directory,
137 * and enables translation toolkit.
141 * @cfg {String} module used with autoBuild to force a file name
145 * @cfg {String} debugTargettarget to write files debug version to (uncompacted)- must be full path.
147 debugTarget : '', // merged file without compression.
149 * @cfg {String} tmpDir (optional) where to put the temporary files.
150 * if you set this, then files will not be cleaned up
154 translateJSON : '', // json based list of strings in all files.
157 * @cfg {Boolean} cleanup (optional) clean up temp files after done -
158 * Defaults to false if you set tmpDir, otherwise true.
163 * @cfg {String} prefix (optional) prefix of directory to be stripped of when
164 * Calculating md5 of filename
167 out : '', // if no target is specified - then this will contain the result
170 * load a dependancy list -f option
171 * @param {String} srcfile sourcefile to parse
175 loadSourceFile : function(srcfile)
177 var lines = File.read(srcfile).split("\n");
179 lines.forEach(function(f) {
181 if (/^\s*\//.test(f) || !/[a-z]+/i.test(f)) { // skip comments..
184 if (/\.js$/.test(f)) {
185 _this.files.push( f);
190 //println("ADD"+ f.replace(/\./g, '/'));
191 var add = f.replace(/\./g, '/').replace(/\s+/g,'')+'.js';
192 if (_this.files.indexOf(f) > -1) {
195 _this.files.push( add );
201 packAll : function() // do the packing (run from constructor)
204 //this.transOrigFile= bpath + '/../lang.en.js'; // needs better naming...
205 //File.write(this.transfile, "");
207 File.write(this.target, "");
210 if (this.debugTarget) {
211 File.write(this.debugTarget, "");
214 for(var i=0; i < this.files.length; i++) {
215 var file = this.files[i];
217 print("reading " +file );
218 if (!File.isFile(file)) {
219 print("SKIP (is not a file) " + file);
223 if (this.debugTarget) {
224 File.append(this.debugTarget, File.read(file));
226 // it's a good idea to check with 0 compression to see if the code can parse!!
229 //File.append(dout, str +"\n");
233 var minfile = this.tmpDir + '/' +file.replace(/\//g, '.');
236 // let's see if we have a min file already?
237 // this might happen if tmpDir is set ..
238 if (true && File.exists(minfile)) {
239 var mt = File.mtime(minfile);
240 var ot = File.mtime(file);
241 print("compare : " + mt + "=>" + ot);
245 // then the min'files time is > than original..
246 var str = File.read(minfile);
247 print("using MIN FILE "+ minfile);
249 File.append(outpath, str + "\n");
258 print("COMPRESSING ");
259 //var codeComp = pack(str, 10, 0, 0);
260 if (File.exists(minfile)) {
261 File.remove(minfile);
263 var str = File.read(file);
264 var str = this.pack(str, file, minfile);
266 File.write(minfile, str);
272 if (this.translateJSON) {
275 print("MERGING LANGUAGE");
276 var out = "if (typeof(_T) == 'undefined') { _T={};}\n"
278 File.write(this.target, out);
285 File.write(this.translateJSON, "");
286 for(var i=0; i < this.files.length; i++) {
287 var file = this.files[i];
288 var transfile= this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang.trans';
289 var transmd5 = this.tmpDir + '/' +file.replace(/\//g, '.') +'.lang';
290 if (File.exists(transmd5)) {
291 var str = File.read(transmd5);
294 File.append(this.target, str + "\n");
296 this.out += str + "\n";
301 File.remove(transmd5);
304 if (File.exists(transfile)) {
305 var str = File.read(transfile);
307 File.append(this.translateJSON, str);
310 File.remove(transfile);
318 print("MERGING SOURCE");
320 for(var i=0; i < this.files.length; i++) {
321 var file = this.files[i];
322 var minfile = this.tmpDir + '/' + file.replace(/\//g, '.');
325 if (!File.exists(minfile)) {
328 var str = File.read(minfile);
329 print("using MIN FILE "+ minfile);
332 File.append(this.target, str + "\n");
334 this.out += str + "\n";
339 File.remove(minfile);
349 * Core packing routine for a file
351 * @param str - str source text..
352 * @param fn - filename (for reference?)
353 * @param minfile - min file location...
357 pack : function (str,fn,minfile)
360 var tr = new TokenReader( {
365 collapseWhite : false
367 this.timerPrint("START" + fn);
369 // we can load translation map here...
371 var toks = tr.tokenize(new TextStream(str)); // dont merge xxx + . + yyyy etc.
373 // at this point we can write a language file...
374 if (this.translateJSON) {
376 this.writeTranslateFile(fn, minfile, toks);
379 this.activeFile = fn;
381 // and replace if we are generating a different language..
383 this.timerPrint("Tokenized");
384 //var ts = new TokenStream(toks);
385 //print(JSON.stringify(toks, null,4 )); Seed.quit();
386 var ts = new Collapse(toks);
387 // print(JSON.stringify(ts.tokens, null,4 )); Seed.quit();
389 var sp = new ScopeParser(ts);
390 this.timerPrint("Converted to Parser");
392 sp.buildSymbolTree();
393 this.timerPrint("Built Sym tree");
394 sp.mungeSymboltree();
395 this.timerPrint("Munged Sym tree");
396 print(sp.warnings.join("\n"));
399 //var out = CompressWhite(new TokenStream(toks), this, true); // do not kill whitespace..
400 var out = CompressWhite(new TokenStream(toks), this, false);
401 this.timerPrint("Compressed");
408 timerPrint: function (str) {
409 var ntime = new Date() * 1;
410 var tdif = ntime -this.timer;
412 print('['+tdif+']'+str);
417 * Translation concept...
418 * -> replace text strings with _T....
419 * -> this file will need inserting at the start of the application....
420 * -> we need to generate 2 files,
421 * -> a reference used to do the translation, and the _T file..
425 writeTranslateFile : function(fn, minfile, toks)
430 toks.forEach(function (t) {
431 if (t.type == 'STRN' && t.name == 'DOUBLE_QUOTE') {
432 var sval = t.data.substring(1,t.data.length-1);
433 var ffn = fn.substring(_this.prefix.length);
434 map[sval] = _this.md5(ffn + '-' + sval);
438 var transfile = minfile + '.lang.trans';
439 var transmd5 = minfile + '.lang';
440 print("writeTranslateFile " + transfile);
443 if (File.exists(transfile)) {
444 File.remove(transfile);
446 if (File.exists(transmd5)) {
447 File.remove(transmd5);
449 for(v in map) { i++; break };
451 return; // no strings in file...
453 var ffn = fn.substring(this.prefix.length);
456 File.write(transfile, "\n'" + ffn + "' : {");
460 File.write(transmd5, '');
465 File.append(transfile, l + "\n\t" + JSON.stringify(v) + " : " + JSON.stringify(v));
467 // strings are raw... - as the where encoded to start with!!!
468 File.append(transmd5, '_T["' + this.md5(ffn + '-' + v) + '"]='+JSON.stringify(v)+";\n");
470 File.append(transfile, "\n},"); // always one trailing..
474 md5 : function (string)
477 return GLib.compute_checksum_for_string(GLib.ChecksumType.MD5, string, string.length);
480 stringHandler : function(tok)
482 //print("STRING HANDLER");
483 // callback when outputing compressed file,
485 if (!this.translateJSON) {
486 // print("TURNED OFF");
489 if (tok.name == 'SINGLE_QUOTE') {
493 var sval = data.substring(1,data.length-1);
494 // we do not clean up... quoting here!??!!?!?!?!?
497 // blank with tabs or spaces..
498 //if (!sval.replace(new RegExp("(\\\\n|\\\\t| )+",'g'), '').length) {
499 // return tok.outData;
502 var sval = tok.data.substring(1,data.length-1);
503 var fn = this.activeFile.substring(this.prefix.length);
506 return '_T["' + this.md5(fn + '-' + sval) + '"]';