amberc.js 21 KB

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