index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict'
  2. var fs = require('fs')
  3. var PassThrough = require('stream').PassThrough
  4. var Transform = require('stream').Transform
  5. if (typeof Transform === 'undefined') {
  6. throw new Error('UglifyJS only supports browserify when using node >= 0.10.x')
  7. }
  8. var cache = {}
  9. module.exports = transform
  10. function transform(file) {
  11. if (!/tools\/node\.js$/.test(file.replace(/\\/g,'/'))) return new PassThrough();
  12. if (cache[file]) return makeStream(cache[file])
  13. var uglify = require(file)
  14. var src = 'var sys = require("util");\nvar MOZ_SourceMap = require("source-map");\nvar UglifyJS = exports;\n' + uglify.FILES.map(function (path) { return fs.readFileSync(path, 'utf8') }).join('\n')
  15. var ast = uglify.parse(src)
  16. ast.figure_out_scope()
  17. var variables = ast.variables
  18. .map(function (node, name) {
  19. return name
  20. })
  21. src += '\n\n' + variables.map(function (v) { return 'exports.' + v + ' = ' + v + ';' }).join('\n') + '\n\n'
  22. src += 'exports.AST_Node.warn_function = function (txt) { if (typeof console != "undefined" && typeof console.warn === "function") console.warn(txt) }\n\n'
  23. src += 'exports.minify = ' + uglify.minify.toString() + ';\n\n'
  24. src += 'exports.describe_ast = ' + uglify.describe_ast.toString() + ';'
  25. // TODO: remove once https://github.com/substack/node-browserify/issues/631 is resolved
  26. src = src.replace(/"for"/g, '"fo" + "r"')
  27. cache[file] = src
  28. return makeStream(src);
  29. }
  30. function makeStream(src) {
  31. var res = new Transform();
  32. res._transform = function (chunk, encoding, callback) { callback() }
  33. res._flush = function (callback) {
  34. res.push(src)
  35. callback()
  36. }
  37. return res;
  38. }