diff --git a/package.json b/package.json index d4ae74d..aa65de2 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,9 @@ "version": "1.0.7", "description": "Builtins that were extracted from node-browser-resolve on which browserify depends", "main": "index.js", + "scripts": { + "test": "tape test/node/* && browserify --transform ./test/browserify-transform.js test/browser/* | testling" + }, "repository": { "type": "git", "url": "git://github.com/alexgorbatchev/node-browser-builtins.git" @@ -22,5 +25,8 @@ "buffer-browserify": "0.1.x", "zlib-browserify": "0.0.x", "constants-browserify": "0.0.x" + }, + "devDependencies": { + "tape": "1.0.x" } } diff --git a/test/browserify-transform.js b/test/browserify-transform.js new file mode 100644 index 0000000..0a0df1a --- /dev/null +++ b/test/browserify-transform.js @@ -0,0 +1,42 @@ + +// This transformer changes the require calls so they don't point to the +// browserify buildins (older version of this module). + +var path = require('path'); +var util = require('util'); +var stream = require('stream'); +var buildins = require('../index.js'); + +function RequireRedirect() { + if (!(this instanceof RequireRedirect)) return new RequireRedirect(); + stream.Transform.call(this); + this.buffers = []; +} +module.exports = RequireRedirect; +util.inherits(RequireRedirect, stream.Transform); + +RequireRedirect.prototype._transform = function (chunk, encoding, done) { + this.buffers.push(chunk); + done(null); +}; + +// NOTE: this is an incomplete require RegExp, but for internal use here +// its fine. +var REQUIRE_REGEX = /require\((?:"|')([^"']+)(?:"|')\)/g; + +var RELATIVE_DIR = path.resolve(__dirname, '..'); + +RequireRedirect.prototype._flush = function (done) { + var file = Buffer.concat(this.buffers).toString(); + + file = file.replace(REQUIRE_REGEX, function (source, name) { + if (buildins.hasOwnProperty(name)) { + return "require('" + buildins[name] + "')"; + } else { + return source; + } + }); + + this.push(file); + done(null); +};