amberc.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /**
  2. * This is a "compiler" for Amber code.
  3. * Put the following code into compiler.js:
  4. * var amberc = require('amberc');
  5. * var compiler = new amberc.Compiler('path/to/amber', ['/optional/path/to/compiler.jar]);
  6. * compiler.main();
  7. *
  8. * Execute 'node compiler.js' without arguments or with -h / --help for help.
  9. */
  10. /**
  11. * Map the async filter function onto array and evaluate callback, once all have finished.
  12. * Taken from: http://howtonode.org/control-flow-part-iii
  13. */
  14. function async_map(array, filter, callback) {
  15. if (0 === array.length) {
  16. callback(null, null);
  17. return;
  18. }
  19. var counter = array.length;
  20. var new_array = [];
  21. array.forEach(function (item, index) {
  22. filter(item, function (err, result) {
  23. if (err) { callback(err); return; }
  24. new_array[index] = result;
  25. counter--;
  26. if (counter === 0) {
  27. callback(null, new_array);
  28. }
  29. });
  30. });
  31. }
  32. /**
  33. * Always evaluates the callback parameter.
  34. * Used by Combo blocks to always call the next function,
  35. * even if all of the other functions did not run.
  36. */
  37. function always_resolve(callback) {
  38. callback();
  39. }
  40. /**
  41. * Helper for concatenating Amber generated AMD modules.
  42. * The produced output can be exported and run as an independent program.
  43. *
  44. * var concatenator = createConcatenator();
  45. * concatenator.start(); // write the required AMD define header
  46. * concatenator.add(module1);
  47. * concatenator.addId(module1_ID);
  48. * //...
  49. * concatenator.finish("//some last code");
  50. * var concatenation = concatenator.toString();
  51. * // The variable concatenation contains the concatenated result
  52. * // which can either be stored in a file or interpreted with eval().
  53. */
  54. function createConcatenator () {
  55. return {
  56. elements: [],
  57. ids: [],
  58. add: function () {
  59. this.elements.push.apply(this.elements, arguments);
  60. },
  61. addId: function () {
  62. this.ids.push.apply(this.ids, arguments);
  63. },
  64. forEach: function () {
  65. this.elements.forEach.apply(this.elements, arguments);
  66. },
  67. start: function () {
  68. this.add(
  69. 'var define = (' + require('amdefine') + ')(), requirejs = define.require;',
  70. 'define("amber_vm/browser-compatibility", [], {});'
  71. );
  72. },
  73. finish: function (realWork) {
  74. this.add(
  75. 'define("amber_vm/_init", ["amber_vm/smalltalk","' + this.ids.join('","') + '"], function (smalltalk) {',
  76. 'smalltalk.initialize();',
  77. realWork,
  78. '});',
  79. 'requirejs("amber_vm/_init");'
  80. );
  81. },
  82. toString: function () {
  83. return this.elements.join('\n');
  84. }
  85. };
  86. }
  87. /**
  88. * Combine several async functions and evaluate callback once all of them have finished.
  89. * Taken from: http://howtonode.org/control-flow
  90. */
  91. function Combo(callback) {
  92. this.callback = callback;
  93. this.items = 0;
  94. this.results = [];
  95. }
  96. Combo.prototype = {
  97. add: function () {
  98. var self = this,
  99. id = this.items;
  100. this.items++;
  101. return function () {
  102. self.check(id, arguments);
  103. };
  104. },
  105. check: function (id, arguments) {
  106. this.results[id] = Array.prototype.slice.call(arguments);
  107. this.items--;
  108. if (this.items == 0) {
  109. this.callback.apply(this, this.results);
  110. }
  111. }
  112. };
  113. var path = require('path'),
  114. util = require('util'),
  115. fs = require('fs'),
  116. exec = require('child_process').exec;
  117. /**
  118. * AmberC constructor function.
  119. * amber_dir: points to the location of an amber installation
  120. * closure_jar: location of compiler.jar (can be left undefined)
  121. */
  122. function AmberC(amber_dir, closure_jar) {
  123. this.amber_dir = amber_dir;
  124. this.closure_jar = closure_jar || '';
  125. this.kernel_libraries = ['boot', '@smalltalk', '@nil', '@_st', 'Kernel-Objects', 'Kernel-Classes', 'Kernel-Methods',
  126. 'Kernel-Collections', 'Kernel-Exceptions', 'Kernel-Transcript',
  127. 'Kernel-Announcements'];
  128. this.compiler_libraries = this.kernel_libraries.concat(['parser', 'Importer-Exporter',
  129. 'Compiler-Core', 'Compiler-AST', 'Compiler-Exceptions', 'Compiler-IR', 'Compiler-Inlining', 'Compiler-Semantic']);
  130. }
  131. /**
  132. * Default values.
  133. */
  134. var createDefaults = function(amber_dir, finished_callback){
  135. if (undefined === amber_dir) {
  136. throw new Error('createDefaults() function needs a valid amber_dir parameter');
  137. }
  138. return {
  139. 'load': [],
  140. 'main': undefined,
  141. 'mainfile': undefined,
  142. 'stFiles': [],
  143. 'jsFiles': [],
  144. 'jsGlobals': [],
  145. 'closure': false,
  146. 'closure_parts': false,
  147. 'closure_full': false,
  148. 'closure_options': ' --language_in=ECMASCRIPT5 ',
  149. 'suffix': '',
  150. 'loadsuffix': '',
  151. 'suffix_used': '',
  152. 'deploy': false,
  153. 'libraries': [],
  154. 'compile': [],
  155. 'compiled': [],
  156. 'program': undefined,
  157. 'output_dir': undefined,
  158. 'verbose': false,
  159. 'finished_callback': finished_callback
  160. };
  161. };
  162. /**
  163. * Main function for executing the compiler.
  164. * If check_configuration_ok() returns successfully the configuration is set on the current compiler
  165. * instance and check_for_closure_compiler() gets called.
  166. * The last step is to call collect_files().
  167. */
  168. AmberC.prototype.main = function(configuration, finished_callback) {
  169. console.time('Compile Time');
  170. if (undefined !== finished_callback) {
  171. configuration.finished_callback = finished_callback;
  172. }
  173. if (configuration.closure || configuration.closure_parts || configuration.closure_full) {
  174. configuration.deploy = true;
  175. }
  176. console.ambercLog = console.log;
  177. if (false === configuration.verbose) {
  178. console.log = function() {};
  179. }
  180. if (this.check_configuration_ok(configuration)) {
  181. this.defaults = configuration;
  182. this.defaults.smalltalk = {}; // the evaluated compiler will be stored in this variable (see create_compiler)
  183. var self = this;
  184. this.check_for_closure_compiler(function(){
  185. self.collect_files(self.defaults.stFiles, self.defaults.jsFiles)
  186. });
  187. }
  188. };
  189. /**
  190. * Check if the passed in configuration object has sufficient/nonconflicting values
  191. */
  192. AmberC.prototype.check_configuration_ok = function(configuration) {
  193. if (undefined === configuration) {
  194. throw new Error('AmberC.check_configuration_ok(): missing configuration object');
  195. }
  196. if (0 === configuration.jsFiles.length && 0 === configuration.stFiles.lenght) {
  197. throw new Error('AmberC.check_configuration_ok(): no files to compile/link specified in configuration object');
  198. }
  199. return true;
  200. };
  201. /**
  202. * Checks if the java executable exists and afterwards,
  203. * if compiler.jar exists at the path stored in this.closure_jar.
  204. * All closure related entries are set to false upon failure.
  205. *
  206. * callback gets called in any case.
  207. */
  208. AmberC.prototype.check_for_closure_compiler = function(callback) {
  209. var defaults = this.defaults;
  210. var self = this;
  211. if (defaults.closure) {
  212. exec('which java', function(error, stdout, stderr) {
  213. // stdout contains path to java executable
  214. if (null !== error) {
  215. console.warn('java is not installed but is needed for running the Closure compiler (-O, -A or -o flags).');
  216. defaults.closure = false;
  217. defaults.closure_parts = false;
  218. defaults.closure_full = false;
  219. callback();
  220. return;
  221. }
  222. fs.exists(self.closure_jar, function(exists) {
  223. if (!exists) {
  224. console.warn('Can not find Closure compiler at: ' + self.closure_jar);
  225. defaults.closure = false;
  226. defaults.closure_parts = false;
  227. defaults.closure_full = false;
  228. } else {
  229. console.warn('Closure compiler found at: ' + self.closure_jar);
  230. }
  231. callback();
  232. return;
  233. });
  234. });
  235. } else {
  236. callback();
  237. }
  238. };
  239. /**
  240. * Check if the file given as parameter exists in the local directory or in $AMBER/js/.
  241. * '.js' is appended first.
  242. *
  243. * @param filename name of a file without '.js' prefix
  244. * @param callback gets called on success with path to .js file as parameter
  245. */
  246. AmberC.prototype.resolve_js = function(filename, callback) {
  247. var special = filename[0] == "@";
  248. if (special) {
  249. filename = filename.slice(1);
  250. }
  251. var baseName = path.basename(filename, '.js');
  252. var jsFile = baseName + this.defaults.loadsuffix + '.js';
  253. var amberJsFile = path.join(this.amber_dir, (special ? 'js/lib' : 'js'), jsFile);
  254. console.log('Resolving: ' + jsFile);
  255. fs.exists(jsFile, function(exists) {
  256. if (exists) {
  257. callback(jsFile);
  258. } else {
  259. fs.exists(amberJsFile, function(exists) {
  260. if (exists) {
  261. callback(amberJsFile);
  262. } else {
  263. throw(new Error('JavaScript file not found: ' + jsFile));
  264. }
  265. });
  266. }
  267. });
  268. };
  269. /**
  270. * Collect libraries and Smalltalk files looking
  271. * both locally and in $AMBER/js and $AMBER/st.
  272. * Followed by resolve_libraries().
  273. */
  274. AmberC.prototype.collect_files = function(stFiles, jsFiles) {
  275. var self = this;
  276. var collected_files = new Combo(function() {
  277. self.resolve_libraries();
  278. });
  279. if (0 !== stFiles.length) {
  280. self.collect_st_files(stFiles, collected_files.add());
  281. }
  282. if (0 !== jsFiles.length) {
  283. self.collect_js_files(jsFiles, collected_files.add());
  284. }
  285. };
  286. /**
  287. * Resolve st files given by stFiles and add them to defaults.compile.
  288. * Respective categories get added to defaults.compile_categories.
  289. * callback is evaluated afterwards.
  290. */
  291. AmberC.prototype.collect_st_files = function(stFiles, callback) {
  292. var defaults = this.defaults;
  293. var self = this;
  294. var collected_st_files = new Combo(function() {
  295. Array.prototype.slice.call(arguments).forEach(function(data) {
  296. var stFile = data[0];
  297. defaults.compile.push(stFile);
  298. });
  299. callback();
  300. });
  301. stFiles.forEach(function(stFile) {
  302. var _callback = collected_st_files.add();
  303. console.log('Checking: ' + stFile);
  304. var amberStFile = path.join(self.amber_dir, 'st', stFile);
  305. fs.exists(stFile, function(exists) {
  306. if (exists) {
  307. _callback(stFile);
  308. } else {
  309. console.log('Checking: ' + amberStFile);
  310. fs.exists(amberStFile, function(exists) {
  311. if (exists) {
  312. _callback(amberStFile);
  313. } else {
  314. throw(new Error('Smalltalk file not found: ' + amberStFile));
  315. }
  316. });
  317. }
  318. });
  319. });
  320. };
  321. /**
  322. * Resolve js files given by jsFiles and add them to defaults.libraries.
  323. * callback is evaluated afterwards.
  324. */
  325. AmberC.prototype.collect_js_files = function(jsFiles, callback) {
  326. var self = this;
  327. var collected_js_files = new Combo(function() {
  328. Array.prototype.slice.call(arguments).forEach(function(file) {
  329. self.defaults.libraries.push(file[0]);
  330. });
  331. callback();
  332. });
  333. jsFiles.forEach(function(jsFile) {
  334. self.resolve_js(jsFile, collected_js_files.add());
  335. });
  336. };
  337. /**
  338. * Resolve kernel and compiler files.
  339. * Followed by resolve_init().
  340. */
  341. AmberC.prototype.resolve_libraries = function() {
  342. // Resolve libraries listed in this.kernel_libraries
  343. var self = this;
  344. var all_resolved = new Combo(function(resolved_kernel_files, resolved_compiler_files) {
  345. self.create_compiler(resolved_compiler_files[0]);
  346. });
  347. this.resolve_kernel(all_resolved.add());
  348. this.resolve_compiler(all_resolved.add());
  349. };
  350. /**
  351. * Resolve .js files needed by kernel
  352. * callback is evaluated afterwards.
  353. */
  354. AmberC.prototype.resolve_kernel = function(callback) {
  355. var self = this;
  356. var kernel_files = this.kernel_libraries.concat(this.defaults.load);
  357. var kernel_resolved = new Combo(function() {
  358. var foundLibraries = [];
  359. Array.prototype.slice.call(arguments).forEach(function(file) {
  360. if (undefined !== file[0]) {
  361. foundLibraries.push(file[0]);
  362. }
  363. });
  364. // boot.js and Kernel files need to be used first
  365. // otherwise the global smalltalk object is undefined
  366. self.defaults.libraries = foundLibraries.concat(self.defaults.libraries);
  367. callback(null);
  368. });
  369. kernel_files.forEach(function(file) {
  370. self.resolve_js(file, kernel_resolved.add());
  371. });
  372. always_resolve(kernel_resolved.add());
  373. };
  374. /**
  375. * Resolve .js files needed by compiler.
  376. * callback is evaluated afterwards with resolved files as argument.
  377. */
  378. AmberC.prototype.resolve_compiler = function(callback) {
  379. // Resolve compiler libraries
  380. var compiler_files = this.compiler_libraries.concat(this.defaults.load);
  381. var compiler_resolved = new Combo(function() {
  382. var compilerFiles = [];
  383. Array.prototype.slice.call(arguments).forEach(function(file) {
  384. if (undefined !== file[0]) {
  385. compilerFiles.push(file[0]);
  386. }
  387. });
  388. callback(compilerFiles);
  389. });
  390. var self = this
  391. compiler_files.forEach(function(file) {
  392. self.resolve_js(file, compiler_resolved.add());
  393. });
  394. always_resolve(compiler_resolved.add());
  395. };
  396. /**
  397. * Read all .js files needed by compiler and eval() them.
  398. * The finished Compiler gets stored in defaults.smalltalk.
  399. * Followed by compile().
  400. */
  401. AmberC.prototype.create_compiler = function(compilerFilesArray) {
  402. var self = this;
  403. var compiler_files = new Combo(function() {
  404. var builder = createConcatenator();
  405. builder.add('(function() {');
  406. builder.start();
  407. Array.prototype.slice.call(arguments).forEach(function(data) {
  408. // data is an array where index 0 is the error code and index 1 contains the data
  409. builder.add(data[1]);
  410. // matches and returns the "module_id" string in the AMD definition: define("module_id", ...)
  411. var match = ('' + data[1]).match(/^define\("([^"]*)"/);
  412. if (match) {
  413. builder.addId(match[1]);
  414. }
  415. });
  416. // store the generated smalltalk env in self.defaults.smalltalk
  417. builder.finish('self.defaults.smalltalk = smalltalk;');
  418. builder.add('})();');
  419. eval(builder.toString());
  420. console.log('Compiler loaded');
  421. self.defaults.smalltalk.ErrorHandler._setCurrent_(self.defaults.smalltalk.RethrowErrorHandler._new());
  422. if(0 != self.defaults.jsGlobals.length) {
  423. var jsGlobalVariables = self.defaults.smalltalk.globalJsVariables;
  424. jsGlobalVariables.push.apply(jsGlobalVariables, self.defaults.jsGlobals);
  425. }
  426. self.compile();
  427. });
  428. compilerFilesArray.forEach(function(file) {
  429. console.log('Loading file: ' + file);
  430. fs.readFile(file, compiler_files.add());
  431. });
  432. };
  433. /**
  434. * Compile all given .st files by importing them.
  435. * Followed by category_export().
  436. */
  437. AmberC.prototype.compile = function() {
  438. console.log('Compiling collected .st files')
  439. // import .st files
  440. var self = this;
  441. var imports = new Combo(function() {
  442. Array.prototype.slice.call(arguments).forEach(function(code) {
  443. if (undefined !== code[0]) {
  444. // get element 0 of code since all return values are stored inside an array by Combo
  445. self.defaults.smalltalk.Importer._new()._import_(code[0]._stream());
  446. }
  447. });
  448. self.category_export();
  449. });
  450. this.defaults.compile.forEach(function(stFile) {
  451. var callback = imports.add();
  452. if (/\.st/.test(stFile)) {
  453. console.ambercLog('Importing: ' + stFile);
  454. fs.readFile(stFile, 'utf8', function(err, data) {
  455. if (!err)
  456. callback(data);
  457. else
  458. throw new Error('Could not import: ' + stFile);
  459. });
  460. }
  461. });
  462. always_resolve(imports.add());
  463. };
  464. /**
  465. * Export compiled categories to JavaScript files.
  466. * Followed by verify().
  467. */
  468. AmberC.prototype.category_export = function() {
  469. var defaults = this.defaults;
  470. var self = this;
  471. // export categories as .js
  472. async_map(defaults.compile, function(stFile, callback) {
  473. var category = path.basename(stFile, '.st');
  474. var jsFilePath = defaults.output_dir;
  475. if (undefined === jsFilePath) {
  476. jsFilePath = path.dirname(stFile);
  477. }
  478. var jsFile = category + defaults.suffix_used + '.js';
  479. jsFile = path.join(jsFilePath, jsFile);
  480. defaults.compiled.push(jsFile);
  481. var jsFileDeploy = category + defaults.suffix_used + '.deploy.js';
  482. jsFileDeploy = path.join(jsFilePath, jsFileDeploy);
  483. console.log('Exporting ' + (defaults.deploy ? '(debug + deploy)' : '(debug)')
  484. + ' category ' + category + ' as ' + jsFile
  485. + (defaults.deploy ? ' and ' + jsFileDeploy : ''));
  486. var smalltalk = defaults.smalltalk;
  487. var pluggableExporter = smalltalk.PluggableExporter;
  488. var packageObject = smalltalk.Package._named_(category);
  489. packageObject._amdNamespace_("amber");
  490. fs.writeFile(jsFile, smalltalk.String._streamContents_(function (stream) {
  491. pluggableExporter._newUsing_(smalltalk.Exporter._amdRecipe())._exportPackage_on_(packageObject, stream); }), function(err) {
  492. if (defaults.deploy) {
  493. fs.writeFile(jsFileDeploy, smalltalk.String._streamContents_(function (stream) {
  494. pluggableExporter._newUsing_(smalltalk.StrippedExporter._amdRecipe())._exportPackage_on_(packageObject, stream); }), callback);
  495. } else {
  496. callback(null, null);
  497. }
  498. });
  499. }, function(err, result){
  500. self.verify();
  501. });
  502. };
  503. /**
  504. * Verify if all .st files have been compiled.
  505. * Followed by compose_js_files() and optimize().
  506. */
  507. AmberC.prototype.verify = function() {
  508. console.log('Verifying if all .st files were compiled');
  509. var self = this;
  510. // copy array
  511. var compiledFiles = this.defaults.compiled.slice(0);
  512. // append deploy files if necessary
  513. if (true === this.defaults.deploy) {
  514. this.defaults.compiled.forEach(function(file) {
  515. compiledFiles.push(file.replace(/\.js/g, '.deploy.js'));
  516. });
  517. }
  518. async_map(compiledFiles,
  519. function(file, callback) {
  520. fs.exists(file, function(exists) {
  521. if (exists)
  522. callback(null, null);
  523. else
  524. throw(new Error('Compilation failed of: ' + file));
  525. });
  526. }, function(err, result) {
  527. self.compose_js_files();
  528. });
  529. };
  530. /**
  531. * Synchronous function.
  532. * Concatenates compiled JavaScript files into one file in the correct order.
  533. * The name of the produced file is given by defaults.program (set by the last commandline option).
  534. */
  535. AmberC.prototype.compose_js_files = function() {
  536. var defaults = this.defaults;
  537. var self = this;
  538. var programFile = defaults.program;
  539. if (undefined === programFile) {
  540. self.optimize();
  541. return;
  542. }
  543. if (undefined !== defaults.output_dir) {
  544. programFile = path.join(defaults.output_dir, programFile);
  545. }
  546. var program_files = [];
  547. if (0 !== defaults.libraries.length) {
  548. console.log('Collecting libraries: ' + defaults.libraries);
  549. program_files.push.apply(program_files, defaults.libraries);
  550. }
  551. if (0 !== defaults.compiled.length) {
  552. var compiledFiles = defaults.compiled.slice(0);
  553. if (true === defaults.deploy) {
  554. compiledFiles = compiledFiles.map(function(file) {
  555. return file.replace(/\.js$/g, '.deploy.js');
  556. });
  557. }
  558. console.log('Collecting compiled files: ' + compiledFiles);
  559. program_files.push.apply(program_files, compiledFiles);
  560. }
  561. console.ambercLog('Writing program file: %s.js', programFile);
  562. var fileStream = fs.createWriteStream(programFile + defaults.suffix_used + '.js');
  563. fileStream.on('error', function(error) {
  564. fileStream.end();
  565. console.ambercLog(error);
  566. });
  567. fileStream.on('close', function(){
  568. self.optimize();
  569. });
  570. var builder = createConcatenator();
  571. builder.start();
  572. program_files.forEach(function(file) {
  573. if(fs.existsSync(file)) {
  574. console.log('Adding : ' + file);
  575. var buffer = fs.readFileSync(file);
  576. // matches and returns the "module_id" string in the AMD define: define("module_id", ...)
  577. var match = buffer.toString().match(/^define\("([^"]*)"/);
  578. if (match /*&& match[1].slice(0,9) !== "amber_vm/"*/) {
  579. builder.addId(match[1]);
  580. }
  581. builder.add(buffer);
  582. } else {
  583. fileStream.end();
  584. throw(new Error('Can not find file ' + file));
  585. }
  586. });
  587. var mainFunctionOrFile = '';
  588. if (undefined !== defaults.main) {
  589. console.log('Adding call to: %s>>main', defaults.main);
  590. mainFunctionOrFile += 'smalltalk.' + defaults.main + '._main();';
  591. }
  592. if (undefined !== defaults.mainfile && fs.existsSync(defaults.mainfile)) {
  593. console.log('Adding main file: ' + defaults.mainfile);
  594. mainFunctionOrFile += '\n' + fs.readFileSync(defaults.mainfile);
  595. }
  596. builder.finish(mainFunctionOrFile);
  597. console.log('Writing...');
  598. builder.forEach(function (element) {
  599. fileStream.write(element);
  600. fileStream.write('\n');
  601. });
  602. console.log('Done.');
  603. fileStream.end();
  604. };
  605. /**
  606. * Optimize created JavaScript files with Google Closure compiler depending
  607. * on the flags: defaults.closure_parts, defaults.closure_full.
  608. */
  609. AmberC.prototype.optimize = function() {
  610. var defaults = this.defaults;
  611. var self = this;
  612. var optimization_done = new Combo(function() {
  613. console.log = console.ambercLog;
  614. console.timeEnd('Compile Time');
  615. if (undefined !== defaults.finished_callback) {
  616. defaults.finished_callback();
  617. }
  618. });
  619. if (defaults.closure_parts) {
  620. console.log('Compiling all js files using Google closure compiler.');
  621. defaults.compiled.forEach(function(file) {
  622. var deployFile = file.replace(/\.js$/g, '.deploy.js');
  623. console.log('Compiling ' + deployFile + ' file using Google closure compiler.');
  624. var minifiedName = deployFile.replace(/\.js$/g, '.min.js');
  625. self.closure_compile(deployFile, minifiedName, optimization_done.add());
  626. });
  627. }
  628. if (defaults.closure_full && (undefined !== defaults.program)) {
  629. var programFile = defaults.program;
  630. if (undefined !== defaults.output_dir) {
  631. programFile = path.join(defaults.output_dir, programFile);
  632. }
  633. console.log('Compiling ' + programFile + '.js file using Google closure compiler.');
  634. self.closure_compile(programFile + '.js', programFile + '.min.js', optimization_done.add());
  635. }
  636. always_resolve(optimization_done.add());
  637. };
  638. /**
  639. * Compile sourceFile into minifiedFile with Google Closure compiler.
  640. * callback gets executed once finished.
  641. */
  642. AmberC.prototype.closure_compile = function(sourceFile, minifiedFile, callback) {
  643. // exec is asynchronous
  644. var self = this;
  645. exec(
  646. 'java -jar ' +
  647. self.closure_jar + ' ' +
  648. self.defaults.closure_options +
  649. ' --js '+ sourceFile +
  650. ' --js_output_file '+ minifiedFile,
  651. function (error, stdout, stderr) {
  652. if (error) {
  653. console.log(stderr);
  654. } else {
  655. console.log(stdout);
  656. console.log('Minified: '+ minifiedFile);
  657. }
  658. callback();
  659. }
  660. );
  661. };
  662. module.exports.Compiler = AmberC;
  663. module.exports.createDefaults = createDefaults;
  664. module.exports.Combo = Combo;
  665. module.exports.map = async_map;