post-compile.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env node
  2. ;(function() {
  3. 'use strict';
  4. /** The Node filesystem module */
  5. var fs = require('fs');
  6. /** The minimal license/copyright template */
  7. var licenseTemplate = {
  8. 'lodash':
  9. '/*!\n' +
  10. ' Lo-Dash @VERSION lodash.com/license\n' +
  11. ' Underscore.js 1.3.3 github.com/documentcloud/underscore/blob/master/LICENSE\n' +
  12. '*/',
  13. 'underscore':
  14. '/*! Underscore.js @VERSION github.com/documentcloud/underscore/blob/master/LICENSE */'
  15. };
  16. /*--------------------------------------------------------------------------*/
  17. /**
  18. * Post-process a given minified Lo-Dash `source`, preparing it for
  19. * deployment.
  20. *
  21. * @param {String} source The source to process.
  22. * @returns {String} Returns the processed source.
  23. */
  24. function postprocess(source) {
  25. // move vars exposed by Closure Compiler into the IIFE
  26. source = source.replace(/^([^(\n]+)\s*(\(function[^)]+\){)/, '$2$1');
  27. // unescape properties (i.e. foo["bar"] => foo.bar)
  28. source = source.replace(/(\w)\["([^."]+)"\]/g, function(match, left, right) {
  29. return /\W/.test(right) ? match : (left + '.' + right);
  30. });
  31. // correct AMD module definition for AMD build optimizers
  32. source = source.replace(/("function")\s*==\s*(typeof define)\s*&&\s*\(?\s*("object")\s*==\s*(typeof define\.amd)\s*&&\s*(define\.amd)\s*\)?/, '$2==$1&&$4==$3&&$5');
  33. // add trailing semicolon
  34. if (source) {
  35. source = source.replace(/[\s;]*$/, ';');
  36. }
  37. // exit early if version snippet isn't found
  38. var snippet = /VERSION\s*[=:]\s*([\'"])(.*?)\1/.exec(source);
  39. if (!snippet) {
  40. return source;
  41. }
  42. // add license
  43. return licenseTemplate[/call\(this\);?$/.test(source) ? 'underscore' : 'lodash']
  44. .replace('@VERSION', snippet[2]) + '\n;' + source;
  45. }
  46. /*--------------------------------------------------------------------------*/
  47. // expose `postprocess`
  48. if (module != require.main) {
  49. module.exports = postprocess;
  50. } else {
  51. // read the Lo-Dash source file from the first argument if the script
  52. // was invoked directly (e.g. `node post-compile.js source.js`) and write to
  53. // the same file
  54. (function() {
  55. var source = fs.readFileSync(process.argv[2], 'utf8');
  56. fs.writeFileSync(process.argv[2], postprocess(source), 'utf8');
  57. }());
  58. }
  59. }());