diff --git a/.eslintrc b/.eslintrc
new file mode 100644
index 000000000..e3578aadf
--- /dev/null
+++ b/.eslintrc
@@ -0,0 +1,3 @@
+{
+ "extends": "standard"
+}
diff --git a/.gitignore b/.gitignore
index 1db018319..726672b45 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,5 @@
node_modules
some-test.js
npm-debug.log
+sauce_connect.log
+test/tmp-disposable-nodes-addrs.json
diff --git a/.travis.yml b/.travis.yml
index 851a54a6f..db469efc8 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,3 +1,7 @@
language: node_js
node_js:
- "4.0"
+
+before_script:
+ - export DISPLAY=:99.0
+ - sh -e /etc/init.d/xvfb start
diff --git a/README.md b/README.md
index 10a359b01..71320bb16 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,8 @@ IPFS API wrapper library for Node.js and the browser
# Usage
+### NOTE - Current version only supports IPFS 0.3.7
+
## Installing the module
### In Node.js Through npm
diff --git a/dist/ipfsapi.js b/dist/ipfsapi.js
index cbc57bf5a..960009f7c 100644
--- a/dist/ipfsapi.js
+++ b/dist/ipfsapi.js
@@ -359,7 +359,47 @@ var objectKeys = Object.keys || function (obj) {
return keys;
};
-},{"util/":90}],2:[function(require,module,exports){
+},{"util/":138}],2:[function(require,module,exports){
+module.exports = balanced;
+function balanced(a, b, str) {
+ var bal = 0;
+ var m = {};
+ var ended = false;
+
+ for (var i = 0; i < str.length; i++) {
+ if (a == str.substr(i, a.length)) {
+ if (!('start' in m)) m.start = i;
+ bal++;
+ }
+ else if (b == str.substr(i, b.length) && 'start' in m) {
+ ended = true;
+ bal--;
+ if (!bal) {
+ m.end = i;
+ m.pre = str.substr(0, m.start);
+ m.body = (m.end - m.start > 1)
+ ? str.substring(m.start + a.length, m.end)
+ : '';
+ m.post = str.slice(m.end + b.length);
+ return m;
+ }
+ }
+ }
+
+ // if we opened more than we closed, find the one we closed
+ if (bal && ended) {
+ var start = m.start + a.length;
+ m = balanced(a, b, str.substr(start));
+ if (m) {
+ m.start += start;
+ m.end += start;
+ m.pre = str.slice(0, start) + m.pre;
+ }
+ return m;
+ }
+}
+
+},{}],3:[function(require,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
@@ -485,11 +525,204 @@ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
-},{}],3:[function(require,module,exports){
-
},{}],4:[function(require,module,exports){
-arguments[4][3][0].apply(exports,arguments)
-},{"dup":3}],5:[function(require,module,exports){
+var concatMap = require('concat-map');
+var balanced = require('balanced-match');
+
+module.exports = expandTop;
+
+var escSlash = '\0SLASH'+Math.random()+'\0';
+var escOpen = '\0OPEN'+Math.random()+'\0';
+var escClose = '\0CLOSE'+Math.random()+'\0';
+var escComma = '\0COMMA'+Math.random()+'\0';
+var escPeriod = '\0PERIOD'+Math.random()+'\0';
+
+function numeric(str) {
+ return parseInt(str, 10) == str
+ ? parseInt(str, 10)
+ : str.charCodeAt(0);
+}
+
+function escapeBraces(str) {
+ return str.split('\\\\').join(escSlash)
+ .split('\\{').join(escOpen)
+ .split('\\}').join(escClose)
+ .split('\\,').join(escComma)
+ .split('\\.').join(escPeriod);
+}
+
+function unescapeBraces(str) {
+ return str.split(escSlash).join('\\')
+ .split(escOpen).join('{')
+ .split(escClose).join('}')
+ .split(escComma).join(',')
+ .split(escPeriod).join('.');
+}
+
+
+// Basically just str.split(","), but handling cases
+// where we have nested braced sections, which should be
+// treated as individual members, like {a,{b,c},d}
+function parseCommaParts(str) {
+ if (!str)
+ return [''];
+
+ var parts = [];
+ var m = balanced('{', '}', str);
+
+ if (!m)
+ return str.split(',');
+
+ var pre = m.pre;
+ var body = m.body;
+ var post = m.post;
+ var p = pre.split(',');
+
+ p[p.length-1] += '{' + body + '}';
+ var postParts = parseCommaParts(post);
+ if (post.length) {
+ p[p.length-1] += postParts.shift();
+ p.push.apply(p, postParts);
+ }
+
+ parts.push.apply(parts, p);
+
+ return parts;
+}
+
+function expandTop(str) {
+ if (!str)
+ return [];
+
+ return expand(escapeBraces(str), true).map(unescapeBraces);
+}
+
+function identity(e) {
+ return e;
+}
+
+function embrace(str) {
+ return '{' + str + '}';
+}
+function isPadded(el) {
+ return /^-?0\d/.test(el);
+}
+
+function lte(i, y) {
+ return i <= y;
+}
+function gte(i, y) {
+ return i >= y;
+}
+
+function expand(str, isTop) {
+ var expansions = [];
+
+ var m = balanced('{', '}', str);
+ if (!m || /\$$/.test(m.pre)) return [str];
+
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
+ var isSequence = isNumericSequence || isAlphaSequence;
+ var isOptions = /^(.*,)+(.+)?$/.test(m.body);
+ if (!isSequence && !isOptions) {
+ // {a},b}
+ if (m.post.match(/,.*}/)) {
+ str = m.pre + '{' + m.body + escClose + m.post;
+ return expand(str);
+ }
+ return [str];
+ }
+
+ var n;
+ if (isSequence) {
+ n = m.body.split(/\.\./);
+ } else {
+ n = parseCommaParts(m.body);
+ if (n.length === 1) {
+ // x{{a,b}}y ==> x{a}y x{b}y
+ n = expand(n[0], false).map(embrace);
+ if (n.length === 1) {
+ var post = m.post.length
+ ? expand(m.post, false)
+ : [''];
+ return post.map(function(p) {
+ return m.pre + n[0] + p;
+ });
+ }
+ }
+ }
+
+ // at this point, n is the parts, and we know it's not a comma set
+ // with a single entry.
+
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
+ var pre = m.pre;
+ var post = m.post.length
+ ? expand(m.post, false)
+ : [''];
+
+ var N;
+
+ if (isSequence) {
+ var x = numeric(n[0]);
+ var y = numeric(n[1]);
+ var width = Math.max(n[0].length, n[1].length)
+ var incr = n.length == 3
+ ? Math.abs(numeric(n[2]))
+ : 1;
+ var test = lte;
+ var reverse = y < x;
+ if (reverse) {
+ incr *= -1;
+ test = gte;
+ }
+ var pad = n.some(isPadded);
+
+ N = [];
+
+ for (var i = x; test(i, y); i += incr) {
+ var c;
+ if (isAlphaSequence) {
+ c = String.fromCharCode(i);
+ if (c === '\\')
+ c = '';
+ } else {
+ c = String(i);
+ if (pad) {
+ var need = width - c.length;
+ if (need > 0) {
+ var z = new Array(need + 1).join('0');
+ if (i < 0)
+ c = '-' + z + c.slice(1);
+ else
+ c = z + c;
+ }
+ }
+ }
+ N.push(c);
+ }
+ } else {
+ N = concatMap(n, function(el) { return expand(el, false) });
+ }
+
+ for (var j = 0; j < N.length; j++) {
+ for (var k = 0; k < post.length; k++) {
+ var expansion = pre + N[j] + post[k];
+ if (!isTop || isSequence || expansion)
+ expansions.push(expansion);
+ }
+ }
+
+ return expansions;
+}
+
+
+},{"balanced-match":2,"concat-map":12}],5:[function(require,module,exports){
+
+},{}],6:[function(require,module,exports){
+arguments[4][5][0].apply(exports,arguments)
+},{"dup":5}],7:[function(require,module,exports){
var Buffer = require('buffer').Buffer; // for use with browserify
module.exports = function (a, b) {
@@ -505,7 +738,7 @@ module.exports = function (a, b) {
return true;
};
-},{"buffer":6}],6:[function(require,module,exports){
+},{"buffer":8}],8:[function(require,module,exports){
(function (global){
/*!
* The buffer module from node.js, for the browser.
@@ -555,20 +788,22 @@ var rootParent = {}
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
- : (function () {
- function Bar () {}
- try {
- var arr = new Uint8Array(1)
- arr.foo = function () { return 42 }
- arr.constructor = Bar
- return arr.foo() === 42 && // typed array instances can be augmented
- arr.constructor === Bar && // constructor can be set
- typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
- arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
- } catch (e) {
- return false
- }
- })()
+ : typedArraySupport()
+
+function typedArraySupport () {
+ function Bar () {}
+ try {
+ var arr = new Uint8Array(1)
+ arr.foo = function () { return 42 }
+ arr.constructor = Bar
+ return arr.foo() === 42 && // typed array instances can be augmented
+ arr.constructor === Bar && // constructor can be set
+ typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
+ arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
+ } catch (e) {
+ return false
+ }
+}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
@@ -1522,7 +1757,7 @@ Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
- this[offset] = value
+ this[offset] = (value & 0xff)
return offset + 1
}
@@ -1539,7 +1774,7 @@ Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = value
+ this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
@@ -1553,7 +1788,7 @@ Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
- this[offset + 1] = value
+ this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
@@ -1575,7 +1810,7 @@ Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
- this[offset] = value
+ this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
@@ -1590,7 +1825,7 @@ Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
- this[offset + 3] = value
+ this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
@@ -1643,7 +1878,7 @@ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
- this[offset] = value
+ this[offset] = (value & 0xff)
return offset + 1
}
@@ -1652,7 +1887,7 @@ Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert)
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = value
+ this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
@@ -1666,7 +1901,7 @@ Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert)
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
- this[offset + 1] = value
+ this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
@@ -1678,7 +1913,7 @@ Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert)
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = value
+ this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
@@ -1697,7 +1932,7 @@ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
- this[offset + 3] = value
+ this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
@@ -2051,7 +2286,7 @@ function blitBuffer (src, dst, offset, length) {
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"base64-js":2,"ieee754":16,"is-array":20}],7:[function(require,module,exports){
+},{"base64-js":3,"ieee754":44,"is-array":49}],9:[function(require,module,exports){
module.exports = {
"100": "Continue",
"101": "Switching Protocols",
@@ -2112,7 +2347,7 @@ module.exports = {
"511": "Network Authentication Required"
}
-},{}],8:[function(require,module,exports){
+},{}],10:[function(require,module,exports){
var Stat = require('fs').Stats
module.exports = cloneStats
@@ -2127,7 +2362,7 @@ function cloneStats(stats) {
return replacement
}
-},{"fs":4}],9:[function(require,module,exports){
+},{"fs":6}],11:[function(require,module,exports){
(function (Buffer){
var clone = (function() {
'use strict';
@@ -2291,19 +2526,34 @@ if (typeof module === 'object' && module.exports) {
}
}).call(this,require("buffer").Buffer)
-},{"buffer":6}],10:[function(require,module,exports){
-module.exports={
- "O_RDONLY": 0,
- "O_WRONLY": 1,
- "O_RDWR": 2,
- "S_IFMT": 61440,
- "S_IFREG": 32768,
- "S_IFDIR": 16384,
- "S_IFCHR": 8192,
- "S_IFBLK": 24576,
- "S_IFIFO": 4096,
- "S_IFLNK": 40960,
- "S_IFSOCK": 49152,
+},{"buffer":8}],12:[function(require,module,exports){
+module.exports = function (xs, fn) {
+ var res = [];
+ for (var i = 0; i < xs.length; i++) {
+ var x = fn(xs[i], i);
+ if (isArray(x)) res.push.apply(res, x);
+ else res.push(x);
+ }
+ return res;
+};
+
+var isArray = Array.isArray || function (xs) {
+ return Object.prototype.toString.call(xs) === '[object Array]';
+};
+
+},{}],13:[function(require,module,exports){
+module.exports={
+ "O_RDONLY": 0,
+ "O_WRONLY": 1,
+ "O_RDWR": 2,
+ "S_IFMT": 61440,
+ "S_IFREG": 32768,
+ "S_IFDIR": 16384,
+ "S_IFCHR": 8192,
+ "S_IFBLK": 24576,
+ "S_IFIFO": 4096,
+ "S_IFLNK": 40960,
+ "S_IFSOCK": 49152,
"O_CREAT": 512,
"O_EXCL": 2048,
"O_NOCTTY": 131072,
@@ -2471,7 +2721,163 @@ module.exports={
"NPN_ENABLED": 1
}
-},{}],11:[function(require,module,exports){
+},{}],14:[function(require,module,exports){
+(function (Buffer){
+'use strict';
+var fs = require('fs');
+var path = require('path');
+
+var commentRx = /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+;)?base64,(.*)$/mg;
+var mapFileCommentRx =
+ // //# sourceMappingURL=foo.js.map
+ /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg
+
+function decodeBase64(base64) {
+ return new Buffer(base64, 'base64').toString();
+}
+
+function stripComment(sm) {
+ return sm.split(',').pop();
+}
+
+function readFromFileMap(sm, dir) {
+ // NOTE: this will only work on the server since it attempts to read the map file
+
+ var r = mapFileCommentRx.exec(sm);
+ mapFileCommentRx.lastIndex = 0;
+
+ // for some odd reason //# .. captures in 1 and /* .. */ in 2
+ var filename = r[1] || r[2];
+ var filepath = path.join(dir, filename);
+
+ try {
+ return fs.readFileSync(filepath, 'utf8');
+ } catch (e) {
+ throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e);
+ }
+}
+
+function Converter (sm, opts) {
+ opts = opts || {};
+
+ if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir);
+ if (opts.hasComment) sm = stripComment(sm);
+ if (opts.isEncoded) sm = decodeBase64(sm);
+ if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm);
+
+ this.sourcemap = sm;
+}
+
+function convertFromLargeSource(content){
+ var lines = content.split('\n');
+ var line;
+ // find first line which contains a source map starting at end of content
+ for (var i = lines.length - 1; i > 0; i--) {
+ line = lines[i]
+ if (~line.indexOf('sourceMappingURL=data:')) return exports.fromComment(line);
+ }
+}
+
+Converter.prototype.toJSON = function (space) {
+ return JSON.stringify(this.sourcemap, null, space);
+};
+
+Converter.prototype.toBase64 = function () {
+ var json = this.toJSON();
+ return new Buffer(json).toString('base64');
+};
+
+Converter.prototype.toComment = function (options) {
+ var base64 = this.toBase64();
+ var data = 'sourceMappingURL=data:application/json;base64,' + base64;
+ return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
+};
+
+// returns copy instead of original
+Converter.prototype.toObject = function () {
+ return JSON.parse(this.toJSON());
+};
+
+Converter.prototype.addProperty = function (key, value) {
+ if (this.sourcemap.hasOwnProperty(key)) throw new Error('property %s already exists on the sourcemap, use set property instead');
+ return this.setProperty(key, value);
+};
+
+Converter.prototype.setProperty = function (key, value) {
+ this.sourcemap[key] = value;
+ return this;
+};
+
+Converter.prototype.getProperty = function (key) {
+ return this.sourcemap[key];
+};
+
+exports.fromObject = function (obj) {
+ return new Converter(obj);
+};
+
+exports.fromJSON = function (json) {
+ return new Converter(json, { isJSON: true });
+};
+
+exports.fromBase64 = function (base64) {
+ return new Converter(base64, { isEncoded: true });
+};
+
+exports.fromComment = function (comment) {
+ comment = comment
+ .replace(/^\/\*/g, '//')
+ .replace(/\*\/$/g, '');
+
+ return new Converter(comment, { isEncoded: true, hasComment: true });
+};
+
+exports.fromMapFileComment = function (comment, dir) {
+ return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true });
+};
+
+// Finds last sourcemap comment in file or returns null if none was found
+exports.fromSource = function (content, largeSource) {
+ if (largeSource) return convertFromLargeSource(content);
+
+ var m = content.match(commentRx);
+ commentRx.lastIndex = 0;
+ return m ? exports.fromComment(m.pop()) : null;
+};
+
+// Finds last sourcemap comment in file or returns null if none was found
+exports.fromMapFileSource = function (content, dir) {
+ var m = content.match(mapFileCommentRx);
+ mapFileCommentRx.lastIndex = 0;
+ return m ? exports.fromMapFileComment(m.pop(), dir) : null;
+};
+
+exports.removeComments = function (src) {
+ commentRx.lastIndex = 0;
+ return src.replace(commentRx, '');
+};
+
+exports.removeMapFileComments = function (src) {
+ mapFileCommentRx.lastIndex = 0;
+ return src.replace(mapFileCommentRx, '');
+};
+
+Object.defineProperty(exports, 'commentRegex', {
+ get: function getCommentRegex () {
+ commentRx.lastIndex = 0;
+ return commentRx;
+ }
+});
+
+Object.defineProperty(exports, 'mapFileCommentRegex', {
+ get: function getMapFileCommentRegex () {
+ mapFileCommentRx.lastIndex = 0;
+ return mapFileCommentRx;
+ }
+});
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":8,"fs":6,"path":104}],15:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
@@ -2580,8 +2986,8 @@ exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
-}).call(this,{"isBuffer":require("/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js")})
-},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21}],12:[function(require,module,exports){
+}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
+},{"../../is-buffer/index.js":50}],16:[function(require,module,exports){
(function (process,Buffer){
var stream = require('readable-stream')
var eos = require('end-of-stream')
@@ -2811,7 +3217,7 @@ Duplexify.prototype.end = function(data, enc, cb) {
module.exports = Duplexify
}).call(this,require('_process'),require("buffer").Buffer)
-},{"_process":64,"buffer":6,"end-of-stream":13,"readable-stream":76,"util":90}],13:[function(require,module,exports){
+},{"_process":107,"buffer":8,"end-of-stream":17,"readable-stream":119,"util":138}],17:[function(require,module,exports){
var once = require('once');
var noop = function() {};
@@ -2884,7 +3290,7 @@ var eos = function(stream, opts, callback) {
};
module.exports = eos;
-},{"once":60}],14:[function(require,module,exports){
+},{"once":95}],18:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -3187,13353 +3593,11631 @@ function isUndefined(arg) {
return arg === void 0;
}
-},{}],15:[function(require,module,exports){
-
-var hasOwn = Object.prototype.hasOwnProperty;
-var toString = Object.prototype.toString;
+},{}],19:[function(require,module,exports){
+function findIndex(array, predicate, self) {
+ var len = array.length;
+ var i;
+ if (len === 0) return -1;
+ if (typeof predicate !== 'function') {
+ throw new TypeError(predicate + ' must be a function');
+ }
-module.exports = function forEach (obj, fn, ctx) {
- if (toString.call(fn) !== '[object Function]') {
- throw new TypeError('iterator must be a function');
+ if (self) {
+ for (i = 0; i < len; i++) {
+ if (predicate.call(self, array[i], i, array)) {
+ return i;
+ }
}
- var l = obj.length;
- if (l === +l) {
- for (var i = 0; i < l; i++) {
- fn.call(ctx, obj[i], i, obj);
- }
- } else {
- for (var k in obj) {
- if (hasOwn.call(obj, k)) {
- fn.call(ctx, obj[k], k, obj);
- }
- }
+ } else {
+ for (i = 0; i < len; i++) {
+ if (predicate(array[i], i, array)) {
+ return i;
+ }
}
-};
+ }
+ return -1;
+}
-},{}],16:[function(require,module,exports){
-exports.read = function (buffer, offset, isLE, mLen, nBytes) {
- var e, m
- var eLen = nBytes * 8 - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var nBits = -7
- var i = isLE ? (nBytes - 1) : 0
- var d = isLE ? -1 : 1
- var s = buffer[offset + i]
+module.exports = findIndex
- i += d
+},{}],20:[function(require,module,exports){
+(function (Buffer){
+'use strict';
+var util = require('util');
+var Transform = require('stream').Transform;
- e = s & ((1 << (-nBits)) - 1)
- s >>= (-nBits)
- nBits += eLen
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+function ctor(options, transform) {
+ util.inherits(FirstChunk, Transform);
- m = e & ((1 << (-nBits)) - 1)
- e >>= (-nBits)
- nBits += mLen
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+ if (typeof options === 'function') {
+ transform = options;
+ options = {};
+ }
- if (e === 0) {
- e = 1 - eBias
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity)
- } else {
- m = m + Math.pow(2, mLen)
- e = e - eBias
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
-}
+ if (typeof transform !== 'function') {
+ throw new Error('transform function required');
+ }
-exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
- var e, m, c
- var eLen = nBytes * 8 - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
- var i = isLE ? 0 : (nBytes - 1)
- var d = isLE ? 1 : -1
- var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
+ function FirstChunk(options2) {
+ if (!(this instanceof FirstChunk)) {
+ return new FirstChunk(options2);
+ }
- value = Math.abs(value)
+ Transform.call(this, options2);
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0
- e = eMax
- } else {
- e = Math.floor(Math.log(value) / Math.LN2)
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--
- c *= 2
- }
- if (e + eBias >= 1) {
- value += rt / c
- } else {
- value += rt * Math.pow(2, 1 - eBias)
- }
- if (value * c >= 2) {
- e++
- c /= 2
- }
+ this._firstChunk = true;
+ this._transformCalled = false;
+ this._minSize = options.minSize;
+ }
- if (e + eBias >= eMax) {
- m = 0
- e = eMax
- } else if (e + eBias >= 1) {
- m = (value * c - 1) * Math.pow(2, mLen)
- e = e + eBias
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
- e = 0
- }
- }
+ FirstChunk.prototype._transform = function (chunk, enc, cb) {
+ this._enc = enc;
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
+ if (this._firstChunk) {
+ this._firstChunk = false;
- e = (e << mLen) | m
- eLen += mLen
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
+ if (this._minSize == null) {
+ transform.call(this, chunk, enc, cb);
+ this._transformCalled = true;
+ return;
+ }
- buffer[offset + i - d] |= s * 128
-}
+ this._buffer = chunk;
+ cb();
+ return;
+ }
-},{}],17:[function(require,module,exports){
+ if (this._minSize == null) {
+ this.push(chunk);
+ cb();
+ return;
+ }
-var indexOf = [].indexOf;
+ if (this._buffer.length < this._minSize) {
+ this._buffer = Buffer.concat([this._buffer, chunk]);
+ cb();
+ return;
+ }
-module.exports = function(arr, obj){
- if (indexOf) return arr.indexOf(obj);
- for (var i = 0; i < arr.length; ++i) {
- if (arr[i] === obj) return i;
- }
- return -1;
-};
-},{}],18:[function(require,module,exports){
-if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- };
-} else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
-}
+ if (this._buffer.length >= this._minSize) {
+ transform.call(this, this._buffer.slice(), enc, function () {
+ this.push(chunk);
+ cb();
+ }.bind(this));
+ this._transformCalled = true;
+ this._buffer = false;
+ return;
+ }
-},{}],19:[function(require,module,exports){
-var ip = exports,
- Buffer = require('buffer').Buffer,
- os = require('os');
+ this.push(chunk);
+ cb();
+ };
-ip.toBuffer = function toBuffer(ip, buff, offset) {
- offset = ~~offset;
+ FirstChunk.prototype._flush = function (cb) {
+ if (!this._buffer) {
+ cb();
+ return;
+ }
- var result;
+ if (this._transformCalled) {
+ this.push(this._buffer);
+ cb();
+ } else {
+ transform.call(this, this._buffer.slice(), this._enc, cb);
+ }
+ };
- if (/^(\d{1,3}\.){3,3}\d{1,3}$/.test(ip)) {
- result = buff || new Buffer(offset + 4);
- ip.split(/\./g).map(function(byte) {
- result[offset++] = parseInt(byte, 10) & 0xff;
- });
- } else if (/^[a-f0-9:]+$/.test(ip)) {
- var s = ip.split(/::/g, 2),
- head = (s[0] || '').split(/:/g, 8),
- tail = (s[1] || '').split(/:/g, 8);
+ return FirstChunk;
+}
- if (tail.length === 0) {
- // xxxx::
- while (head.length < 8) head.push('0000');
- } else if (head.length === 0) {
- // ::xxxx
- while (tail.length < 8) tail.unshift('0000');
- } else {
- // xxxx::xxxx
- while (head.length + tail.length < 8) head.push('0000');
- }
+module.exports = function () {
+ return ctor.apply(ctor, arguments)();
+};
- result = buff || new Buffer(offset + 16);
- head.concat(tail).map(function(word) {
- word = parseInt(word, 16);
- result[offset++] = (word >> 8) & 0xff;
- result[offset++] = word & 0xff;
- });
- } else {
- throw Error('Invalid ip address: ' + ip);
- }
+module.exports.ctor = ctor;
- return result;
-};
+}).call(this,require("buffer").Buffer)
+},{"buffer":8,"stream":124,"util":138}],21:[function(require,module,exports){
-ip.toString = function toString(buff, offset, length) {
- offset = ~~offset;
- length = length || (buff.length - offset);
+var hasOwn = Object.prototype.hasOwnProperty;
+var toString = Object.prototype.toString;
- var result = [];
- if (length === 4) {
- // IPv4
- for (var i = 0; i < length; i++) {
- result.push(buff[offset + i]);
+module.exports = function forEach (obj, fn, ctx) {
+ if (toString.call(fn) !== '[object Function]') {
+ throw new TypeError('iterator must be a function');
}
- result = result.join('.');
- } else if (length === 16) {
- // IPv6
- for (var i = 0; i < length; i += 2) {
- result.push(buff.readUInt16BE(offset + i).toString(16));
+ var l = obj.length;
+ if (l === +l) {
+ for (var i = 0; i < l; i++) {
+ fn.call(ctx, obj[i], i, obj);
+ }
+ } else {
+ for (var k in obj) {
+ if (hasOwn.call(obj, k)) {
+ fn.call(ctx, obj[k], k, obj);
+ }
+ }
}
- result = result.join(':');
- result = result.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3');
- result = result.replace(/:{3,4}/, '::');
- }
-
- return result;
};
-ip.fromPrefixLen = function fromPrefixLen(prefixlen, family) {
- if (prefixlen > 32) {
- family = 'ipv6';
- } else {
- family = _normalizeFamily(family);
- }
-
- var len = 4;
- if (family === 'ipv6') {
- len = 16;
- }
- var buff = new Buffer(len);
-
- for (var i = 0, n = buff.length; i < n; ++i) {
- var bits = 8;
- if (prefixlen < 8) {
- bits = prefixlen;
- }
- prefixlen -= bits;
- buff[i] = ~(0xff >> bits);
- }
+},{}],22:[function(require,module,exports){
+(function (process){
+/*jslint node: true */
- return ip.toString(buff);
-};
+'use strict';
-ip.mask = function mask(addr, mask) {
- addr = ip.toBuffer(addr);
- mask = ip.toBuffer(mask);
+var through2 = require('through2');
+var Combine = require('ordered-read-streams');
+var unique = require('unique-stream');
- var result = new Buffer(Math.max(addr.length, mask.length));
+var glob = require('glob');
+var Minimatch = require('minimatch').Minimatch;
+var glob2base = require('glob2base');
+var path = require('path');
- // Same protocol - do bitwise and
- if (addr.length === mask.length) {
- for (var i = 0; i < addr.length; i++) {
- result[i] = addr[i] & mask[i];
- }
- } else if (mask.length === 4) {
- // IPv6 address and IPv4 mask
- // (Mask low bits)
- for (var i = 0; i < mask.length; i++) {
- result[i] = addr[addr.length - 4 + i] & mask[i];
- }
- } else {
- // IPv6 mask and IPv4 addr
- for (var i = 0; i < result.length - 6; i++) {
- result[i] = 0;
- }
+var gs = {
+ // creates a stream for a single glob or filter
+ createStream: function(ourGlob, negatives, opt) {
+ // remove path relativity to make globs make sense
+ ourGlob = unrelative(opt.cwd, ourGlob);
- // ::ffff:ipv4
- result[10] = 0xff;
- result[11] = 0xff;
- for (var i = 0; i < addr.length; i++) {
- result[i + 12] = addr[i] & mask[i + 12];
- }
- }
+ // create globbing stuff
+ var globber = new glob.Glob(ourGlob, opt);
- return ip.toString(result);
-};
+ // extract base path from glob
+ var basePath = opt.base || glob2base(globber);
-ip.cidr = function cidr(cidrString) {
- var cidrParts = cidrString.split('/');
+ // create stream and map events from globber to it
+ var stream = through2.obj(negatives.length ? filterNegatives : undefined);
- if (cidrParts.length != 2)
- throw new Error('invalid CIDR subnet: ' + addr);
+ var found = false;
- var addr = cidrParts[0];
- var mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10));
+ globber.on('error', stream.emit.bind(stream, 'error'));
+ globber.on('end', function(){
+ if (opt.allowEmpty !== true && !found && globIsSingular(globber)) {
+ stream.emit('error', new Error('File not found with singular glob'));
+ }
- return ip.mask(addr, mask);
-}
+ stream.end();
+ });
+ globber.on('match', function(filename) {
+ found = true;
-ip.subnet = function subnet(addr, mask) {
- var networkAddress = ip.toLong(ip.mask(addr, mask));
+ stream.write({
+ cwd: opt.cwd,
+ base: basePath,
+ path: path.resolve(opt.cwd, filename)
+ });
+ });
- // Calculate the mask's length.
- var maskBuffer = ip.toBuffer(mask);
- var maskLength = 0;
+ return stream;
- for (var i = 0; i < maskBuffer.length; i++) {
- if (maskBuffer[i] == 0xff) {
- maskLength += 8;
- } else {
- var octet = maskBuffer[i] & 0xff;
- while (octet) {
- octet = (octet << 1) & 0xff;
- maskLength++;
+ function filterNegatives(filename, enc, cb) {
+ var matcha = isMatch.bind(null, filename);
+ if (negatives.every(matcha)) {
+ cb(null, filename); // pass
+ } else {
+ cb(); // ignore
}
}
- }
+ },
- var numberOfAddresses = Math.pow(2, 32 - maskLength);
+ // creates a stream for multiple globs or filters
+ create: function(globs, opt) {
+ if (!opt) opt = {};
+ if (typeof opt.cwd !== 'string') opt.cwd = process.cwd();
+ if (typeof opt.dot !== 'boolean') opt.dot = false;
+ if (typeof opt.silent !== 'boolean') opt.silent = true;
+ if (typeof opt.nonull !== 'boolean') opt.nonull = false;
+ if (typeof opt.cwdbase !== 'boolean') opt.cwdbase = false;
+ if (opt.cwdbase) opt.base = opt.cwd;
- return {
- networkAddress: ip.fromLong(networkAddress),
- firstAddress: numberOfAddresses <= 2 ?
- ip.fromLong(networkAddress) :
- ip.fromLong(networkAddress + 1),
- lastAddress: numberOfAddresses <= 2 ?
- ip.fromLong(networkAddress + numberOfAddresses - 1) :
- ip.fromLong(networkAddress + numberOfAddresses - 2),
- broadcastAddress: ip.fromLong(networkAddress + numberOfAddresses - 1),
- subnetMask: mask,
- subnetMaskLength: maskLength,
- numHosts: numberOfAddresses <= 2 ?
- numberOfAddresses : numberOfAddresses - 2,
- length: numberOfAddresses
- };
-}
+ // only one glob no need to aggregate
+ if (!Array.isArray(globs)) globs = [globs];
-ip.cidrSubnet = function cidrSubnet(cidrString) {
- var cidrParts = cidrString.split('/');
+ var positives = [];
+ var negatives = [];
- if (cidrParts.length !== 2)
- throw new Error('invalid CIDR subnet: ' + addr);
+ globs.forEach(function(glob, index) {
+ if (typeof glob !== 'string' && !(glob instanceof RegExp)) {
+ throw new Error('Invalid glob at index ' + index);
+ }
- var addr = cidrParts[0];
- var mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10));
+ var globArray = isNegative(glob) ? negatives : positives;
- return ip.subnet(addr, mask);
-}
+ // create Minimatch instances for negative glob patterns
+ if (globArray === negatives && typeof glob === 'string') {
+ glob = new Minimatch(unrelative(opt.cwd, glob), opt);
+ }
-ip.not = function not(addr) {
- var buff = ip.toBuffer(addr);
- for (var i = 0; i < buff.length; i++) {
- buff[i] = 0xff ^ buff[i];
- }
- return ip.toString(buff);
-};
+ globArray.push({
+ index: index,
+ glob: glob
+ });
+ });
-ip.or = function or(a, b) {
- a = ip.toBuffer(a);
- b = ip.toBuffer(b);
+ if (positives.length === 0) throw new Error('Missing positive glob');
- // same protocol
- if (a.length == b.length) {
- for (var i = 0; i < a.length; ++i) {
- a[i] |= b[i];
- }
- return ip.toString(a);
+ // only one positive glob no need to aggregate
+ if (positives.length === 1) return streamFromPositive(positives[0]);
- // mixed protocols
- } else {
- var buff = a;
- var other = b;
- if (b.length > a.length) {
- buff = b;
- other = a;
- }
+ // create all individual streams
+ var streams = positives.map(streamFromPositive);
- var offset = buff.length - other.length;
- for (var i = offset; i < buff.length; ++i) {
- buff[i] |= other[i - offset];
- }
+ // then just pipe them to a single unique stream and return it
+ var aggregate = new Combine(streams);
+ var uniqueStream = unique('path');
+ var returnStream = aggregate.pipe(uniqueStream);
- return ip.toString(buff);
- }
-};
+ aggregate.on('error', function (err) {
+ returnStream.emit('error', err);
+ });
-ip.isEqual = function isEqual(a, b) {
- a = ip.toBuffer(a);
- b = ip.toBuffer(b);
+ return returnStream;
- // Same protocol
- if (a.length === b.length) {
- for (var i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) return false;
+ function streamFromPositive(positive) {
+ var negativeGlobs = negatives.filter(indexGreaterThan(positive.index)).map(toGlob);
+ return gs.createStream(positive.glob, negativeGlobs, opt);
}
- return true;
}
+};
- // Swap
- if (b.length === 4) {
- var t = b;
- b = a;
- a = t;
- }
+function isMatch(file, matcher) {
+ if (matcher instanceof Minimatch) return matcher.match(file.path);
+ if (matcher instanceof RegExp) return matcher.test(file.path);
+}
- // a - IPv4, b - IPv6
- for (var i = 0; i < 10; i++) {
- if (b[i] !== 0) return false;
+function isNegative(pattern) {
+ if (typeof pattern === 'string') return pattern[0] === '!';
+ if (pattern instanceof RegExp) return true;
+}
+
+function unrelative(cwd, glob) {
+ var mod = '';
+ if (glob[0] === '!') {
+ mod = glob[0];
+ glob = glob.slice(1);
}
+ return mod+path.resolve(cwd, glob);
+}
- var word = b.readUInt16BE(10);
- if (word !== 0 && word !== 0xffff) return false;
+function indexGreaterThan(index) {
+ return function(obj) {
+ return obj.index > index;
+ };
+}
- for (var i = 0; i < 4; i++) {
- if (a[i] !== b[i + 12]) return false;
- }
+function toGlob(obj) {
+ return obj.glob;
+}
- return true;
-};
+function globIsSingular(glob) {
+ var globSet = glob.minimatch.set;
-ip.isPrivate = function isPrivate(addr) {
- return addr.match(/^10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
- addr.match(/^192\.168\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
- addr.match(
- /^172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
- addr.match(/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
- addr.match(/^169\.254\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
- addr.match(/^fc00:/) != null || addr.match(/^fe80:/) != null ||
- addr.match(/^::1$/) != null || addr.match(/^::$/) != null;
-};
+ if (globSet.length !== 1) {
+ return false;
+ }
-ip.isPublic = function isPublic(addr) {
- return !ip.isPrivate(addr);
+ return globSet[0].every(function isString(value) {
+ return typeof value === 'string';
+ });
}
-ip.isLoopback = function isLoopback(addr) {
- return /^127\.0\.0\.1$/.test(addr)
- || /^fe80::1$/.test(addr)
- || /^::1$/.test(addr)
- || /^::$/.test(addr);
-};
-
-ip.loopback = function loopback(family) {
- //
- // Default to `ipv4`
- //
- family = _normalizeFamily(family);
-
- if (family !== 'ipv4' && family !== 'ipv6') {
- throw new Error('family must be ipv4 or ipv6');
- }
-
- return family === 'ipv4'
- ? '127.0.0.1'
- : 'fe80::1';
-};
+module.exports = gs;
+}).call(this,require('_process'))
+},{"_process":107,"glob":30,"glob2base":32,"minimatch":84,"ordered-read-streams":96,"path":104,"through2":28,"unique-stream":134}],23:[function(require,module,exports){
+(function (process){
+// Copyright Joyent, Inc. and other Node contributors.
//
-// ### function address (name, family)
-// #### @name {string|'public'|'private'} **Optional** Name or security
-// of the network interface.
-// #### @family {ipv4|ipv6} **Optional** IP family of the address (defaults
-// to ipv4).
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
//
-// Returns the address for the network interface on the current system with
-// the specified `name`:
-// * String: First `family` address of the interface.
-// If not found see `undefined`.
-// * 'public': the first public ip address of family.
-// * 'private': the first private ip address of family.
-// * undefined: First address with `ipv4` or loopback addres `127.0.0.1`.
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
//
-ip.address = function address(name, family) {
- var interfaces = os.networkInterfaces(),
- all;
-
- //
- // Default to `ipv4`
- //
- family = _normalizeFamily(family);
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
- // If a specific network interface has been named,
- // return the address.
- //
- if (name && !~['public', 'private'].indexOf(name)) {
- return interfaces[name].filter(function (details) {
- details.family = details.family.toLowerCase();
- return details.family === family;
- })[0].address;
- }
+// a duplex stream is just a stream that is both readable and writable.
+// Since JS doesn't have multiple prototypal inheritance, this class
+// prototypally inherits from Readable, and then parasitically from
+// Writable.
- var all = Object.keys(interfaces).map(function (nic) {
- //
- // Note: name will only be `public` or `private`
- // when this is called.
- //
- var addresses = interfaces[nic].filter(function (details) {
- details.family = details.family.toLowerCase();
- if (details.family !== family || ip.isLoopback(details.address)) {
- return false;
- }
- else if (!name) {
- return true;
- }
+module.exports = Duplex;
- return name === 'public'
- ? !ip.isPrivate(details.address)
- : ip.isPrivate(details.address)
- });
+/**/
+var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+ for (var key in obj) keys.push(key);
+ return keys;
+}
+/**/
- return addresses.length
- ? addresses[0].address
- : undefined;
- }).filter(Boolean);
- return !all.length
- ? ip.loopback(family)
- : all[0];
-};
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
-ip.toLong = function toInt(ip){
- var ipl=0;
- ip.split('.').forEach(function( octet ) {
- ipl<<=8;
- ipl+=parseInt(octet);
- });
- return(ipl >>>0);
-};
+var Readable = require('./_stream_readable');
+var Writable = require('./_stream_writable');
-ip.fromLong = function fromInt(ipl){
- return ( (ipl>>>24) +'.' +
- (ipl>>16 & 255) +'.' +
- (ipl>>8 & 255) +'.' +
- (ipl & 255) );
-};
+util.inherits(Duplex, Readable);
-function _normalizeFamily(family) {
- return family ? family.toLowerCase() : 'ipv4';
-}
+forEach(objectKeys(Writable.prototype), function(method) {
+ if (!Duplex.prototype[method])
+ Duplex.prototype[method] = Writable.prototype[method];
+});
-},{"buffer":6,"os":61}],20:[function(require,module,exports){
+function Duplex(options) {
+ if (!(this instanceof Duplex))
+ return new Duplex(options);
-/**
- * isArray
- */
+ Readable.call(this, options);
+ Writable.call(this, options);
-var isArray = Array.isArray;
+ if (options && options.readable === false)
+ this.readable = false;
-/**
- * toString
- */
+ if (options && options.writable === false)
+ this.writable = false;
-var str = Object.prototype.toString;
+ this.allowHalfOpen = true;
+ if (options && options.allowHalfOpen === false)
+ this.allowHalfOpen = false;
-/**
- * Whether or not the given `val`
- * is an array.
- *
- * example:
- *
- * isArray([]);
- * // > true
- * isArray(arguments);
- * // > false
- * isArray('');
- * // > false
- *
- * @param {mixed} val
- * @return {bool}
- */
+ this.once('end', onend);
+}
-module.exports = isArray || function (val) {
- return !! val && '[object Array]' == str.call(val);
-};
+// the no-half-open enforcer
+function onend() {
+ // if we allow half-open state, or if the writable side ended,
+ // then we're ok.
+ if (this.allowHalfOpen || this._writableState.ended)
+ return;
-},{}],21:[function(require,module,exports){
-/**
- * Determine if an object is Buffer
- *
- * Author: Feross Aboukhadijeh
- * License: MIT
- *
- * `npm install is-buffer`
- */
+ // no more data can be written.
+ // But allow more writes to happen in this tick.
+ process.nextTick(this.end.bind(this));
+}
-module.exports = function (obj) {
- return !!(obj != null &&
- (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor)
- (obj.constructor &&
- typeof obj.constructor.isBuffer === 'function' &&
- obj.constructor.isBuffer(obj))
- ))
+function forEach (xs, f) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ f(xs[i], i);
+ }
}
-},{}],22:[function(require,module,exports){
-module.exports = Array.isArray || function (arr) {
- return Object.prototype.toString.call(arr) == '[object Array]';
-};
+}).call(this,require('_process'))
+},{"./_stream_readable":24,"./_stream_writable":26,"_process":107,"core-util-is":15,"inherits":47}],24:[function(require,module,exports){
+(function (process){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
-},{}],23:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
+module.exports = Readable;
-/** Used to pool arrays and objects used internally */
-var arrayPool = [];
+/**/
+var isArray = require('isarray');
+/**/
-module.exports = arrayPool;
-},{}],24:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var baseCreate = require('lodash._basecreate'),
- isObject = require('lodash.isobject'),
- setBindData = require('lodash._setbinddata'),
- slice = require('lodash._slice');
+/**/
+var Buffer = require('buffer').Buffer;
+/**/
-/**
- * Used for `Array` method references.
- *
- * Normally `Array.prototype` would suffice, however, using an array literal
- * avoids issues in Narwhal.
- */
-var arrayRef = [];
+Readable.ReadableState = ReadableState;
-/** Native method shortcuts */
-var push = arrayRef.push;
+var EE = require('events').EventEmitter;
-/**
- * The base implementation of `_.bind` that creates the bound function and
- * sets its meta data.
- *
- * @private
- * @param {Array} bindData The bind data array.
- * @returns {Function} Returns the new bound function.
- */
-function baseBind(bindData) {
- var func = bindData[0],
- partialArgs = bindData[2],
- thisArg = bindData[4];
+/**/
+if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
+ return emitter.listeners(type).length;
+};
+/**/
- function bound() {
- // `Function#bind` spec
- // http://es5.github.io/#x15.3.4.5
- if (partialArgs) {
- // avoid `arguments` object deoptimizations by using `slice` instead
- // of `Array.prototype.slice.call` and not assigning `arguments` to a
- // variable as a ternary expression
- var args = slice(partialArgs);
- push.apply(args, arguments);
- }
- // mimic the constructor's `return` behavior
- // http://es5.github.io/#x13.2.2
- if (this instanceof bound) {
- // ensure `new bound` is an instance of `func`
- var thisBinding = baseCreate(func.prototype),
- result = func.apply(thisBinding, args || arguments);
- return isObject(result) ? result : thisBinding;
- }
- return func.apply(thisArg, args || arguments);
- }
- setBindData(bound, bindData);
- return bound;
-}
+var Stream = require('stream');
-module.exports = baseBind;
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
-},{"lodash._basecreate":25,"lodash._setbinddata":35,"lodash._slice":37,"lodash.isobject":45}],25:[function(require,module,exports){
-(function (global){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var isNative = require('lodash._isnative'),
- isObject = require('lodash.isobject'),
- noop = require('lodash.noop');
+var StringDecoder;
-/* Native method shortcuts for methods with the same name as other `lodash` methods */
-var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate;
+util.inherits(Readable, Stream);
-/**
- * The base implementation of `_.create` without support for assigning
- * properties to the created object.
- *
- * @private
- * @param {Object} prototype The object to inherit from.
- * @returns {Object} Returns the new object.
- */
-function baseCreate(prototype, properties) {
- return isObject(prototype) ? nativeCreate(prototype) : {};
-}
-// fallback for browsers without `Object.create`
-if (!nativeCreate) {
- baseCreate = (function() {
- function Object() {}
- return function(prototype) {
- if (isObject(prototype)) {
- Object.prototype = prototype;
- var result = new Object;
- Object.prototype = null;
- }
- return result || global.Object();
- };
- }());
-}
+function ReadableState(options, stream) {
+ options = options || {};
-module.exports = baseCreate;
+ // the point at which it stops calling _read() to fill the buffer
+ // Note: 0 is a valid value, means "don't call _read preemptively ever"
+ var hwm = options.highWaterMark;
+ this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"lodash._isnative":31,"lodash.isobject":45,"lodash.noop":48}],26:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var bind = require('lodash.bind'),
- identity = require('lodash.identity'),
- setBindData = require('lodash._setbinddata'),
- support = require('lodash.support');
+ // cast to ints.
+ this.highWaterMark = ~~this.highWaterMark;
-/** Used to detected named functions */
-var reFuncName = /^\s*function[ \n\r\t]+\w/;
+ this.buffer = [];
+ this.length = 0;
+ this.pipes = null;
+ this.pipesCount = 0;
+ this.flowing = false;
+ this.ended = false;
+ this.endEmitted = false;
+ this.reading = false;
-/** Used to detect functions containing a `this` reference */
-var reThis = /\bthis\b/;
+ // In streams that never have any data, and do push(null) right away,
+ // the consumer can miss the 'end' event if they do some I/O before
+ // consuming the stream. So, we don't emit('end') until some reading
+ // happens.
+ this.calledRead = false;
-/** Native method shortcuts */
-var fnToString = Function.prototype.toString;
+ // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, becuase any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+ this.sync = true;
-/**
- * The base implementation of `_.createCallback` without support for creating
- * "_.pluck" or "_.where" style callbacks.
- *
- * @private
- * @param {*} [func=identity] The value to convert to a callback.
- * @param {*} [thisArg] The `this` binding of the created callback.
- * @param {number} [argCount] The number of arguments the callback accepts.
- * @returns {Function} Returns a callback function.
- */
-function baseCreateCallback(func, thisArg, argCount) {
- if (typeof func != 'function') {
- return identity;
- }
- // exit early for no `thisArg` or already bound by `Function#bind`
- if (typeof thisArg == 'undefined' || !('prototype' in func)) {
- return func;
- }
- var bindData = func.__bindData__;
- if (typeof bindData == 'undefined') {
- if (support.funcNames) {
- bindData = !func.name;
- }
- bindData = bindData || !support.funcDecomp;
- if (!bindData) {
- var source = fnToString.call(func);
- if (!support.funcNames) {
- bindData = !reFuncName.test(source);
- }
- if (!bindData) {
- // checks if `func` references the `this` keyword and stores the result
- bindData = reThis.test(source);
- setBindData(func, bindData);
- }
- }
- }
- // exit early if there are no `this` references or `func` is bound
- if (bindData === false || (bindData !== true && bindData[1] & 1)) {
- return func;
- }
- switch (argCount) {
- case 1: return function(value) {
- return func.call(thisArg, value);
- };
- case 2: return function(a, b) {
- return func.call(thisArg, a, b);
- };
- case 3: return function(value, index, collection) {
- return func.call(thisArg, value, index, collection);
- };
- case 4: return function(accumulator, value, index, collection) {
- return func.call(thisArg, accumulator, value, index, collection);
- };
- }
- return bind(func, thisArg);
-}
+ // whenever we return null, then we set a flag to say
+ // that we're awaiting a 'readable' event emission.
+ this.needReadable = false;
+ this.emittedReadable = false;
+ this.readableListening = false;
-module.exports = baseCreateCallback;
-},{"lodash._setbinddata":35,"lodash.bind":38,"lodash.identity":43,"lodash.support":50}],27:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var baseCreate = require('lodash._basecreate'),
- isObject = require('lodash.isobject'),
- setBindData = require('lodash._setbinddata'),
- slice = require('lodash._slice');
+ // object stream flag. Used to make read(n) ignore n and to
+ // make all the buffer merging and length checks go away
+ this.objectMode = !!options.objectMode;
-/**
- * Used for `Array` method references.
- *
- * Normally `Array.prototype` would suffice, however, using an array literal
- * avoids issues in Narwhal.
- */
-var arrayRef = [];
+ // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+ this.defaultEncoding = options.defaultEncoding || 'utf8';
-/** Native method shortcuts */
-var push = arrayRef.push;
+ // when piping, we only care about 'readable' events that happen
+ // after read()ing all the bytes and not getting any pushback.
+ this.ranOut = false;
-/**
- * The base implementation of `createWrapper` that creates the wrapper and
- * sets its meta data.
- *
- * @private
- * @param {Array} bindData The bind data array.
- * @returns {Function} Returns the new function.
- */
-function baseCreateWrapper(bindData) {
- var func = bindData[0],
- bitmask = bindData[1],
- partialArgs = bindData[2],
- partialRightArgs = bindData[3],
- thisArg = bindData[4],
- arity = bindData[5];
+ // the number of writers that are awaiting a drain event in .pipe()s
+ this.awaitDrain = 0;
- var isBind = bitmask & 1,
- isBindKey = bitmask & 2,
- isCurry = bitmask & 4,
- isCurryBound = bitmask & 8,
- key = func;
+ // if true, a maybeReadMore has been scheduled
+ this.readingMore = false;
- function bound() {
- var thisBinding = isBind ? thisArg : this;
- if (partialArgs) {
- var args = slice(partialArgs);
- push.apply(args, arguments);
- }
- if (partialRightArgs || isCurry) {
- args || (args = slice(arguments));
- if (partialRightArgs) {
- push.apply(args, partialRightArgs);
- }
- if (isCurry && args.length < arity) {
- bitmask |= 16 & ~32;
- return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
- }
- }
- args || (args = arguments);
- if (isBindKey) {
- func = thisBinding[key];
- }
- if (this instanceof bound) {
- thisBinding = baseCreate(func.prototype);
- var result = func.apply(thisBinding, args);
- return isObject(result) ? result : thisBinding;
- }
- return func.apply(thisBinding, args);
+ this.decoder = null;
+ this.encoding = null;
+ if (options.encoding) {
+ if (!StringDecoder)
+ StringDecoder = require('string_decoder/').StringDecoder;
+ this.decoder = new StringDecoder(options.encoding);
+ this.encoding = options.encoding;
}
- setBindData(bound, bindData);
- return bound;
}
-module.exports = baseCreateWrapper;
-
-},{"lodash._basecreate":25,"lodash._setbinddata":35,"lodash._slice":37,"lodash.isobject":45}],28:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var forIn = require('lodash.forin'),
- getArray = require('lodash._getarray'),
- isFunction = require('lodash.isfunction'),
- objectTypes = require('lodash._objecttypes'),
- releaseArray = require('lodash._releasearray');
+function Readable(options) {
+ if (!(this instanceof Readable))
+ return new Readable(options);
-/** `Object#toString` result shortcuts */
-var argsClass = '[object Arguments]',
- arrayClass = '[object Array]',
- boolClass = '[object Boolean]',
- dateClass = '[object Date]',
- numberClass = '[object Number]',
- objectClass = '[object Object]',
- regexpClass = '[object RegExp]',
- stringClass = '[object String]';
+ this._readableState = new ReadableState(options, this);
-/** Used for native method references */
-var objectProto = Object.prototype;
+ // legacy
+ this.readable = true;
-/** Used to resolve the internal [[Class]] of values */
-var toString = objectProto.toString;
+ Stream.call(this);
+}
-/** Native method shortcuts */
-var hasOwnProperty = objectProto.hasOwnProperty;
+// Manually shove something into the read() buffer.
+// This returns true if the highWaterMark has not been hit yet,
+// similar to how Writable.write() returns true if you should
+// write() some more.
+Readable.prototype.push = function(chunk, encoding) {
+ var state = this._readableState;
-/**
- * The base implementation of `_.isEqual`, without support for `thisArg` binding,
- * that allows partial "_.where" style comparisons.
- *
- * @private
- * @param {*} a The value to compare.
- * @param {*} b The other value to compare.
- * @param {Function} [callback] The function to customize comparing values.
- * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
- * @param {Array} [stackA=[]] Tracks traversed `a` objects.
- * @param {Array} [stackB=[]] Tracks traversed `b` objects.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- */
-function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
- // used to indicate that when comparing objects, `a` has at least the properties of `b`
- if (callback) {
- var result = callback(a, b);
- if (typeof result != 'undefined') {
- return !!result;
+ if (typeof chunk === 'string' && !state.objectMode) {
+ encoding = encoding || state.defaultEncoding;
+ if (encoding !== state.encoding) {
+ chunk = new Buffer(chunk, encoding);
+ encoding = '';
}
}
- // exit early for identical values
- if (a === b) {
- // treat `+0` vs. `-0` as not equal
- return a !== 0 || (1 / a == 1 / b);
- }
- var type = typeof a,
- otherType = typeof b;
-
- // exit early for unlike primitive values
- if (a === a &&
- !(a && objectTypes[type]) &&
- !(b && objectTypes[otherType])) {
- return false;
- }
- // exit early for `null` and `undefined` avoiding ES3's Function#call behavior
- // http://es5.github.io/#x15.3.4.4
- if (a == null || b == null) {
- return a === b;
- }
- // compare [[Class]] names
- var className = toString.call(a),
- otherClass = toString.call(b);
- if (className == argsClass) {
- className = objectClass;
- }
- if (otherClass == argsClass) {
- otherClass = objectClass;
- }
- if (className != otherClass) {
- return false;
- }
- switch (className) {
- case boolClass:
- case dateClass:
- // coerce dates and booleans to numbers, dates to milliseconds and booleans
- // to `1` or `0` treating invalid dates coerced to `NaN` as not equal
- return +a == +b;
+ return readableAddChunk(this, state, chunk, encoding, false);
+};
- case numberClass:
- // treat `NaN` vs. `NaN` as equal
- return (a != +a)
- ? b != +b
- // but treat `+0` vs. `-0` as not equal
- : (a == 0 ? (1 / a == 1 / b) : a == +b);
+// Unshift should *always* be something directly out of read()
+Readable.prototype.unshift = function(chunk) {
+ var state = this._readableState;
+ return readableAddChunk(this, state, chunk, '', true);
+};
- case regexpClass:
- case stringClass:
- // coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
- // treat string primitives and their corresponding object instances as equal
- return a == String(b);
- }
- var isArr = className == arrayClass;
- if (!isArr) {
- // unwrap any `lodash` wrapped values
- var aWrapped = hasOwnProperty.call(a, '__wrapped__'),
- bWrapped = hasOwnProperty.call(b, '__wrapped__');
+function readableAddChunk(stream, state, chunk, encoding, addToFront) {
+ var er = chunkInvalid(state, chunk);
+ if (er) {
+ stream.emit('error', er);
+ } else if (chunk === null || chunk === undefined) {
+ state.reading = false;
+ if (!state.ended)
+ onEofChunk(stream, state);
+ } else if (state.objectMode || chunk && chunk.length > 0) {
+ if (state.ended && !addToFront) {
+ var e = new Error('stream.push() after EOF');
+ stream.emit('error', e);
+ } else if (state.endEmitted && addToFront) {
+ var e = new Error('stream.unshift() after end event');
+ stream.emit('error', e);
+ } else {
+ if (state.decoder && !addToFront && !encoding)
+ chunk = state.decoder.write(chunk);
- if (aWrapped || bWrapped) {
- return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB);
- }
- // exit for functions and DOM nodes
- if (className != objectClass) {
- return false;
- }
- // in older versions of Opera, `arguments` objects have `Array` constructors
- var ctorA = a.constructor,
- ctorB = b.constructor;
+ // update the buffer info.
+ state.length += state.objectMode ? 1 : chunk.length;
+ if (addToFront) {
+ state.buffer.unshift(chunk);
+ } else {
+ state.reading = false;
+ state.buffer.push(chunk);
+ }
- // non `Object` object instances with different constructors are not equal
- if (ctorA != ctorB &&
- !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
- ('constructor' in a && 'constructor' in b)
- ) {
- return false;
- }
- }
- // assume cyclic structures are equal
- // the algorithm for detecting cyclic structures is adapted from ES 5.1
- // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
- var initedStack = !stackA;
- stackA || (stackA = getArray());
- stackB || (stackB = getArray());
+ if (state.needReadable)
+ emitReadable(stream);
- var length = stackA.length;
- while (length--) {
- if (stackA[length] == a) {
- return stackB[length] == b;
+ maybeReadMore(stream, state);
}
+ } else if (!addToFront) {
+ state.reading = false;
}
- var size = 0;
- result = true;
- // add `a` and `b` to the stack of traversed objects
- stackA.push(a);
- stackB.push(b);
+ return needMoreData(state);
+}
- // recursively compare objects and arrays (susceptible to call stack limits)
- if (isArr) {
- // compare lengths to determine if a deep comparison is necessary
- length = a.length;
- size = b.length;
- result = size == length;
- if (result || isWhere) {
- // deep compare the contents, ignoring non-numeric properties
- while (size--) {
- var index = length,
- value = b[size];
- if (isWhere) {
- while (index--) {
- if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
- break;
- }
- }
- } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
- break;
- }
- }
- }
- }
- else {
- // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
- // which, in this case, is more costly
- forIn(b, function(value, key, b) {
- if (hasOwnProperty.call(b, key)) {
- // count the number of properties.
- size++;
- // deep compare each property value.
- return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
- }
- });
+// if it's past the high water mark, we can push in some more.
+// Also, if we have no data yet, we can stand some
+// more bytes. This is to work around cases where hwm=0,
+// such as the repl. Also, if the push() triggered a
+// readable event, and the user called read(largeNumber) such that
+// needReadable was set, then we ought to push more, so that another
+// 'readable' event will be triggered.
+function needMoreData(state) {
+ return !state.ended &&
+ (state.needReadable ||
+ state.length < state.highWaterMark ||
+ state.length === 0);
+}
- if (result && !isWhere) {
- // ensure both objects have the same number of properties
- forIn(a, function(value, key, a) {
- if (hasOwnProperty.call(a, key)) {
- // `size` will be `-1` if `a` has more properties than `b`
- return (result = --size > -1);
- }
- });
- }
- }
- stackA.pop();
- stackB.pop();
+// backwards compatibility.
+Readable.prototype.setEncoding = function(enc) {
+ if (!StringDecoder)
+ StringDecoder = require('string_decoder/').StringDecoder;
+ this._readableState.decoder = new StringDecoder(enc);
+ this._readableState.encoding = enc;
+};
- if (initedStack) {
- releaseArray(stackA);
- releaseArray(stackB);
+// Don't raise the hwm > 128MB
+var MAX_HWM = 0x800000;
+function roundUpToNextPowerOf2(n) {
+ if (n >= MAX_HWM) {
+ n = MAX_HWM;
+ } else {
+ // Get the next highest power of 2
+ n--;
+ for (var p = 1; p < 32; p <<= 1) n |= n >> p;
+ n++;
}
- return result;
+ return n;
}
-module.exports = baseIsEqual;
+function howMuchToRead(n, state) {
+ if (state.length === 0 && state.ended)
+ return 0;
-},{"lodash._getarray":30,"lodash._objecttypes":33,"lodash._releasearray":34,"lodash.forin":41,"lodash.isfunction":44}],29:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var baseBind = require('lodash._basebind'),
- baseCreateWrapper = require('lodash._basecreatewrapper'),
- isFunction = require('lodash.isfunction'),
- slice = require('lodash._slice');
+ if (state.objectMode)
+ return n === 0 ? 0 : 1;
-/**
- * Used for `Array` method references.
- *
- * Normally `Array.prototype` would suffice, however, using an array literal
- * avoids issues in Narwhal.
- */
-var arrayRef = [];
+ if (n === null || isNaN(n)) {
+ // only flow one buffer at a time
+ if (state.flowing && state.buffer.length)
+ return state.buffer[0].length;
+ else
+ return state.length;
+ }
-/** Native method shortcuts */
-var push = arrayRef.push,
- unshift = arrayRef.unshift;
+ if (n <= 0)
+ return 0;
-/**
- * Creates a function that, when called, either curries or invokes `func`
- * with an optional `this` binding and partially applied arguments.
- *
- * @private
- * @param {Function|string} func The function or method name to reference.
- * @param {number} bitmask The bitmask of method flags to compose.
- * The bitmask may be composed of the following flags:
- * 1 - `_.bind`
- * 2 - `_.bindKey`
- * 4 - `_.curry`
- * 8 - `_.curry` (bound)
- * 16 - `_.partial`
- * 32 - `_.partialRight`
- * @param {Array} [partialArgs] An array of arguments to prepend to those
- * provided to the new function.
- * @param {Array} [partialRightArgs] An array of arguments to append to those
- * provided to the new function.
- * @param {*} [thisArg] The `this` binding of `func`.
- * @param {number} [arity] The arity of `func`.
- * @returns {Function} Returns the new function.
- */
-function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
- var isBind = bitmask & 1,
- isBindKey = bitmask & 2,
- isCurry = bitmask & 4,
- isCurryBound = bitmask & 8,
- isPartial = bitmask & 16,
- isPartialRight = bitmask & 32;
+ // If we're asking for more than the target buffer level,
+ // then raise the water mark. Bump up to the next highest
+ // power of 2, to prevent increasing it excessively in tiny
+ // amounts.
+ if (n > state.highWaterMark)
+ state.highWaterMark = roundUpToNextPowerOf2(n);
- if (!isBindKey && !isFunction(func)) {
- throw new TypeError;
- }
- if (isPartial && !partialArgs.length) {
- bitmask &= ~16;
- isPartial = partialArgs = false;
- }
- if (isPartialRight && !partialRightArgs.length) {
- bitmask &= ~32;
- isPartialRight = partialRightArgs = false;
- }
- var bindData = func && func.__bindData__;
- if (bindData && bindData !== true) {
- // clone `bindData`
- bindData = slice(bindData);
- if (bindData[2]) {
- bindData[2] = slice(bindData[2]);
- }
- if (bindData[3]) {
- bindData[3] = slice(bindData[3]);
- }
- // set `thisBinding` is not previously bound
- if (isBind && !(bindData[1] & 1)) {
- bindData[4] = thisArg;
- }
- // set if previously bound but not currently (subsequent curried functions)
- if (!isBind && bindData[1] & 1) {
- bitmask |= 8;
- }
- // set curried arity if not yet set
- if (isCurry && !(bindData[1] & 4)) {
- bindData[5] = arity;
- }
- // append partial left arguments
- if (isPartial) {
- push.apply(bindData[2] || (bindData[2] = []), partialArgs);
- }
- // append partial right arguments
- if (isPartialRight) {
- unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
- }
- // merge flags
- bindData[1] |= bitmask;
- return createWrapper.apply(null, bindData);
+ // don't have that much. return null, unless we've ended.
+ if (n > state.length) {
+ if (!state.ended) {
+ state.needReadable = true;
+ return 0;
+ } else
+ return state.length;
}
- // fast path for `_.bind`
- var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper;
- return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]);
-}
-
-module.exports = createWrapper;
-
-},{"lodash._basebind":24,"lodash._basecreatewrapper":27,"lodash._slice":37,"lodash.isfunction":44}],30:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var arrayPool = require('lodash._arraypool');
-/**
- * Gets an array from the array pool or creates a new one if the pool is empty.
- *
- * @private
- * @returns {Array} The array from the pool.
- */
-function getArray() {
- return arrayPool.pop() || [];
+ return n;
}
-module.exports = getArray;
+// you can override either this method, or the async _read(n) below.
+Readable.prototype.read = function(n) {
+ var state = this._readableState;
+ state.calledRead = true;
+ var nOrig = n;
+ var ret;
-},{"lodash._arraypool":23}],31:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
+ if (typeof n !== 'number' || n > 0)
+ state.emittedReadable = false;
-/** Used for native method references */
-var objectProto = Object.prototype;
+ // if we're doing read(0) to trigger a readable event, but we
+ // already have a bunch of data in the buffer, then just trigger
+ // the 'readable' event and move on.
+ if (n === 0 &&
+ state.needReadable &&
+ (state.length >= state.highWaterMark || state.ended)) {
+ emitReadable(this);
+ return null;
+ }
-/** Used to resolve the internal [[Class]] of values */
-var toString = objectProto.toString;
+ n = howMuchToRead(n, state);
-/** Used to detect if a method is native */
-var reNative = RegExp('^' +
- String(toString)
- .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
- .replace(/toString| for [^\]]+/g, '.*?') + '$'
-);
+ // if we've ended, and we're now clear, then finish it up.
+ if (n === 0 && state.ended) {
+ ret = null;
-/**
- * Checks if `value` is a native function.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if the `value` is a native function, else `false`.
- */
-function isNative(value) {
- return typeof value == 'function' && reNative.test(value);
-}
+ // In cases where the decoder did not receive enough data
+ // to produce a full chunk, then immediately received an
+ // EOF, state.buffer will contain [, ].
+ // howMuchToRead will see this and coerce the amount to
+ // read to zero (because it's looking at the length of the
+ // first in state.buffer), and we'll end up here.
+ //
+ // This can only happen via state.decoder -- no other venue
+ // exists for pushing a zero-length chunk into state.buffer
+ // and triggering this behavior. In this case, we return our
+ // remaining data and end the stream, if appropriate.
+ if (state.length > 0 && state.decoder) {
+ ret = fromList(n, state);
+ state.length -= ret.length;
+ }
-module.exports = isNative;
+ if (state.length === 0)
+ endReadable(this);
-},{}],32:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
+ return ret;
+ }
-/** Used as the max size of the `arrayPool` and `objectPool` */
-var maxPoolSize = 40;
+ // All the actual chunk generation logic needs to be
+ // *below* the call to _read. The reason is that in certain
+ // synthetic stream cases, such as passthrough streams, _read
+ // may be a completely synchronous operation which may change
+ // the state of the read buffer, providing enough data when
+ // before there was *not* enough.
+ //
+ // So, the steps are:
+ // 1. Figure out what the state of things will be after we do
+ // a read from the buffer.
+ //
+ // 2. If that resulting state will trigger a _read, then call _read.
+ // Note that this may be asynchronous, or synchronous. Yes, it is
+ // deeply ugly to write APIs this way, but that still doesn't mean
+ // that the Readable class should behave improperly, as streams are
+ // designed to be sync/async agnostic.
+ // Take note if the _read call is sync or async (ie, if the read call
+ // has returned yet), so that we know whether or not it's safe to emit
+ // 'readable' etc.
+ //
+ // 3. Actually pull the requested chunks out of the buffer and return.
-module.exports = maxPoolSize;
+ // if we need a readable event, then we need to do some reading.
+ var doRead = state.needReadable;
-},{}],33:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
+ // if we currently have less than the highWaterMark, then also read some
+ if (state.length - n <= state.highWaterMark)
+ doRead = true;
-/** Used to determine if values are of the language type Object */
-var objectTypes = {
- 'boolean': false,
- 'function': true,
- 'object': true,
- 'number': false,
- 'string': false,
- 'undefined': false
-};
+ // however, if we've ended, then there's no point, and if we're already
+ // reading, then it's unnecessary.
+ if (state.ended || state.reading)
+ doRead = false;
-module.exports = objectTypes;
+ if (doRead) {
+ state.reading = true;
+ state.sync = true;
+ // if the length is currently zero, then we *need* a readable event.
+ if (state.length === 0)
+ state.needReadable = true;
+ // call internal read method
+ this._read(state.highWaterMark);
+ state.sync = false;
+ }
-},{}],34:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var arrayPool = require('lodash._arraypool'),
- maxPoolSize = require('lodash._maxpoolsize');
+ // If _read called its callback synchronously, then `reading`
+ // will be false, and we need to re-evaluate how much data we
+ // can return to the user.
+ if (doRead && !state.reading)
+ n = howMuchToRead(nOrig, state);
-/**
- * Releases the given array back to the array pool.
- *
- * @private
- * @param {Array} [array] The array to release.
- */
-function releaseArray(array) {
- array.length = 0;
- if (arrayPool.length < maxPoolSize) {
- arrayPool.push(array);
+ if (n > 0)
+ ret = fromList(n, state);
+ else
+ ret = null;
+
+ if (ret === null) {
+ state.needReadable = true;
+ n = 0;
}
-}
-module.exports = releaseArray;
+ state.length -= n;
-},{"lodash._arraypool":23,"lodash._maxpoolsize":32}],35:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var isNative = require('lodash._isnative'),
- noop = require('lodash.noop');
+ // If we have nothing in the buffer, then we want to know
+ // as soon as we *do* get something into the buffer.
+ if (state.length === 0 && !state.ended)
+ state.needReadable = true;
-/** Used as the property descriptor for `__bindData__` */
-var descriptor = {
- 'configurable': false,
- 'enumerable': false,
- 'value': null,
- 'writable': false
+ // If we happened to read() exactly the remaining amount in the
+ // buffer, and the EOF has been seen at this point, then make sure
+ // that we emit 'end' on the very next tick.
+ if (state.ended && !state.endEmitted && state.length === 0)
+ endReadable(this);
+
+ return ret;
};
-/** Used to set meta data on functions */
-var defineProperty = (function() {
- // IE 8 only accepts DOM elements
- try {
- var o = {},
- func = isNative(func = Object.defineProperty) && func,
- result = func(o, o, o) && func;
- } catch(e) { }
- return result;
-}());
+function chunkInvalid(state, chunk) {
+ var er = null;
+ if (!Buffer.isBuffer(chunk) &&
+ 'string' !== typeof chunk &&
+ chunk !== null &&
+ chunk !== undefined &&
+ !state.objectMode) {
+ er = new TypeError('Invalid non-string/buffer chunk');
+ }
+ return er;
+}
-/**
- * Sets `this` binding data on a given function.
- *
- * @private
- * @param {Function} func The function to set data on.
- * @param {Array} value The data array to set.
- */
-var setBindData = !defineProperty ? noop : function(func, value) {
- descriptor.value = value;
- defineProperty(func, '__bindData__', descriptor);
-};
-module.exports = setBindData;
+function onEofChunk(stream, state) {
+ if (state.decoder && !state.ended) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length) {
+ state.buffer.push(chunk);
+ state.length += state.objectMode ? 1 : chunk.length;
+ }
+ }
+ state.ended = true;
-},{"lodash._isnative":31,"lodash.noop":48}],36:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var objectTypes = require('lodash._objecttypes');
+ // if we've ended and we have some data left, then emit
+ // 'readable' now to make sure it gets picked up.
+ if (state.length > 0)
+ emitReadable(stream);
+ else
+ endReadable(stream);
+}
-/** Used for native method references */
-var objectProto = Object.prototype;
+// Don't emit readable right away in sync mode, because this can trigger
+// another read() call => stack overflow. This way, it might trigger
+// a nextTick recursion warning, but that's not so bad.
+function emitReadable(stream) {
+ var state = stream._readableState;
+ state.needReadable = false;
+ if (state.emittedReadable)
+ return;
-/** Native method shortcuts */
-var hasOwnProperty = objectProto.hasOwnProperty;
+ state.emittedReadable = true;
+ if (state.sync)
+ process.nextTick(function() {
+ emitReadable_(stream);
+ });
+ else
+ emitReadable_(stream);
+}
-/**
- * A fallback implementation of `Object.keys` which produces an array of the
- * given object's own enumerable property names.
- *
- * @private
- * @type Function
- * @param {Object} object The object to inspect.
- * @returns {Array} Returns an array of property names.
- */
-var shimKeys = function(object) {
- var index, iterable = object, result = [];
- if (!iterable) return result;
- if (!(objectTypes[typeof object])) return result;
- for (index in iterable) {
- if (hasOwnProperty.call(iterable, index)) {
- result.push(index);
- }
- }
- return result
-};
+function emitReadable_(stream) {
+ stream.emit('readable');
+}
-module.exports = shimKeys;
-},{"lodash._objecttypes":33}],37:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-
-/**
- * Slices the `collection` from the `start` index up to, but not including,
- * the `end` index.
- *
- * Note: This function is used instead of `Array#slice` to support node lists
- * in IE < 9 and to ensure dense arrays are returned.
- *
- * @private
- * @param {Array|Object|string} collection The collection to slice.
- * @param {number} start The start index.
- * @param {number} end The end index.
- * @returns {Array} Returns the new array.
- */
-function slice(array, start, end) {
- start || (start = 0);
- if (typeof end == 'undefined') {
- end = array ? array.length : 0;
+// at this point, the user has presumably seen the 'readable' event,
+// and called read() to consume some data. that may have triggered
+// in turn another _read(n) call, in which case reading = true if
+// it's in progress.
+// However, if we're not ended, or reading, and the length < hwm,
+// then go ahead and try to read some more preemptively.
+function maybeReadMore(stream, state) {
+ if (!state.readingMore) {
+ state.readingMore = true;
+ process.nextTick(function() {
+ maybeReadMore_(stream, state);
+ });
}
- var index = -1,
- length = end - start || 0,
- result = Array(length < 0 ? 0 : length);
+}
- while (++index < length) {
- result[index] = array[start + index];
+function maybeReadMore_(stream, state) {
+ var len = state.length;
+ while (!state.reading && !state.flowing && !state.ended &&
+ state.length < state.highWaterMark) {
+ stream.read(0);
+ if (len === state.length)
+ // didn't get any data, stop spinning.
+ break;
+ else
+ len = state.length;
}
- return result;
+ state.readingMore = false;
}
-module.exports = slice;
+// abstract method. to be overridden in specific implementation classes.
+// call cb(er, data) where data is <= n in length.
+// for virtual (non-string, non-buffer) streams, "length" is somewhat
+// arbitrary, and perhaps not very meaningful.
+Readable.prototype._read = function(n) {
+ this.emit('error', new Error('not implemented'));
+};
-},{}],38:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var createWrapper = require('lodash._createwrapper'),
- slice = require('lodash._slice');
+Readable.prototype.pipe = function(dest, pipeOpts) {
+ var src = this;
+ var state = this._readableState;
-/**
- * Creates a function that, when called, invokes `func` with the `this`
- * binding of `thisArg` and prepends any additional `bind` arguments to those
- * provided to the bound function.
- *
- * @static
- * @memberOf _
- * @category Functions
- * @param {Function} func The function to bind.
- * @param {*} [thisArg] The `this` binding of `func`.
- * @param {...*} [arg] Arguments to be partially applied.
- * @returns {Function} Returns the new bound function.
- * @example
- *
- * var func = function(greeting) {
- * return greeting + ' ' + this.name;
- * };
- *
- * func = _.bind(func, { 'name': 'fred' }, 'hi');
- * func();
- * // => 'hi fred'
- */
-function bind(func, thisArg) {
- return arguments.length > 2
- ? createWrapper(func, 17, slice(arguments, 2), null, thisArg)
- : createWrapper(func, 1, null, null, thisArg);
-}
+ switch (state.pipesCount) {
+ case 0:
+ state.pipes = dest;
+ break;
+ case 1:
+ state.pipes = [state.pipes, dest];
+ break;
+ default:
+ state.pipes.push(dest);
+ break;
+ }
+ state.pipesCount += 1;
-module.exports = bind;
+ var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
+ dest !== process.stdout &&
+ dest !== process.stderr;
-},{"lodash._createwrapper":29,"lodash._slice":37}],39:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.3 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var baseCreateCallback = require('lodash._basecreatecallback'),
- baseIsEqual = require('lodash._baseisequal'),
- isObject = require('lodash.isobject'),
- keys = require('lodash.keys'),
- property = require('lodash.property');
+ var endFn = doEnd ? onend : cleanup;
+ if (state.endEmitted)
+ process.nextTick(endFn);
+ else
+ src.once('end', endFn);
-/**
- * Produces a callback bound to an optional `thisArg`. If `func` is a property
- * name the created callback will return the property value for a given element.
- * If `func` is an object the created callback will return `true` for elements
- * that contain the equivalent object properties, otherwise it will return `false`.
- *
- * @static
- * @memberOf _
- * @category Utilities
- * @param {*} [func=identity] The value to convert to a callback.
- * @param {*} [thisArg] The `this` binding of the created callback.
- * @param {number} [argCount] The number of arguments the callback accepts.
- * @returns {Function} Returns a callback function.
- * @example
- *
- * var characters = [
- * { 'name': 'barney', 'age': 36 },
- * { 'name': 'fred', 'age': 40 }
- * ];
- *
- * // wrap to create custom callback shorthands
- * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
- * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
- * return !match ? func(callback, thisArg) : function(object) {
- * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
- * };
- * });
- *
- * _.filter(characters, 'age__gt38');
- * // => [{ 'name': 'fred', 'age': 40 }]
- */
-function createCallback(func, thisArg, argCount) {
- var type = typeof func;
- if (func == null || type == 'function') {
- return baseCreateCallback(func, thisArg, argCount);
+ dest.on('unpipe', onunpipe);
+ function onunpipe(readable) {
+ if (readable !== src) return;
+ cleanup();
}
- // handle "_.pluck" style callback shorthands
- if (type != 'object') {
- return property(func);
+
+ function onend() {
+ dest.end();
}
- var props = keys(func),
- key = props[0],
- a = func[key];
- // handle "_.where" style callback shorthands
- if (props.length == 1 && a === a && !isObject(a)) {
- // fast path the common case of providing an object with a single
- // property containing a primitive value
- return function(object) {
- var b = object[key];
- return a === b && (a !== 0 || (1 / a == 1 / b));
- };
+ // when the dest drains, it reduces the awaitDrain counter
+ // on the source. This would be more elegant with a .once()
+ // handler in flow(), but adding and removing repeatedly is
+ // too slow.
+ var ondrain = pipeOnDrain(src);
+ dest.on('drain', ondrain);
+
+ function cleanup() {
+ // cleanup event handlers once the pipe is broken
+ dest.removeListener('close', onclose);
+ dest.removeListener('finish', onfinish);
+ dest.removeListener('drain', ondrain);
+ dest.removeListener('error', onerror);
+ dest.removeListener('unpipe', onunpipe);
+ src.removeListener('end', onend);
+ src.removeListener('end', cleanup);
+
+ // if the reader is waiting for a drain event from this
+ // specific writer, then it would cause it to never start
+ // flowing again.
+ // So, if this is awaiting a drain, then we just call it now.
+ // If we don't know, then assume that we are waiting for one.
+ if (!dest._writableState || dest._writableState.needDrain)
+ ondrain();
}
- return function(object) {
- var length = props.length,
- result = false;
- while (length--) {
- if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
- break;
- }
- }
- return result;
- };
-}
+ // if the dest has an error, then stop piping into it.
+ // however, don't suppress the throwing behavior for this.
+ function onerror(er) {
+ unpipe();
+ dest.removeListener('error', onerror);
+ if (EE.listenerCount(dest, 'error') === 0)
+ dest.emit('error', er);
+ }
+ // This is a brutally ugly hack to make sure that our error handler
+ // is attached before any userland ones. NEVER DO THIS.
+ if (!dest._events || !dest._events.error)
+ dest.on('error', onerror);
+ else if (isArray(dest._events.error))
+ dest._events.error.unshift(onerror);
+ else
+ dest._events.error = [onerror, dest._events.error];
-module.exports = createCallback;
-},{"lodash._basecreatecallback":26,"lodash._baseisequal":28,"lodash.isobject":45,"lodash.keys":46,"lodash.property":49}],40:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var createCallback = require('lodash.createcallback'),
- forOwn = require('lodash.forown');
-/**
- * Iterates over elements of a collection, returning an array of all elements
- * the callback returns truey for. The callback is bound to `thisArg` and
- * invoked with three arguments; (value, index|key, collection).
- *
- * If a property name is provided for `callback` the created "_.pluck" style
- * callback will return the property value of the given element.
- *
- * If an object is provided for `callback` the created "_.where" style callback
- * will return `true` for elements that have the properties of the given object,
- * else `false`.
- *
- * @static
- * @memberOf _
- * @alias select
- * @category Collections
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [callback=identity] The function called
- * per iteration. If a property name or object is provided it will be used
- * to create a "_.pluck" or "_.where" style callback, respectively.
- * @param {*} [thisArg] The `this` binding of `callback`.
- * @returns {Array} Returns a new array of elements that passed the callback check.
- * @example
- *
- * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
- * // => [2, 4, 6]
- *
- * var characters = [
- * { 'name': 'barney', 'age': 36, 'blocked': false },
- * { 'name': 'fred', 'age': 40, 'blocked': true }
- * ];
- *
- * // using "_.pluck" callback shorthand
- * _.filter(characters, 'blocked');
- * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
- *
- * // using "_.where" callback shorthand
- * _.filter(characters, { 'age': 36 });
- * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
- */
-function filter(collection, callback, thisArg) {
- var result = [];
- callback = createCallback(callback, thisArg, 3);
-
- var index = -1,
- length = collection ? collection.length : 0;
-
- if (typeof length == 'number') {
- while (++index < length) {
- var value = collection[index];
- if (callback(value, index, collection)) {
- result.push(value);
- }
- }
- } else {
- forOwn(collection, function(value, index, collection) {
- if (callback(value, index, collection)) {
- result.push(value);
- }
- });
- }
- return result;
-}
-
-module.exports = filter;
-
-},{"lodash.createcallback":39,"lodash.forown":42}],41:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var baseCreateCallback = require('lodash._basecreatecallback'),
- objectTypes = require('lodash._objecttypes');
-
-/**
- * Iterates over own and inherited enumerable properties of an object,
- * executing the callback for each property. The callback is bound to `thisArg`
- * and invoked with three arguments; (value, key, object). Callbacks may exit
- * iteration early by explicitly returning `false`.
- *
- * @static
- * @memberOf _
- * @type Function
- * @category Objects
- * @param {Object} object The object to iterate over.
- * @param {Function} [callback=identity] The function called per iteration.
- * @param {*} [thisArg] The `this` binding of `callback`.
- * @returns {Object} Returns `object`.
- * @example
- *
- * function Shape() {
- * this.x = 0;
- * this.y = 0;
- * }
- *
- * Shape.prototype.move = function(x, y) {
- * this.x += x;
- * this.y += y;
- * };
- *
- * _.forIn(new Shape, function(value, key) {
- * console.log(key);
- * });
- * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
- */
-var forIn = function(collection, callback, thisArg) {
- var index, iterable = collection, result = iterable;
- if (!iterable) return result;
- if (!objectTypes[typeof iterable]) return result;
- callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
- for (index in iterable) {
- if (callback(iterable[index], index, collection) === false) return result;
- }
- return result
-};
-
-module.exports = forIn;
-
-},{"lodash._basecreatecallback":26,"lodash._objecttypes":33}],42:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var baseCreateCallback = require('lodash._basecreatecallback'),
- keys = require('lodash.keys'),
- objectTypes = require('lodash._objecttypes');
-
-/**
- * Iterates over own enumerable properties of an object, executing the callback
- * for each property. The callback is bound to `thisArg` and invoked with three
- * arguments; (value, key, object). Callbacks may exit iteration early by
- * explicitly returning `false`.
- *
- * @static
- * @memberOf _
- * @type Function
- * @category Objects
- * @param {Object} object The object to iterate over.
- * @param {Function} [callback=identity] The function called per iteration.
- * @param {*} [thisArg] The `this` binding of `callback`.
- * @returns {Object} Returns `object`.
- * @example
- *
- * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
- * console.log(key);
- * });
- * // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
- */
-var forOwn = function(collection, callback, thisArg) {
- var index, iterable = collection, result = iterable;
- if (!iterable) return result;
- if (!objectTypes[typeof iterable]) return result;
- callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
- var ownIndex = -1,
- ownProps = objectTypes[typeof iterable] && keys(iterable),
- length = ownProps ? ownProps.length : 0;
-
- while (++ownIndex < length) {
- index = ownProps[ownIndex];
- if (callback(iterable[index], index, collection) === false) return result;
- }
- return result
-};
-
-module.exports = forOwn;
-
-},{"lodash._basecreatecallback":26,"lodash._objecttypes":33,"lodash.keys":46}],43:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-
-/**
- * This method returns the first argument provided to it.
- *
- * @static
- * @memberOf _
- * @category Utilities
- * @param {*} value Any value.
- * @returns {*} Returns `value`.
- * @example
- *
- * var object = { 'name': 'fred' };
- * _.identity(object) === object;
- * // => true
- */
-function identity(value) {
- return value;
-}
-
-module.exports = identity;
-
-},{}],44:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-
-/**
- * Checks if `value` is a function.
- *
- * @static
- * @memberOf _
- * @category Objects
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if the `value` is a function, else `false`.
- * @example
- *
- * _.isFunction(_);
- * // => true
- */
-function isFunction(value) {
- return typeof value == 'function';
-}
-
-module.exports = isFunction;
-
-},{}],45:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var objectTypes = require('lodash._objecttypes');
-
-/**
- * Checks if `value` is the language type of Object.
- * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
- *
- * @static
- * @memberOf _
- * @category Objects
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if the `value` is an object, else `false`.
- * @example
- *
- * _.isObject({});
- * // => true
- *
- * _.isObject([1, 2, 3]);
- * // => true
- *
- * _.isObject(1);
- * // => false
- */
-function isObject(value) {
- // check if the value is the ECMAScript language type of Object
- // http://es5.github.io/#x8
- // and avoid a V8 bug
- // http://code.google.com/p/v8/issues/detail?id=2291
- return !!(value && objectTypes[typeof value]);
-}
-
-module.exports = isObject;
-
-},{"lodash._objecttypes":33}],46:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var isNative = require('lodash._isnative'),
- isObject = require('lodash.isobject'),
- shimKeys = require('lodash._shimkeys');
-
-/* Native method shortcuts for methods with the same name as other `lodash` methods */
-var nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys;
-
-/**
- * Creates an array composed of the own enumerable property names of an object.
- *
- * @static
- * @memberOf _
- * @category Objects
- * @param {Object} object The object to inspect.
- * @returns {Array} Returns an array of property names.
- * @example
- *
- * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
- * // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
- */
-var keys = !nativeKeys ? shimKeys : function(object) {
- if (!isObject(object)) {
- return [];
- }
- return nativeKeys(object);
-};
-
-module.exports = keys;
-
-},{"lodash._isnative":31,"lodash._shimkeys":36,"lodash.isobject":45}],47:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var createCallback = require('lodash.createcallback'),
- forOwn = require('lodash.forown');
-
-/**
- * Creates an array of values by running each element in the collection
- * through the callback. The callback is bound to `thisArg` and invoked with
- * three arguments; (value, index|key, collection).
- *
- * If a property name is provided for `callback` the created "_.pluck" style
- * callback will return the property value of the given element.
- *
- * If an object is provided for `callback` the created "_.where" style callback
- * will return `true` for elements that have the properties of the given object,
- * else `false`.
- *
- * @static
- * @memberOf _
- * @alias collect
- * @category Collections
- * @param {Array|Object|string} collection The collection to iterate over.
- * @param {Function|Object|string} [callback=identity] The function called
- * per iteration. If a property name or object is provided it will be used
- * to create a "_.pluck" or "_.where" style callback, respectively.
- * @param {*} [thisArg] The `this` binding of `callback`.
- * @returns {Array} Returns a new array of the results of each `callback` execution.
- * @example
- *
- * _.map([1, 2, 3], function(num) { return num * 3; });
- * // => [3, 6, 9]
- *
- * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
- * // => [3, 6, 9] (property order is not guaranteed across environments)
- *
- * var characters = [
- * { 'name': 'barney', 'age': 36 },
- * { 'name': 'fred', 'age': 40 }
- * ];
- *
- * // using "_.pluck" callback shorthand
- * _.map(characters, 'name');
- * // => ['barney', 'fred']
- */
-function map(collection, callback, thisArg) {
- var index = -1,
- length = collection ? collection.length : 0;
-
- callback = createCallback(callback, thisArg, 3);
- if (typeof length == 'number') {
- var result = Array(length);
- while (++index < length) {
- result[index] = callback(collection[index], index, collection);
- }
- } else {
- result = [];
- forOwn(collection, function(value, key, collection) {
- result[++index] = callback(value, key, collection);
- });
- }
- return result;
-}
-
-module.exports = map;
-
-},{"lodash.createcallback":39,"lodash.forown":42}],48:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-
-/**
- * A no-operation function.
- *
- * @static
- * @memberOf _
- * @category Utilities
- * @example
- *
- * var object = { 'name': 'fred' };
- * _.noop(object) === undefined;
- * // => true
- */
-function noop() {
- // no operation performed
-}
-
-module.exports = noop;
-
-},{}],49:[function(require,module,exports){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-
-/**
- * Creates a "_.pluck" style function, which returns the `key` value of a
- * given object.
- *
- * @static
- * @memberOf _
- * @category Utilities
- * @param {string} key The name of the property to retrieve.
- * @returns {Function} Returns the new function.
- * @example
- *
- * var characters = [
- * { 'name': 'fred', 'age': 40 },
- * { 'name': 'barney', 'age': 36 }
- * ];
- *
- * var getName = _.property('name');
- *
- * _.map(characters, getName);
- * // => ['barney', 'fred']
- *
- * _.sortBy(characters, getName);
- * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]
- */
-function property(key) {
- return function(object) {
- return object[key];
- };
-}
-
-module.exports = property;
-
-},{}],50:[function(require,module,exports){
-(function (global){
-/**
- * Lo-Dash 2.4.1 (Custom Build)
- * Build: `lodash modularize modern exports="npm" -o ./npm/`
- * Copyright 2012-2013 The Dojo Foundation
- * Based on Underscore.js 1.5.2
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- * Available under MIT license
- */
-var isNative = require('lodash._isnative');
-
-/** Used to detect functions containing a `this` reference */
-var reThis = /\bthis\b/;
-
-/**
- * An object used to flag environments features.
- *
- * @static
- * @memberOf _
- * @type Object
- */
-var support = {};
-
-/**
- * Detect if functions can be decompiled by `Function#toString`
- * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
- *
- * @memberOf _.support
- * @type boolean
- */
-support.funcDecomp = !isNative(global.WinRTError) && reThis.test(function() { return this; });
-
-/**
- * Detect if `Function#name` is supported (all but IE).
- *
- * @memberOf _.support
- * @type boolean
- */
-support.funcNames = typeof Function.name == 'string';
-
-module.exports = support;
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"lodash._isnative":31}],51:[function(require,module,exports){
-'use strict';
-
-var PassThrough = require('readable-stream/passthrough')
-
-module.exports = function (/*streams...*/) {
- var sources = []
- var output = new PassThrough({objectMode: true})
-
- output.setMaxListeners(0)
-
- output.add = add
- output.isEmpty = isEmpty
-
- output.on('unpipe', remove)
-
- Array.prototype.slice.call(arguments).forEach(add)
-
- return output
-
- function add (source) {
- if (Array.isArray(source)) {
- source.forEach(add)
- return this
- }
-
- sources.push(source);
- source.once('end', remove.bind(null, source))
- source.pipe(output, {end: false})
- return this
- }
-
- function isEmpty () {
- return sources.length == 0;
- }
-
- function remove (source) {
- sources = sources.filter(function (it) { return it !== source })
- if (!sources.length && output.readable) { output.end() }
- }
-}
-
-},{"readable-stream/passthrough":75}],52:[function(require,module,exports){
-(function (Buffer){
-var map = require('lodash.map')
-var filter = require('lodash.filter')
-var log = console.log
-var convert = require('./convert')
-var protocols = require('./protocols')
-
-// export codec
-var codec = module.exports = {
- stringToStringTuples: stringToStringTuples,
- stringTuplesToString: stringTuplesToString,
-
- tuplesToStringTuples: tuplesToStringTuples,
- stringTuplesToTuples: stringTuplesToTuples,
-
- bufferToTuples: bufferToTuples,
- tuplesToBuffer: tuplesToBuffer,
-
- bufferToString: bufferToString,
- stringToBuffer: stringToBuffer,
-
- fromString: fromString,
- fromBuffer: fromBuffer,
- validateBuffer: validateBuffer,
- isValidBuffer: isValidBuffer,
- cleanPath: cleanPath,
-
- ParseError: ParseError,
- protoFromTuple: protoFromTuple,
-}
-
-// string -> [[str name, str addr]... ]
-function stringToStringTuples(str) {
- var tuples = []
- var parts = str.split('/').slice(1) // skip first empty elem
- if (parts.length == 1 && parts[0] == '')
- return []
-
- for (var p = 0; p < parts.length; p++) {
- var part = parts[p]
- var proto = protocols(part)
- if (proto.size == 0)
- return [part]
-
- p++ // advance addr part
- if (p >= parts.length)
- throw ParseError("invalid address: " + str)
-
- tuples.push([part, parts[p]])
- }
- return tuples
-}
-
-// [[str name, str addr]... ] -> string
-function stringTuplesToString(tuples) {
- var parts = []
- map(tuples, function(tup) {
- var proto = protoFromTuple(tup)
- parts.push(proto.name)
- if (tup.length > 1)
- parts.push(tup[1])
- })
- return "/" + parts.join("/")
-}
-
-
-// [[str name, str addr]... ] -> [[int code, Buffer]... ]
-function stringTuplesToTuples(tuples) {
- return map(tuples, function(tup) {
- var proto = protoFromTuple(tup)
- if (tup.length > 1)
- return [proto.code, convert.toBuffer(proto.code, tup[1])]
- return [proto.code]
- })
-}
-
-// [[int code, Buffer]... ] -> [[str name, str addr]... ]
-function tuplesToStringTuples(tuples) {
- return map(tuples, function(tup) {
- var proto = protoFromTuple(tup)
- if (tup.length > 1)
- return [proto.code, convert.toString(proto.code, tup[1])]
- return [proto.code]
- })
-}
-
-// [[int code, Buffer ]... ] -> Buffer
-function tuplesToBuffer(tuples) {
- return fromBuffer(Buffer.concat(map(tuples, function(tup) {
- var proto = protoFromTuple(tup)
- var buf = new Buffer([proto.code])
- if (tup.length > 1)
- buf = Buffer.concat([buf, tup[1]]) // add address buffer
- return buf
- })))
-}
-
-// Buffer -> [[int code, Buffer ]... ]
-function bufferToTuples(buf) {
- var tuples = []
- for (var i = 0; i < buf.length; ) {
- var code = buf[i]
- var proto = protocols(code)
- if (!proto)
- throw ParseError("Invalid protocol code: " + code)
-
- var size = (proto.size / 8)
- var code = 0 + buf[i]
- var addr = buf.slice(i + 1, i + 1 + size)
- i += 1 + size
- if (i > buf.length) // did not end _exactly_ at buffer.length
- throw ParseError("Invalid address buffer: " + buf.toString('hex'))
-
- // ok, tuple seems good.
- tuples.push([code, addr])
- }
- return tuples
-}
-
-// Buffer -> String
-function bufferToString(buf) {
- var a = bufferToTuples(buf)
- var b = tuplesToStringTuples(a)
- return stringTuplesToString(b)
-}
-
-// String -> Buffer
-function stringToBuffer(str) {
- str = cleanPath(str)
- var a = stringToStringTuples(str)
- var b = stringTuplesToTuples(a)
- return tuplesToBuffer(b)
-}
-
-// String -> Buffer
-function fromString(str) {
- return stringToBuffer(str)
-}
-
-// Buffer -> Buffer
-function fromBuffer(buf) {
- var err = validateBuffer(buf)
- if (err) throw err
- return new Buffer(buf) // copy
-}
-
-function validateBuffer(buf) {
- bufferToTuples(buf) // try to parse. will throw if breaks
-}
-
-function isValidBuffer(buf) {
- try {
- validateBuffer(buf) // try to parse. will throw if breaks
- return true
- } catch(e) {
- return false
- }
-}
-
-function cleanPath(str) {
- return '/' + filter(str.trim().split('/')).join('/')
-}
-
-function ParseError(str) {
- return new Error("Error parsing address: " + str)
-}
-
-function protoFromTuple(tup) {
- var proto = protocols(tup[0])
- if (tup.length > 1 && proto.size == 0)
- throw ParseError("tuple has address but protocol size is 0")
- return proto
-}
-
-}).call(this,require("buffer").Buffer)
-},{"./convert":53,"./protocols":56,"buffer":6,"lodash.filter":40,"lodash.map":47}],53:[function(require,module,exports){
-(function (Buffer){
-var ip = require('ip')
-var protocols = require('./protocols')
-
-module.exports = Convert
-
-// converts (serializes) addresses
-function Convert(proto, a) {
- if (a instanceof Buffer)
- return Convert.toString(proto, a)
- else
- return Convert.toBuffer(proto, a)
-}
-
-Convert.toString = function convertToString(proto, buf) {
- proto = protocols(proto)
- switch (proto.code) {
- case 4: // ipv4
- case 41: // ipv6
- return ip.toString(buf)
-
- case 6: // tcp
- case 17: // udp
- case 33: // dccp
- case 132: // sctp
- return buf2port(buf)
- }
- return buf.toString('hex') // no clue. convert to hex
-}
-
-Convert.toBuffer = function convertToBuffer(proto, str) {
- proto = protocols(proto)
- switch (proto.code) {
- case 4: // ipv4
- case 41: // ipv6
- return ip.toBuffer(str)
-
- case 6: // tcp
- case 17: // udp
- case 33: // dccp
- case 132: // sctp
- return port2buf(parseInt(str, 10))
- }
- return new Buffer(str, 'hex') // no clue. convert from hex
-}
-
-function port2buf(port) {
- var buf = new Buffer(2)
- buf.writeUInt16BE(port, 0);
- return buf
-}
-
-function buf2port(buf) {
- return buf.readUInt16BE(0)
-}
-
-}).call(this,require("buffer").Buffer)
-},{"./protocols":56,"buffer":6,"ip":19}],54:[function(require,module,exports){
-(function (Buffer){
-var map = require('lodash.map')
-var extend = require('xtend')
-var codec = require('./codec')
-var bufeq = require('buffer-equal')
-var protocols = require('./protocols')
-var NotImplemented = new Error("Sorry, Not Implemented Yet.")
-
-module.exports = Multiaddr
-
-function Multiaddr(addr) {
- if (!(this instanceof Multiaddr))
- return new Multiaddr(addr)
-
- // defaults
- if (!addr)
- addr = ''
-
- if (addr instanceof Buffer)
- this.buffer = codec.fromBuffer(addr)
- else if (typeof(addr) == 'string' || addr instanceof String)
- this.buffer = codec.fromString(addr)
- else if (addr.buffer && addr.protos && addr.protoCodes) // Multiaddr
- this.buffer = codec.fromBuffer(addr.buffer) // validate + copy buffer
- else
- throw new Error('addr must be a string, Buffer, or Multiaddr')
-}
-
-// get the multiaddr protocols
-Multiaddr.prototype.toString = function toString() {
- return codec.bufferToString(this.buffer)
-}
-
-// get the multiaddr as a convinent options object to be dropped in net.createConnection
-Multiaddr.prototype.toOptions = function toOptions() {
- var opts = {}
- var parsed = this.toString().split('/')
- opts.family = parsed[1] === 'ip4' ? 'ipv4' : 'ipv6'
- opts.host = parsed[2]
- opts.port = parsed[4]
- return opts
-}
-
-// get the multiaddr protocols
-Multiaddr.prototype.inspect = function inspect() {
- return ""
-}
-
-// get the multiaddr protocols
-Multiaddr.prototype.protos = function protos() {
- return map(this.protoCodes(), function(code) {
- return extend(protocols(code))
- // copy to prevent users from modifying the internal objs.
- });
-}
-
-// get the multiaddr protocols
-Multiaddr.prototype.protos = function protos() {
- return map(this.protoCodes(), function(code) {
- return extend(protocols(code))
- // copy to prevent users from modifying the internal objs.
- });
-}
-
-// get the multiaddr protocol codes
-Multiaddr.prototype.protoCodes = function protoCodes() {
- var codes = []
- for (var i = 0; i < this.buffer.length; i++) {
- var code = 0 + this.buffer[i]
- var size = protocols(code).size / 8
- i += size // skip over proto data
- codes.push(code)
- }
- return codes
-}
-
-// get the multiaddr protocol string names
-Multiaddr.prototype.protoNames = function protoNames() {
- return map(this.protos(), function(proto) {
- return proto.name
- })
-}
-
-// Returns a tuple of parts:
-Multiaddr.prototype.tuples = function tuples() {
- return codec.bufferToTuples(this.buffer)
-}
-
-// Returns a tuple of string parts:
-Multiaddr.prototype.stringTuples = function stringTuples() {
- var t = codec.bufferToTuples(this.buffer)
- return codec.tuplesToStringTuples(t)
-}
-
-
-Multiaddr.prototype.encapsulate = function encapsulate(addr) {
- addr = Multiaddr(addr)
- return Multiaddr(this.toString() + addr.toString())
-}
-
-Multiaddr.prototype.decapsulate = function decapsulate(addr) {
- addr = addr.toString()
- var s = this.toString()
- var i = s.lastIndexOf(addr)
- if (i < 0)
- throw new Error("Address " +this+" does not contain subaddress: " +addr)
- return Multiaddr(s.slice(0, i))
-}
-
-Multiaddr.prototype.equals = function equals(addr) {
- return bufeq(this.buffer, addr.buffer)
-}
-
-// get a node friendly address object
-Multiaddr.prototype.nodeAddress = function nodeAddress() {
- if (!this.isThinWaistAddress())
- throw new Error('Multiaddr must be "thin waist" address for nodeAddress.')
-
- var codes = this.protoCodes()
- var parts = this.toString().split('/').slice(1)
- return {
- family: (codes[0] == 41) ? "IPv6" : "IPv4",
- address: parts[1], // ip addr
- port: parts[3], // tcp or udp port
- }
-}
-
-// from a node friendly address object
-Multiaddr.fromNodeAddress = function fromNodeAddress(addr, transport) {
- if (!addr) throw new Error('requires node address object')
- if (!transport) throw new Error('requires transport protocol')
- var ip = (addr.family == "IPv6") ? 'ip6' : 'ip4'
- return Multiaddr('/' + [ip, addr.address, transport, addr.port].join('/'))
-}
-
-
-// returns whether this address is a standard combination:
-// /{IPv4, IPv6}/{TCP, UDP}
-Multiaddr.prototype.isThinWaistAddress = function isThinWaistAddress(addr) {
- var protos = (addr || this).protos()
- if (protos.length != 2) return false
- if (protos[0].code != 4 && protos[0].code != 41) return false
- if (protos[1].code != 6 && protos[1].code != 17) return false
- return true
-}
-
-
-// parses the "stupid string" format:
-// ://[:]
-// udp4://1.2.3.4:5678
-Multiaddr.prototype.fromStupidString = function fromStupidString(str) {
- throw NotImplemented
-}
-
-// patch this in
-Multiaddr.protocols = protocols
-
-}).call(this,require("buffer").Buffer)
-},{"./codec":52,"./protocols":56,"buffer":6,"buffer-equal":5,"lodash.map":47,"xtend":55}],55:[function(require,module,exports){
-module.exports = extend
-
-function extend() {
- var target = {}
-
- for (var i = 0; i < arguments.length; i++) {
- var source = arguments[i]
-
- for (var key in source) {
- if (source.hasOwnProperty(key)) {
- target[key] = source[key]
- }
- }
- }
-
- return target
-}
-
-},{}],56:[function(require,module,exports){
-var map = require('lodash.map')
-
-module.exports = Protocols
-
-function Protocols(proto) {
- if (typeof(proto) == 'number') {
- if (Protocols.codes[proto])
- return Protocols.codes[proto]
-
- throw new Error("no protocol with code: " + proto)
- }
- else if (typeof(proto) == 'string' || proto instanceof String) {
- if (Protocols.names[proto])
- return Protocols.names[proto]
-
- throw new Error("no protocol with name: " + proto)
- }
-
- throw new Error("invalid protocol id type: " + proto)
-}
-
-// replicating table here to:
-// 1. avoid parsing the csv
-// 2. ensuring errors in the csv don't screw up code.
-// 3. changing a number has to happen in two places.
-
-Protocols.table = [
- [4, 32, 'ip4'],
- [6, 16, 'tcp'],
- [17, 16, 'udp'],
- [33, 16, 'dccp'],
- [41, 128, 'ip6'],
- // these require varint:
- [132, 16, 'sctp'],
- // [480, 0, 'http'],
- // [443, 0, 'https'],
-]
-
-Protocols.names = {}
-Protocols.codes = {}
-
-// populate tables
-map(Protocols.table, function(e) {
- var proto = p.apply(this, e)
- Protocols.codes[proto.code] = proto
- Protocols.names[proto.name] = proto
-})
-
-Protocols.object = p
-
-function p(code, size, name) {
- return {code: code, size: size, name: name}
-}
-
-},{"lodash.map":47}],57:[function(require,module,exports){
-var Sandwich = require('sandwich-stream').SandwichStream
-var stream = require('stream')
-var inherits = require('inherits')
-
-var CRNL = '\r\n'
-
-module.exports = Multipart
-
-/**
- * Multipart request constructor.
- * @constructor
- * @param {object} [opts]
- * @param {string} [opts.boundary] - The boundary to be used. If omitted one is generated.
- * @returns {function} Returns the multipart stream.
- */
-function Multipart(boundary) {
- if(!this instanceof Multipart) {
- return new Multipart(boundary)
- }
-
- this.boundary = boundary || Math.random().toString(36).slice(2)
-
- Sandwich.call(this, {
- head: '--' + this.boundary + CRNL,
- tail: CRNL + '--' + this.boundary + '--',
- separator: CRNL + '--' + this.boundary + CRNL
- })
-
- this._add = this.add
- this.add = this.addPart
-}
-
-inherits(Multipart, Sandwich)
-
-/**
- * Adds a new part to the request.
- * @param {object} [part={}]
- * @param {object} [part.headers={}]
- * @param {string|buffer|stream} [part.body=\r\n]
- * @returns {function} Returns the multipart stream.
- */
-Multipart.prototype.addPart = function(part) {
- part = part || {}
- var partStream = new stream.PassThrough()
-
- if(part.headers) {
- for(var key in part.headers) {
- var header = part.headers[key]
- partStream.write(key + ': ' + header + CRNL)
- }
- }
-
- partStream.write(CRNL)
-
- if(part.body instanceof stream.Stream) {
- part.body.pipe(partStream)
- } else {
- partStream.end(part.body)
- }
-
- this._add(partStream)
-}
-},{"inherits":18,"sandwich-stream":80,"stream":81}],58:[function(require,module,exports){
-'use strict';
-
-// modified from https://github.com/es-shims/es5-shim
-var has = Object.prototype.hasOwnProperty;
-var toStr = Object.prototype.toString;
-var slice = Array.prototype.slice;
-var isArgs = require('./isArguments');
-var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString');
-var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
-var dontEnums = [
- 'toString',
- 'toLocaleString',
- 'valueOf',
- 'hasOwnProperty',
- 'isPrototypeOf',
- 'propertyIsEnumerable',
- 'constructor'
-];
-var equalsConstructorPrototype = function (o) {
- var ctor = o.constructor;
- return ctor && ctor.prototype === o;
-};
-var blacklistedKeys = {
- $window: true,
- $console: true,
- $parent: true,
- $self: true,
- $frames: true,
- $webkitIndexedDB: true,
- $webkitStorageInfo: true
-};
-var hasAutomationEqualityBug = (function () {
- /* global window */
- if (typeof window === 'undefined') { return false; }
- for (var k in window) {
- if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
- try {
- equalsConstructorPrototype(window[k]);
- } catch (e) {
- return true;
- }
- }
- }
- return false;
-}());
-var equalsConstructorPrototypeIfNotBuggy = function (o) {
- /* global window */
- if (typeof window === 'undefined' && !hasAutomationEqualityBug) {
- return equalsConstructorPrototype(o);
- }
- try {
- return equalsConstructorPrototype(o);
- } catch (e) {
- return false;
- }
-};
-
-var keysShim = function keys(object) {
- var isObject = object !== null && typeof object === 'object';
- var isFunction = toStr.call(object) === '[object Function]';
- var isArguments = isArgs(object);
- var isString = isObject && toStr.call(object) === '[object String]';
- var theKeys = [];
-
- if (!isObject && !isFunction && !isArguments) {
- throw new TypeError('Object.keys called on a non-object');
- }
-
- var skipProto = hasProtoEnumBug && isFunction;
- if (isString && object.length > 0 && !has.call(object, 0)) {
- for (var i = 0; i < object.length; ++i) {
- theKeys.push(String(i));
- }
- }
-
- if (isArguments && object.length > 0) {
- for (var j = 0; j < object.length; ++j) {
- theKeys.push(String(j));
- }
- } else {
- for (var name in object) {
- if (!(skipProto && name === 'prototype') && has.call(object, name)) {
- theKeys.push(String(name));
- }
- }
- }
-
- if (hasDontEnumBug) {
- var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
-
- for (var k = 0; k < dontEnums.length; ++k) {
- if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
- theKeys.push(dontEnums[k]);
- }
- }
- }
- return theKeys;
-};
-
-keysShim.shim = function shimObjectKeys() {
- if (!Object.keys) {
- Object.keys = keysShim;
- } else {
- var keysWorksWithArguments = (function () {
- // Safari 5.0 bug
- return (Object.keys(arguments) || '').length === 2;
- }(1, 2));
- if (!keysWorksWithArguments) {
- var originalKeys = Object.keys;
- Object.keys = function keys(object) {
- if (isArgs(object)) {
- return originalKeys(slice.call(object));
- } else {
- return originalKeys(object);
- }
- };
- }
- }
- return Object.keys || keysShim;
-};
-
-module.exports = keysShim;
-
-},{"./isArguments":59}],59:[function(require,module,exports){
-'use strict';
-
-var toStr = Object.prototype.toString;
-
-module.exports = function isArguments(value) {
- var str = toStr.call(value);
- var isArgs = str === '[object Arguments]';
- if (!isArgs) {
- isArgs = str !== '[object Array]' &&
- value !== null &&
- typeof value === 'object' &&
- typeof value.length === 'number' &&
- value.length >= 0 &&
- toStr.call(value.callee) === '[object Function]';
- }
- return isArgs;
-};
-
-},{}],60:[function(require,module,exports){
-var wrappy = require('wrappy')
-module.exports = wrappy(once)
-
-once.proto = once(function () {
- Object.defineProperty(Function.prototype, 'once', {
- value: function () {
- return once(this)
- },
- configurable: true
- })
-})
-
-function once (fn) {
- var f = function () {
- if (f.called) return f.value
- f.called = true
- return f.value = fn.apply(this, arguments)
- }
- f.called = false
- return f
-}
-
-},{"wrappy":103}],61:[function(require,module,exports){
-exports.endianness = function () { return 'LE' };
-
-exports.hostname = function () {
- if (typeof location !== 'undefined') {
- return location.hostname
- }
- else return '';
-};
-
-exports.loadavg = function () { return [] };
-
-exports.uptime = function () { return 0 };
-
-exports.freemem = function () {
- return Number.MAX_VALUE;
-};
-
-exports.totalmem = function () {
- return Number.MAX_VALUE;
-};
-
-exports.cpus = function () { return [] };
-
-exports.type = function () { return 'Browser' };
-
-exports.release = function () {
- if (typeof navigator !== 'undefined') {
- return navigator.appVersion;
- }
- return '';
-};
-
-exports.networkInterfaces
-= exports.getNetworkInterfaces
-= function () { return {} };
-
-exports.arch = function () { return 'javascript' };
-
-exports.platform = function () { return 'browser' };
-
-exports.tmpdir = exports.tmpDir = function () {
- return '/tmp';
-};
-
-exports.EOL = '\n';
-
-},{}],62:[function(require,module,exports){
-(function (process){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// resolves . and .. elements in a path array with directory names there
-// must be no slashes, empty elements, or device names (c:\) in the array
-// (so also no leading and trailing slashes - it does not distinguish
-// relative and absolute paths)
-function normalizeArray(parts, allowAboveRoot) {
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = parts.length - 1; i >= 0; i--) {
- var last = parts[i];
- if (last === '.') {
- parts.splice(i, 1);
- } else if (last === '..') {
- parts.splice(i, 1);
- up++;
- } else if (up) {
- parts.splice(i, 1);
- up--;
- }
- }
-
- // if the path is allowed to go above the root, restore leading ..s
- if (allowAboveRoot) {
- for (; up--; up) {
- parts.unshift('..');
- }
- }
-
- return parts;
-}
-
-// Split a filename into [root, dir, basename, ext], unix version
-// 'root' is just a slash, or nothing.
-var splitPathRe =
- /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
-var splitPath = function(filename) {
- return splitPathRe.exec(filename).slice(1);
-};
-
-// path.resolve([from ...], to)
-// posix version
-exports.resolve = function() {
- var resolvedPath = '',
- resolvedAbsolute = false;
-
- for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
- var path = (i >= 0) ? arguments[i] : process.cwd();
-
- // Skip empty and invalid entries
- if (typeof path !== 'string') {
- throw new TypeError('Arguments to path.resolve must be strings');
- } else if (!path) {
- continue;
- }
-
- resolvedPath = path + '/' + resolvedPath;
- resolvedAbsolute = path.charAt(0) === '/';
- }
-
- // At this point the path should be resolved to a full absolute path, but
- // handle relative paths to be safe (might happen when process.cwd() fails)
-
- // Normalize the path
- resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
- return !!p;
- }), !resolvedAbsolute).join('/');
-
- return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
-};
-
-// path.normalize(path)
-// posix version
-exports.normalize = function(path) {
- var isAbsolute = exports.isAbsolute(path),
- trailingSlash = substr(path, -1) === '/';
-
- // Normalize the path
- path = normalizeArray(filter(path.split('/'), function(p) {
- return !!p;
- }), !isAbsolute).join('/');
-
- if (!path && !isAbsolute) {
- path = '.';
- }
- if (path && trailingSlash) {
- path += '/';
- }
-
- return (isAbsolute ? '/' : '') + path;
-};
-
-// posix version
-exports.isAbsolute = function(path) {
- return path.charAt(0) === '/';
-};
-
-// posix version
-exports.join = function() {
- var paths = Array.prototype.slice.call(arguments, 0);
- return exports.normalize(filter(paths, function(p, index) {
- if (typeof p !== 'string') {
- throw new TypeError('Arguments to path.join must be strings');
- }
- return p;
- }).join('/'));
-};
-
-
-// path.relative(from, to)
-// posix version
-exports.relative = function(from, to) {
- from = exports.resolve(from).substr(1);
- to = exports.resolve(to).substr(1);
-
- function trim(arr) {
- var start = 0;
- for (; start < arr.length; start++) {
- if (arr[start] !== '') break;
- }
-
- var end = arr.length - 1;
- for (; end >= 0; end--) {
- if (arr[end] !== '') break;
- }
-
- if (start > end) return [];
- return arr.slice(start, end - start + 1);
- }
-
- var fromParts = trim(from.split('/'));
- var toParts = trim(to.split('/'));
-
- var length = Math.min(fromParts.length, toParts.length);
- var samePartsLength = length;
- for (var i = 0; i < length; i++) {
- if (fromParts[i] !== toParts[i]) {
- samePartsLength = i;
- break;
- }
- }
-
- var outputParts = [];
- for (var i = samePartsLength; i < fromParts.length; i++) {
- outputParts.push('..');
- }
-
- outputParts = outputParts.concat(toParts.slice(samePartsLength));
-
- return outputParts.join('/');
-};
-
-exports.sep = '/';
-exports.delimiter = ':';
-
-exports.dirname = function(path) {
- var result = splitPath(path),
- root = result[0],
- dir = result[1];
-
- if (!root && !dir) {
- // No dirname whatsoever
- return '.';
- }
-
- if (dir) {
- // It has a dirname, strip trailing slash
- dir = dir.substr(0, dir.length - 1);
- }
-
- return root + dir;
-};
-
-
-exports.basename = function(path, ext) {
- var f = splitPath(path)[2];
- // TODO: make this comparison case-insensitive on windows?
- if (ext && f.substr(-1 * ext.length) === ext) {
- f = f.substr(0, f.length - ext.length);
- }
- return f;
-};
-
-
-exports.extname = function(path) {
- return splitPath(path)[3];
-};
-
-function filter (xs, f) {
- if (xs.filter) return xs.filter(f);
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- if (f(xs[i], i, xs)) res.push(xs[i]);
- }
- return res;
-}
-
-// String.prototype.substr - negative index don't work in IE8
-var substr = 'ab'.substr(-1) === 'b'
- ? function (str, start, len) { return str.substr(start, len) }
- : function (str, start, len) {
- if (start < 0) start = str.length + start;
- return str.substr(start, len);
- }
-;
-
-}).call(this,require('_process'))
-},{"_process":64}],63:[function(require,module,exports){
-(function (process){
-'use strict';
-module.exports = nextTick;
-
-function nextTick(fn) {
- var args = new Array(arguments.length - 1);
- var i = 0;
- while (i < args.length) {
- args[i++] = arguments[i];
- }
- process.nextTick(function afterTick() {
- fn.apply(null, args);
- });
-}
-
-}).call(this,require('_process'))
-},{"_process":64}],64:[function(require,module,exports){
-// shim for using process in browser
-
-var process = module.exports = {};
-var queue = [];
-var draining = false;
-var currentQueue;
-var queueIndex = -1;
-
-function cleanUpNextTick() {
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
-}
-
-function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = setTimeout(cleanUpNextTick);
- draining = true;
-
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- clearTimeout(timeout);
-}
-
-process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- setTimeout(drainQueue, 0);
- }
-};
-
-// v8 likes predictible objects
-function Item(fun, array) {
- this.fun = fun;
- this.array = array;
-}
-Item.prototype.run = function () {
- this.fun.apply(null, this.array);
-};
-process.title = 'browser';
-process.browser = true;
-process.env = {};
-process.argv = [];
-process.version = ''; // empty string to avoid regexp issues
-process.versions = {};
-
-function noop() {}
-
-process.on = noop;
-process.addListener = noop;
-process.once = noop;
-process.off = noop;
-process.removeListener = noop;
-process.removeAllListeners = noop;
-process.emit = noop;
-
-process.binding = function (name) {
- throw new Error('process.binding is not supported');
-};
-
-process.cwd = function () { return '/' };
-process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
-};
-process.umask = function() { return 0; };
-
-},{}],65:[function(require,module,exports){
-(function (global){
-/*! https://mths.be/punycode v1.3.2 by @mathias */
-;(function(root) {
-
- /** Detect free variables */
- var freeExports = typeof exports == 'object' && exports &&
- !exports.nodeType && exports;
- var freeModule = typeof module == 'object' && module &&
- !module.nodeType && module;
- var freeGlobal = typeof global == 'object' && global;
- if (
- freeGlobal.global === freeGlobal ||
- freeGlobal.window === freeGlobal ||
- freeGlobal.self === freeGlobal
- ) {
- root = freeGlobal;
- }
-
- /**
- * The `punycode` object.
- * @name punycode
- * @type Object
- */
- var punycode,
-
- /** Highest positive signed 32-bit float value */
- maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
-
- /** Bootstring parameters */
- base = 36,
- tMin = 1,
- tMax = 26,
- skew = 38,
- damp = 700,
- initialBias = 72,
- initialN = 128, // 0x80
- delimiter = '-', // '\x2D'
-
- /** Regular expressions */
- regexPunycode = /^xn--/,
- regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
- regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
-
- /** Error messages */
- errors = {
- 'overflow': 'Overflow: input needs wider integers to process',
- 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
- 'invalid-input': 'Invalid input'
- },
-
- /** Convenience shortcuts */
- baseMinusTMin = base - tMin,
- floor = Math.floor,
- stringFromCharCode = String.fromCharCode,
-
- /** Temporary variable */
- key;
-
- /*--------------------------------------------------------------------------*/
-
- /**
- * A generic error utility function.
- * @private
- * @param {String} type The error type.
- * @returns {Error} Throws a `RangeError` with the applicable error message.
- */
- function error(type) {
- throw RangeError(errors[type]);
- }
-
- /**
- * A generic `Array#map` utility function.
- * @private
- * @param {Array} array The array to iterate over.
- * @param {Function} callback The function that gets called for every array
- * item.
- * @returns {Array} A new array of values returned by the callback function.
- */
- function map(array, fn) {
- var length = array.length;
- var result = [];
- while (length--) {
- result[length] = fn(array[length]);
- }
- return result;
- }
-
- /**
- * A simple `Array#map`-like wrapper to work with domain name strings or email
- * addresses.
- * @private
- * @param {String} domain The domain name or email address.
- * @param {Function} callback The function that gets called for every
- * character.
- * @returns {Array} A new string of characters returned by the callback
- * function.
- */
- function mapDomain(string, fn) {
- var parts = string.split('@');
- var result = '';
- if (parts.length > 1) {
- // In email addresses, only the domain name should be punycoded. Leave
- // the local part (i.e. everything up to `@`) intact.
- result = parts[0] + '@';
- string = parts[1];
- }
- // Avoid `split(regex)` for IE8 compatibility. See #17.
- string = string.replace(regexSeparators, '\x2E');
- var labels = string.split('.');
- var encoded = map(labels, fn).join('.');
- return result + encoded;
- }
-
- /**
- * Creates an array containing the numeric code points of each Unicode
- * character in the string. While JavaScript uses UCS-2 internally,
- * this function will convert a pair of surrogate halves (each of which
- * UCS-2 exposes as separate characters) into a single code point,
- * matching UTF-16.
- * @see `punycode.ucs2.encode`
- * @see
- * @memberOf punycode.ucs2
- * @name decode
- * @param {String} string The Unicode input string (UCS-2).
- * @returns {Array} The new array of code points.
- */
- function ucs2decode(string) {
- var output = [],
- counter = 0,
- length = string.length,
- value,
- extra;
- while (counter < length) {
- value = string.charCodeAt(counter++);
- if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
- // high surrogate, and there is a next character
- extra = string.charCodeAt(counter++);
- if ((extra & 0xFC00) == 0xDC00) { // low surrogate
- output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
- } else {
- // unmatched surrogate; only append this code unit, in case the next
- // code unit is the high surrogate of a surrogate pair
- output.push(value);
- counter--;
- }
- } else {
- output.push(value);
- }
- }
- return output;
- }
-
- /**
- * Creates a string based on an array of numeric code points.
- * @see `punycode.ucs2.decode`
- * @memberOf punycode.ucs2
- * @name encode
- * @param {Array} codePoints The array of numeric code points.
- * @returns {String} The new Unicode string (UCS-2).
- */
- function ucs2encode(array) {
- return map(array, function(value) {
- var output = '';
- if (value > 0xFFFF) {
- value -= 0x10000;
- output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
- value = 0xDC00 | value & 0x3FF;
- }
- output += stringFromCharCode(value);
- return output;
- }).join('');
- }
-
- /**
- * Converts a basic code point into a digit/integer.
- * @see `digitToBasic()`
- * @private
- * @param {Number} codePoint The basic numeric code point value.
- * @returns {Number} The numeric value of a basic code point (for use in
- * representing integers) in the range `0` to `base - 1`, or `base` if
- * the code point does not represent a value.
- */
- function basicToDigit(codePoint) {
- if (codePoint - 48 < 10) {
- return codePoint - 22;
- }
- if (codePoint - 65 < 26) {
- return codePoint - 65;
- }
- if (codePoint - 97 < 26) {
- return codePoint - 97;
- }
- return base;
- }
-
- /**
- * Converts a digit/integer into a basic code point.
- * @see `basicToDigit()`
- * @private
- * @param {Number} digit The numeric value of a basic code point.
- * @returns {Number} The basic code point whose value (when used for
- * representing integers) is `digit`, which needs to be in the range
- * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
- * used; else, the lowercase form is used. The behavior is undefined
- * if `flag` is non-zero and `digit` has no uppercase form.
- */
- function digitToBasic(digit, flag) {
- // 0..25 map to ASCII a..z or A..Z
- // 26..35 map to ASCII 0..9
- return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
- }
-
- /**
- * Bias adaptation function as per section 3.4 of RFC 3492.
- * http://tools.ietf.org/html/rfc3492#section-3.4
- * @private
- */
- function adapt(delta, numPoints, firstTime) {
- var k = 0;
- delta = firstTime ? floor(delta / damp) : delta >> 1;
- delta += floor(delta / numPoints);
- for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
- delta = floor(delta / baseMinusTMin);
- }
- return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
- }
-
- /**
- * Converts a Punycode string of ASCII-only symbols to a string of Unicode
- * symbols.
- * @memberOf punycode
- * @param {String} input The Punycode string of ASCII-only symbols.
- * @returns {String} The resulting string of Unicode symbols.
- */
- function decode(input) {
- // Don't use UCS-2
- var output = [],
- inputLength = input.length,
- out,
- i = 0,
- n = initialN,
- bias = initialBias,
- basic,
- j,
- index,
- oldi,
- w,
- k,
- digit,
- t,
- /** Cached calculation results */
- baseMinusT;
-
- // Handle the basic code points: let `basic` be the number of input code
- // points before the last delimiter, or `0` if there is none, then copy
- // the first basic code points to the output.
-
- basic = input.lastIndexOf(delimiter);
- if (basic < 0) {
- basic = 0;
- }
-
- for (j = 0; j < basic; ++j) {
- // if it's not a basic code point
- if (input.charCodeAt(j) >= 0x80) {
- error('not-basic');
- }
- output.push(input.charCodeAt(j));
- }
-
- // Main decoding loop: start just after the last delimiter if any basic code
- // points were copied; start at the beginning otherwise.
-
- for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
-
- // `index` is the index of the next character to be consumed.
- // Decode a generalized variable-length integer into `delta`,
- // which gets added to `i`. The overflow checking is easier
- // if we increase `i` as we go, then subtract off its starting
- // value at the end to obtain `delta`.
- for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
-
- if (index >= inputLength) {
- error('invalid-input');
- }
-
- digit = basicToDigit(input.charCodeAt(index++));
-
- if (digit >= base || digit > floor((maxInt - i) / w)) {
- error('overflow');
- }
-
- i += digit * w;
- t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
-
- if (digit < t) {
- break;
- }
-
- baseMinusT = base - t;
- if (w > floor(maxInt / baseMinusT)) {
- error('overflow');
- }
-
- w *= baseMinusT;
-
- }
-
- out = output.length + 1;
- bias = adapt(i - oldi, out, oldi == 0);
-
- // `i` was supposed to wrap around from `out` to `0`,
- // incrementing `n` each time, so we'll fix that now:
- if (floor(i / out) > maxInt - n) {
- error('overflow');
- }
-
- n += floor(i / out);
- i %= out;
-
- // Insert `n` at position `i` of the output
- output.splice(i++, 0, n);
-
- }
-
- return ucs2encode(output);
- }
-
- /**
- * Converts a string of Unicode symbols (e.g. a domain name label) to a
- * Punycode string of ASCII-only symbols.
- * @memberOf punycode
- * @param {String} input The string of Unicode symbols.
- * @returns {String} The resulting Punycode string of ASCII-only symbols.
- */
- function encode(input) {
- var n,
- delta,
- handledCPCount,
- basicLength,
- bias,
- j,
- m,
- q,
- k,
- t,
- currentValue,
- output = [],
- /** `inputLength` will hold the number of code points in `input`. */
- inputLength,
- /** Cached calculation results */
- handledCPCountPlusOne,
- baseMinusT,
- qMinusT;
-
- // Convert the input in UCS-2 to Unicode
- input = ucs2decode(input);
-
- // Cache the length
- inputLength = input.length;
-
- // Initialize the state
- n = initialN;
- delta = 0;
- bias = initialBias;
-
- // Handle the basic code points
- for (j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue < 0x80) {
- output.push(stringFromCharCode(currentValue));
- }
- }
-
- handledCPCount = basicLength = output.length;
-
- // `handledCPCount` is the number of code points that have been handled;
- // `basicLength` is the number of basic code points.
-
- // Finish the basic string - if it is not empty - with a delimiter
- if (basicLength) {
- output.push(delimiter);
- }
-
- // Main encoding loop:
- while (handledCPCount < inputLength) {
-
- // All non-basic code points < n have been handled already. Find the next
- // larger one:
- for (m = maxInt, j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue >= n && currentValue < m) {
- m = currentValue;
- }
- }
-
- // Increase `delta` enough to advance the decoder's state to ,
- // but guard against overflow
- handledCPCountPlusOne = handledCPCount + 1;
- if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
- error('overflow');
- }
-
- delta += (m - n) * handledCPCountPlusOne;
- n = m;
-
- for (j = 0; j < inputLength; ++j) {
- currentValue = input[j];
-
- if (currentValue < n && ++delta > maxInt) {
- error('overflow');
- }
-
- if (currentValue == n) {
- // Represent delta as a generalized variable-length integer
- for (q = delta, k = base; /* no condition */; k += base) {
- t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
- if (q < t) {
- break;
- }
- qMinusT = q - t;
- baseMinusT = base - t;
- output.push(
- stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
- );
- q = floor(qMinusT / baseMinusT);
- }
-
- output.push(stringFromCharCode(digitToBasic(q, 0)));
- bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
- delta = 0;
- ++handledCPCount;
- }
- }
-
- ++delta;
- ++n;
-
- }
- return output.join('');
- }
-
- /**
- * Converts a Punycode string representing a domain name or an email address
- * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
- * it doesn't matter if you call it on a string that has already been
- * converted to Unicode.
- * @memberOf punycode
- * @param {String} input The Punycoded domain name or email address to
- * convert to Unicode.
- * @returns {String} The Unicode representation of the given Punycode
- * string.
- */
- function toUnicode(input) {
- return mapDomain(input, function(string) {
- return regexPunycode.test(string)
- ? decode(string.slice(4).toLowerCase())
- : string;
- });
- }
-
- /**
- * Converts a Unicode string representing a domain name or an email address to
- * Punycode. Only the non-ASCII parts of the domain name will be converted,
- * i.e. it doesn't matter if you call it with a domain that's already in
- * ASCII.
- * @memberOf punycode
- * @param {String} input The domain name or email address to convert, as a
- * Unicode string.
- * @returns {String} The Punycode representation of the given domain name or
- * email address.
- */
- function toASCII(input) {
- return mapDomain(input, function(string) {
- return regexNonASCII.test(string)
- ? 'xn--' + encode(string)
- : string;
- });
- }
-
- /*--------------------------------------------------------------------------*/
-
- /** Define the public API */
- punycode = {
- /**
- * A string representing the current Punycode.js version number.
- * @memberOf punycode
- * @type String
- */
- 'version': '1.3.2',
- /**
- * An object of methods to convert from JavaScript's internal character
- * representation (UCS-2) to Unicode code points, and back.
- * @see
- * @memberOf punycode
- * @type Object
- */
- 'ucs2': {
- 'decode': ucs2decode,
- 'encode': ucs2encode
- },
- 'decode': decode,
- 'encode': encode,
- 'toASCII': toASCII,
- 'toUnicode': toUnicode
- };
-
- /** Expose `punycode` */
- // Some AMD build optimizers, like r.js, check for specific condition patterns
- // like the following:
- if (
- typeof define == 'function' &&
- typeof define.amd == 'object' &&
- define.amd
- ) {
- define('punycode', function() {
- return punycode;
- });
- } else if (freeExports && freeModule) {
- if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+
- freeModule.exports = punycode;
- } else { // in Narwhal or RingoJS v0.7.0-
- for (key in punycode) {
- punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
- }
- }
- } else { // in Rhino or a web browser
- root.punycode = punycode;
- }
-
-}(this));
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],66:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-'use strict';
-
-// If obj.hasOwnProperty has been overridden, then calling
-// obj.hasOwnProperty(prop) will break.
-// See: https://github.com/joyent/node/issues/1707
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
-
-module.exports = function(qs, sep, eq, options) {
- sep = sep || '&';
- eq = eq || '=';
- var obj = {};
-
- if (typeof qs !== 'string' || qs.length === 0) {
- return obj;
- }
-
- var regexp = /\+/g;
- qs = qs.split(sep);
-
- var maxKeys = 1000;
- if (options && typeof options.maxKeys === 'number') {
- maxKeys = options.maxKeys;
- }
-
- var len = qs.length;
- // maxKeys <= 0 means that we should not limit keys count
- if (maxKeys > 0 && len > maxKeys) {
- len = maxKeys;
- }
-
- for (var i = 0; i < len; ++i) {
- var x = qs[i].replace(regexp, '%20'),
- idx = x.indexOf(eq),
- kstr, vstr, k, v;
-
- if (idx >= 0) {
- kstr = x.substr(0, idx);
- vstr = x.substr(idx + 1);
- } else {
- kstr = x;
- vstr = '';
- }
-
- k = decodeURIComponent(kstr);
- v = decodeURIComponent(vstr);
-
- if (!hasOwnProperty(obj, k)) {
- obj[k] = v;
- } else if (isArray(obj[k])) {
- obj[k].push(v);
- } else {
- obj[k] = [obj[k], v];
- }
- }
-
- return obj;
-};
-
-var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
-};
-
-},{}],67:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-'use strict';
-
-var stringifyPrimitive = function(v) {
- switch (typeof v) {
- case 'string':
- return v;
-
- case 'boolean':
- return v ? 'true' : 'false';
-
- case 'number':
- return isFinite(v) ? v : '';
-
- default:
- return '';
+ // Both close and finish should trigger unpipe, but only once.
+ function onclose() {
+ dest.removeListener('finish', onfinish);
+ unpipe();
}
-};
-
-module.exports = function(obj, sep, eq, name) {
- sep = sep || '&';
- eq = eq || '=';
- if (obj === null) {
- obj = undefined;
+ dest.once('close', onclose);
+ function onfinish() {
+ dest.removeListener('close', onclose);
+ unpipe();
}
+ dest.once('finish', onfinish);
- if (typeof obj === 'object') {
- return map(objectKeys(obj), function(k) {
- var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
- if (isArray(obj[k])) {
- return map(obj[k], function(v) {
- return ks + encodeURIComponent(stringifyPrimitive(v));
- }).join(sep);
- } else {
- return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
- }
- }).join(sep);
-
+ function unpipe() {
+ src.unpipe(dest);
}
- if (!name) return '';
- return encodeURIComponent(stringifyPrimitive(name)) + eq +
- encodeURIComponent(stringifyPrimitive(obj));
-};
+ // tell the dest that it's being piped to
+ dest.emit('pipe', src);
-var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
-};
+ // start the flow if it hasn't been started already.
+ if (!state.flowing) {
+ // the handler that waits for readable events after all
+ // the data gets sucked out in flow.
+ // This would be easier to follow with a .once() handler
+ // in flow(), but that is too slow.
+ this.on('readable', pipeOnReadable);
-function map (xs, f) {
- if (xs.map) return xs.map(f);
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- res.push(f(xs[i], i));
+ state.flowing = true;
+ process.nextTick(function() {
+ flow(src);
+ });
}
- return res;
-}
-var objectKeys = Object.keys || function (obj) {
- var res = [];
- for (var key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
- }
- return res;
+ return dest;
};
-},{}],68:[function(require,module,exports){
-'use strict';
-
-exports.decode = exports.parse = require('./decode');
-exports.encode = exports.stringify = require('./encode');
-
-},{"./decode":66,"./encode":67}],69:[function(require,module,exports){
-module.exports = require("./lib/_stream_duplex.js")
-
-},{"./lib/_stream_duplex.js":70}],70:[function(require,module,exports){
-// a duplex stream is just a stream that is both readable and writable.
-// Since JS doesn't have multiple prototypal inheritance, this class
-// prototypally inherits from Readable, and then parasitically from
-// Writable.
-
-'use strict';
-
-/**/
-var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) keys.push(key);
- return keys;
+function pipeOnDrain(src) {
+ return function() {
+ var dest = this;
+ var state = src._readableState;
+ state.awaitDrain--;
+ if (state.awaitDrain === 0)
+ flow(src);
+ };
}
-/**/
+function flow(src) {
+ var state = src._readableState;
+ var chunk;
+ state.awaitDrain = 0;
-module.exports = Duplex;
+ function write(dest, i, list) {
+ var written = dest.write(chunk);
+ if (false === written) {
+ state.awaitDrain++;
+ }
+ }
-/**/
-var processNextTick = require('process-nextick-args');
-/**/
+ while (state.pipesCount && null !== (chunk = src.read())) {
+ if (state.pipesCount === 1)
+ write(state.pipes, 0, null);
+ else
+ forEach(state.pipes, write);
+ src.emit('data', chunk);
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+ // if anyone needs a drain, then we have to wait for that.
+ if (state.awaitDrain > 0)
+ return;
+ }
-var Readable = require('./_stream_readable');
-var Writable = require('./_stream_writable');
+ // if every destination was unpiped, either before entering this
+ // function, or in the while loop, then stop flowing.
+ //
+ // NB: This is a pretty rare edge case.
+ if (state.pipesCount === 0) {
+ state.flowing = false;
-util.inherits(Duplex, Readable);
+ // if there were data event listeners added, then switch to old mode.
+ if (EE.listenerCount(src, 'data') > 0)
+ emitDataEvents(src);
+ return;
+ }
-var keys = objectKeys(Writable.prototype);
-for (var v = 0; v < keys.length; v++) {
- var method = keys[v];
- if (!Duplex.prototype[method])
- Duplex.prototype[method] = Writable.prototype[method];
+ // at this point, no one needed a drain, so we just ran out of data
+ // on the next readable event, start it over again.
+ state.ranOut = true;
}
-function Duplex(options) {
- if (!(this instanceof Duplex))
- return new Duplex(options);
+function pipeOnReadable() {
+ if (this._readableState.ranOut) {
+ this._readableState.ranOut = false;
+ flow(this);
+ }
+}
- Readable.call(this, options);
- Writable.call(this, options);
- if (options && options.readable === false)
- this.readable = false;
+Readable.prototype.unpipe = function(dest) {
+ var state = this._readableState;
- if (options && options.writable === false)
- this.writable = false;
+ // if we're not piping anywhere, then do nothing.
+ if (state.pipesCount === 0)
+ return this;
- this.allowHalfOpen = true;
- if (options && options.allowHalfOpen === false)
- this.allowHalfOpen = false;
+ // just one destination. most common case.
+ if (state.pipesCount === 1) {
+ // passed in one, but it's not the right one.
+ if (dest && dest !== state.pipes)
+ return this;
- this.once('end', onend);
-}
+ if (!dest)
+ dest = state.pipes;
-// the no-half-open enforcer
-function onend() {
- // if we allow half-open state, or if the writable side ended,
- // then we're ok.
- if (this.allowHalfOpen || this._writableState.ended)
- return;
+ // got a match.
+ state.pipes = null;
+ state.pipesCount = 0;
+ this.removeListener('readable', pipeOnReadable);
+ state.flowing = false;
+ if (dest)
+ dest.emit('unpipe', this);
+ return this;
+ }
- // no more data can be written.
- // But allow more writes to happen in this tick.
- processNextTick(onEndNT, this);
-}
+ // slow case. multiple pipe destinations.
-function onEndNT(self) {
- self.end();
-}
+ if (!dest) {
+ // remove all.
+ var dests = state.pipes;
+ var len = state.pipesCount;
+ state.pipes = null;
+ state.pipesCount = 0;
+ this.removeListener('readable', pipeOnReadable);
+ state.flowing = false;
-function forEach (xs, f) {
- for (var i = 0, l = xs.length; i < l; i++) {
- f(xs[i], i);
+ for (var i = 0; i < len; i++)
+ dests[i].emit('unpipe', this);
+ return this;
}
-}
-},{"./_stream_readable":72,"./_stream_writable":74,"core-util-is":11,"inherits":18,"process-nextick-args":63}],71:[function(require,module,exports){
-// a passthrough stream.
-// basically just the most minimal sort of Transform stream.
-// Every written chunk gets output as-is.
+ // try to find the right one.
+ var i = indexOf(state.pipes, dest);
+ if (i === -1)
+ return this;
-'use strict';
+ state.pipes.splice(i, 1);
+ state.pipesCount -= 1;
+ if (state.pipesCount === 1)
+ state.pipes = state.pipes[0];
-module.exports = PassThrough;
+ dest.emit('unpipe', this);
-var Transform = require('./_stream_transform');
+ return this;
+};
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+// set up data events if they are asked for
+// Ensure readable listeners eventually get something
+Readable.prototype.on = function(ev, fn) {
+ var res = Stream.prototype.on.call(this, ev, fn);
-util.inherits(PassThrough, Transform);
+ if (ev === 'data' && !this._readableState.flowing)
+ emitDataEvents(this);
-function PassThrough(options) {
- if (!(this instanceof PassThrough))
- return new PassThrough(options);
+ if (ev === 'readable' && this.readable) {
+ var state = this._readableState;
+ if (!state.readableListening) {
+ state.readableListening = true;
+ state.emittedReadable = false;
+ state.needReadable = true;
+ if (!state.reading) {
+ this.read(0);
+ } else if (state.length) {
+ emitReadable(this, state);
+ }
+ }
+ }
- Transform.call(this, options);
-}
+ return res;
+};
+Readable.prototype.addListener = Readable.prototype.on;
-PassThrough.prototype._transform = function(chunk, encoding, cb) {
- cb(null, chunk);
+// pause() and resume() are remnants of the legacy readable stream API
+// If the user uses them, then switch into old mode.
+Readable.prototype.resume = function() {
+ emitDataEvents(this);
+ this.read(0);
+ this.emit('resume');
};
-},{"./_stream_transform":73,"core-util-is":11,"inherits":18}],72:[function(require,module,exports){
-(function (process){
-'use strict';
+Readable.prototype.pause = function() {
+ emitDataEvents(this, true);
+ this.emit('pause');
+};
-module.exports = Readable;
+function emitDataEvents(stream, startPaused) {
+ var state = stream._readableState;
-/**/
-var processNextTick = require('process-nextick-args');
-/**/
+ if (state.flowing) {
+ // https://github.com/isaacs/readable-stream/issues/16
+ throw new Error('Cannot switch to old mode now.');
+ }
+
+ var paused = startPaused || false;
+ var readable = false;
+ // convert to an old-style stream.
+ stream.readable = true;
+ stream.pipe = Stream.prototype.pipe;
+ stream.on = stream.addListener = Stream.prototype.on;
-/**/
-var isArray = require('isarray');
-/**/
+ stream.on('readable', function() {
+ readable = true;
+ var c;
+ while (!paused && (null !== (c = stream.read())))
+ stream.emit('data', c);
-/**/
-var Buffer = require('buffer').Buffer;
-/**/
+ if (c === null) {
+ readable = false;
+ stream._readableState.needReadable = true;
+ }
+ });
-Readable.ReadableState = ReadableState;
+ stream.pause = function() {
+ paused = true;
+ this.emit('pause');
+ };
-var EE = require('events').EventEmitter;
+ stream.resume = function() {
+ paused = false;
+ if (readable)
+ process.nextTick(function() {
+ stream.emit('readable');
+ });
+ else
+ this.read(0);
+ this.emit('resume');
+ };
-/**/
-if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
- return emitter.listeners(type).length;
-};
-/**/
+ // now make it start, just in case it hadn't already.
+ stream.emit('readable');
+}
+
+// wrap an old-style stream as the async data source.
+// This is *not* part of the readable stream interface.
+// It is an ugly unfortunate mess of history.
+Readable.prototype.wrap = function(stream) {
+ var state = this._readableState;
+ var paused = false;
+
+ var self = this;
+ stream.on('end', function() {
+ if (state.decoder && !state.ended) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length)
+ self.push(chunk);
+ }
+ self.push(null);
+ });
+ stream.on('data', function(chunk) {
+ if (state.decoder)
+ chunk = state.decoder.write(chunk);
-/**/
-var Stream;
-(function (){try{
- Stream = require('st' + 'ream');
-}catch(_){}finally{
- if (!Stream)
- Stream = require('events').EventEmitter;
-}}())
-/**/
+ // don't skip over falsy values in objectMode
+ //if (state.objectMode && util.isNullOrUndefined(chunk))
+ if (state.objectMode && (chunk === null || chunk === undefined))
+ return;
+ else if (!state.objectMode && (!chunk || !chunk.length))
+ return;
-var Buffer = require('buffer').Buffer;
+ var ret = self.push(chunk);
+ if (!ret) {
+ paused = true;
+ stream.pause();
+ }
+ });
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+ // proxy all the other methods.
+ // important when wrapping filters and duplexes.
+ for (var i in stream) {
+ if (typeof stream[i] === 'function' &&
+ typeof this[i] === 'undefined') {
+ this[i] = function(method) { return function() {
+ return stream[method].apply(stream, arguments);
+ }}(i);
+ }
+ }
+ // proxy certain important events.
+ var events = ['error', 'close', 'destroy', 'pause', 'resume'];
+ forEach(events, function(ev) {
+ stream.on(ev, self.emit.bind(self, ev));
+ });
+ // when we try to consume some more bytes, simply unpause the
+ // underlying stream.
+ self._read = function(n) {
+ if (paused) {
+ paused = false;
+ stream.resume();
+ }
+ };
-/**/
-var debug = require('util');
-if (debug && debug.debuglog) {
- debug = debug.debuglog('stream');
-} else {
- debug = function () {};
-}
-/**/
+ return self;
+};
-var StringDecoder;
-util.inherits(Readable, Stream);
-function ReadableState(options, stream) {
- var Duplex = require('./_stream_duplex');
+// exposed for testing purposes only.
+Readable._fromList = fromList;
- options = options || {};
+// Pluck off n bytes from an array of buffers.
+// Length is the combined lengths of all the buffers in the list.
+function fromList(n, state) {
+ var list = state.buffer;
+ var length = state.length;
+ var stringMode = !!state.decoder;
+ var objectMode = !!state.objectMode;
+ var ret;
- // object stream flag. Used to make read(n) ignore n and to
- // make all the buffer merging and length checks go away
- this.objectMode = !!options.objectMode;
+ // nothing in the list, definitely empty.
+ if (list.length === 0)
+ return null;
- if (stream instanceof Duplex)
- this.objectMode = this.objectMode || !!options.readableObjectMode;
+ if (length === 0)
+ ret = null;
+ else if (objectMode)
+ ret = list.shift();
+ else if (!n || n >= length) {
+ // read it all, truncate the array.
+ if (stringMode)
+ ret = list.join('');
+ else
+ ret = Buffer.concat(list, length);
+ list.length = 0;
+ } else {
+ // read just some of it.
+ if (n < list[0].length) {
+ // just take a part of the first list item.
+ // slice is the same for buffers and strings.
+ var buf = list[0];
+ ret = buf.slice(0, n);
+ list[0] = buf.slice(n);
+ } else if (n === list[0].length) {
+ // first list is a perfect match
+ ret = list.shift();
+ } else {
+ // complex case.
+ // we have enough to cover it, but it spans past the first buffer.
+ if (stringMode)
+ ret = '';
+ else
+ ret = new Buffer(n);
- // the point at which it stops calling _read() to fill the buffer
- // Note: 0 is a valid value, means "don't call _read preemptively ever"
- var hwm = options.highWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
- this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
+ var c = 0;
+ for (var i = 0, l = list.length; i < l && c < n; i++) {
+ var buf = list[0];
+ var cpy = Math.min(n - c, buf.length);
- // cast to ints.
- this.highWaterMark = ~~this.highWaterMark;
+ if (stringMode)
+ ret += buf.slice(0, cpy);
+ else
+ buf.copy(ret, c, 0, cpy);
- this.buffer = [];
- this.length = 0;
- this.pipes = null;
- this.pipesCount = 0;
- this.flowing = null;
- this.ended = false;
- this.endEmitted = false;
- this.reading = false;
+ if (cpy < buf.length)
+ list[0] = buf.slice(cpy);
+ else
+ list.shift();
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
+ c += cpy;
+ }
+ }
+ }
- // whenever we return null, then we set a flag to say
- // that we're awaiting a 'readable' event emission.
- this.needReadable = false;
- this.emittedReadable = false;
- this.readableListening = false;
+ return ret;
+}
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
+function endReadable(stream) {
+ var state = stream._readableState;
- // when piping, we only care about 'readable' events that happen
- // after read()ing all the bytes and not getting any pushback.
- this.ranOut = false;
+ // If we get here before consuming all the bytes, then that is a
+ // bug in node. Should never happen.
+ if (state.length > 0)
+ throw new Error('endReadable called on non-empty stream');
- // the number of writers that are awaiting a drain event in .pipe()s
- this.awaitDrain = 0;
+ if (!state.endEmitted && state.calledRead) {
+ state.ended = true;
+ process.nextTick(function() {
+ // Check that we didn't get one last unshift.
+ if (!state.endEmitted && state.length === 0) {
+ state.endEmitted = true;
+ stream.readable = false;
+ stream.emit('end');
+ }
+ });
+ }
+}
- // if true, a maybeReadMore has been scheduled
- this.readingMore = false;
+function forEach (xs, f) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ f(xs[i], i);
+ }
+}
- this.decoder = null;
- this.encoding = null;
- if (options.encoding) {
- if (!StringDecoder)
- StringDecoder = require('string_decoder/').StringDecoder;
- this.decoder = new StringDecoder(options.encoding);
- this.encoding = options.encoding;
+function indexOf (xs, x) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ if (xs[i] === x) return i;
}
+ return -1;
}
-function Readable(options) {
- var Duplex = require('./_stream_duplex');
+}).call(this,require('_process'))
+},{"_process":107,"buffer":8,"core-util-is":15,"events":18,"inherits":47,"isarray":53,"stream":124,"string_decoder/":129}],25:[function(require,module,exports){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
- if (!(this instanceof Readable))
- return new Readable(options);
- this._readableState = new ReadableState(options, this);
+// a transform stream is a readable/writable stream where you do
+// something with the data. Sometimes it's called a "filter",
+// but that's not a great name for it, since that implies a thing where
+// some bits pass through, and others are simply ignored. (That would
+// be a valid example of a transform, of course.)
+//
+// While the output is causally related to the input, it's not a
+// necessarily symmetric or synchronous transformation. For example,
+// a zlib stream might take multiple plain-text writes(), and then
+// emit a single compressed chunk some time in the future.
+//
+// Here's how this works:
+//
+// The Transform stream has all the aspects of the readable and writable
+// stream classes. When you write(chunk), that calls _write(chunk,cb)
+// internally, and returns false if there's a lot of pending writes
+// buffered up. When you call read(), that calls _read(n) until
+// there's enough pending readable data buffered up.
+//
+// In a transform stream, the written data is placed in a buffer. When
+// _read(n) is called, it transforms the queued up data, calling the
+// buffered _write cb's as it consumes chunks. If consuming a single
+// written chunk would result in multiple output chunks, then the first
+// outputted bit calls the readcb, and subsequent chunks just go into
+// the read buffer, and will cause it to emit 'readable' if necessary.
+//
+// This way, back-pressure is actually determined by the reading side,
+// since _read has to be called to start processing a new chunk. However,
+// a pathological inflate type of transform can cause excessive buffering
+// here. For example, imagine a stream where every byte of input is
+// interpreted as an integer from 0-255, and then results in that many
+// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
+// 1kb of data being output. In this case, you could write a very small
+// amount of input, and end up with a very large amount of output. In
+// such a pathological inflating mechanism, there'd be no way to tell
+// the system to stop doing the transform. A single 4MB write could
+// cause the system to run out of memory.
+//
+// However, even in such a pathological case, only a single written chunk
+// would be consumed, and then the rest would wait (un-transformed) until
+// the results of the previous transformed chunk were consumed.
+
+module.exports = Transform;
- // legacy
- this.readable = true;
+var Duplex = require('./_stream_duplex');
- if (options && typeof options.read === 'function')
- this._read = options.read;
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
- Stream.call(this);
-}
+util.inherits(Transform, Duplex);
-// Manually shove something into the read() buffer.
-// This returns true if the highWaterMark has not been hit yet,
-// similar to how Writable.write() returns true if you should
-// write() some more.
-Readable.prototype.push = function(chunk, encoding) {
- var state = this._readableState;
- if (!state.objectMode && typeof chunk === 'string') {
- encoding = encoding || state.defaultEncoding;
- if (encoding !== state.encoding) {
- chunk = new Buffer(chunk, encoding);
- encoding = '';
- }
- }
+function TransformState(options, stream) {
+ this.afterTransform = function(er, data) {
+ return afterTransform(stream, er, data);
+ };
- return readableAddChunk(this, state, chunk, encoding, false);
-};
+ this.needTransform = false;
+ this.transforming = false;
+ this.writecb = null;
+ this.writechunk = null;
+}
-// Unshift should *always* be something directly out of read()
-Readable.prototype.unshift = function(chunk) {
- var state = this._readableState;
- return readableAddChunk(this, state, chunk, '', true);
-};
+function afterTransform(stream, er, data) {
+ var ts = stream._transformState;
+ ts.transforming = false;
-Readable.prototype.isPaused = function() {
- return this._readableState.flowing === false;
-};
+ var cb = ts.writecb;
-function readableAddChunk(stream, state, chunk, encoding, addToFront) {
- var er = chunkInvalid(state, chunk);
- if (er) {
- stream.emit('error', er);
- } else if (chunk === null) {
- state.reading = false;
- onEofChunk(stream, state);
- } else if (state.objectMode || chunk && chunk.length > 0) {
- if (state.ended && !addToFront) {
- var e = new Error('stream.push() after EOF');
- stream.emit('error', e);
- } else if (state.endEmitted && addToFront) {
- var e = new Error('stream.unshift() after end event');
- stream.emit('error', e);
- } else {
- if (state.decoder && !addToFront && !encoding)
- chunk = state.decoder.write(chunk);
+ if (!cb)
+ return stream.emit('error', new Error('no writecb in Transform class'));
- if (!addToFront)
- state.reading = false;
+ ts.writechunk = null;
+ ts.writecb = null;
- // if we want the data now, just emit it.
- if (state.flowing && state.length === 0 && !state.sync) {
- stream.emit('data', chunk);
- stream.read(0);
- } else {
- // update the buffer info.
- state.length += state.objectMode ? 1 : chunk.length;
- if (addToFront)
- state.buffer.unshift(chunk);
- else
- state.buffer.push(chunk);
+ if (data !== null && data !== undefined)
+ stream.push(data);
- if (state.needReadable)
- emitReadable(stream);
- }
+ if (cb)
+ cb(er);
- maybeReadMore(stream, state);
- }
- } else if (!addToFront) {
- state.reading = false;
+ var rs = stream._readableState;
+ rs.reading = false;
+ if (rs.needReadable || rs.length < rs.highWaterMark) {
+ stream._read(rs.highWaterMark);
}
-
- return needMoreData(state);
}
+function Transform(options) {
+ if (!(this instanceof Transform))
+ return new Transform(options);
-// if it's past the high water mark, we can push in some more.
-// Also, if we have no data yet, we can stand some
-// more bytes. This is to work around cases where hwm=0,
-// such as the repl. Also, if the push() triggered a
-// readable event, and the user called read(largeNumber) such that
-// needReadable was set, then we ought to push more, so that another
-// 'readable' event will be triggered.
-function needMoreData(state) {
- return !state.ended &&
- (state.needReadable ||
- state.length < state.highWaterMark ||
- state.length === 0);
-}
+ Duplex.call(this, options);
-// backwards compatibility.
-Readable.prototype.setEncoding = function(enc) {
- if (!StringDecoder)
- StringDecoder = require('string_decoder/').StringDecoder;
- this._readableState.decoder = new StringDecoder(enc);
- this._readableState.encoding = enc;
- return this;
-};
+ var ts = this._transformState = new TransformState(options, this);
-// Don't raise the hwm > 128MB
-var MAX_HWM = 0x800000;
-function roundUpToNextPowerOf2(n) {
- if (n >= MAX_HWM) {
- n = MAX_HWM;
- } else {
- // Get the next highest power of 2
- n--;
- for (var p = 1; p < 32; p <<= 1) n |= n >> p;
- n++;
- }
- return n;
-}
+ // when the writable side finishes, then flush out anything remaining.
+ var stream = this;
-function howMuchToRead(n, state) {
- if (state.length === 0 && state.ended)
- return 0;
+ // start out asking for a readable event once data is transformed.
+ this._readableState.needReadable = true;
- if (state.objectMode)
- return n === 0 ? 0 : 1;
+ // we have implemented the _read method, and done the other things
+ // that Readable wants before the first _read call, so unset the
+ // sync guard flag.
+ this._readableState.sync = false;
- if (n === null || isNaN(n)) {
- // only flow one buffer at a time
- if (state.flowing && state.buffer.length)
- return state.buffer[0].length;
+ this.once('finish', function() {
+ if ('function' === typeof this._flush)
+ this._flush(function(er) {
+ done(stream, er);
+ });
else
- return state.length;
- }
+ done(stream);
+ });
+}
- if (n <= 0)
- return 0;
+Transform.prototype.push = function(chunk, encoding) {
+ this._transformState.needTransform = false;
+ return Duplex.prototype.push.call(this, chunk, encoding);
+};
- // If we're asking for more than the target buffer level,
- // then raise the water mark. Bump up to the next highest
- // power of 2, to prevent increasing it excessively in tiny
- // amounts.
- if (n > state.highWaterMark)
- state.highWaterMark = roundUpToNextPowerOf2(n);
+// This is the part where you do stuff!
+// override this function in implementation classes.
+// 'chunk' is an input chunk.
+//
+// Call `push(newChunk)` to pass along transformed output
+// to the readable side. You may call 'push' zero or more times.
+//
+// Call `cb(err)` when you are done with this chunk. If you pass
+// an error, then that'll put the hurt on the whole operation. If you
+// never call cb(), then you'll never get another chunk.
+Transform.prototype._transform = function(chunk, encoding, cb) {
+ throw new Error('not implemented');
+};
- // don't have that much. return null, unless we've ended.
- if (n > state.length) {
- if (!state.ended) {
- state.needReadable = true;
- return 0;
- } else {
- return state.length;
- }
+Transform.prototype._write = function(chunk, encoding, cb) {
+ var ts = this._transformState;
+ ts.writecb = cb;
+ ts.writechunk = chunk;
+ ts.writeencoding = encoding;
+ if (!ts.transforming) {
+ var rs = this._readableState;
+ if (ts.needTransform ||
+ rs.needReadable ||
+ rs.length < rs.highWaterMark)
+ this._read(rs.highWaterMark);
}
+};
- return n;
-}
-
-// you can override either this method, or the async _read(n) below.
-Readable.prototype.read = function(n) {
- debug('read', n);
- var state = this._readableState;
- var nOrig = n;
-
- if (typeof n !== 'number' || n > 0)
- state.emittedReadable = false;
+// Doesn't matter what the args are here.
+// _transform does all the work.
+// That we got here means that the readable side wants more data.
+Transform.prototype._read = function(n) {
+ var ts = this._transformState;
- // if we're doing read(0) to trigger a readable event, but we
- // already have a bunch of data in the buffer, then just trigger
- // the 'readable' event and move on.
- if (n === 0 &&
- state.needReadable &&
- (state.length >= state.highWaterMark || state.ended)) {
- debug('read: emitReadable', state.length, state.ended);
- if (state.length === 0 && state.ended)
- endReadable(this);
- else
- emitReadable(this);
- return null;
+ if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
+ ts.transforming = true;
+ this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
+ } else {
+ // mark that we need a transform, so that any data that comes in
+ // will get processed, now that we've asked for it.
+ ts.needTransform = true;
}
+};
- n = howMuchToRead(n, state);
- // if we've ended, and we're now clear, then finish it up.
- if (n === 0 && state.ended) {
- if (state.length === 0)
- endReadable(this);
- return null;
- }
+function done(stream, er) {
+ if (er)
+ return stream.emit('error', er);
- // All the actual chunk generation logic needs to be
- // *below* the call to _read. The reason is that in certain
- // synthetic stream cases, such as passthrough streams, _read
- // may be a completely synchronous operation which may change
- // the state of the read buffer, providing enough data when
- // before there was *not* enough.
- //
- // So, the steps are:
- // 1. Figure out what the state of things will be after we do
- // a read from the buffer.
- //
- // 2. If that resulting state will trigger a _read, then call _read.
- // Note that this may be asynchronous, or synchronous. Yes, it is
- // deeply ugly to write APIs this way, but that still doesn't mean
- // that the Readable class should behave improperly, as streams are
- // designed to be sync/async agnostic.
- // Take note if the _read call is sync or async (ie, if the read call
- // has returned yet), so that we know whether or not it's safe to emit
- // 'readable' etc.
- //
- // 3. Actually pull the requested chunks out of the buffer and return.
+ // if there's nothing in the write buffer, then that means
+ // that nothing more will ever be provided
+ var ws = stream._writableState;
+ var rs = stream._readableState;
+ var ts = stream._transformState;
- // if we need a readable event, then we need to do some reading.
- var doRead = state.needReadable;
- debug('need readable', doRead);
+ if (ws.length)
+ throw new Error('calling transform done when ws.length != 0');
- // if we currently have less than the highWaterMark, then also read some
- if (state.length === 0 || state.length - n < state.highWaterMark) {
- doRead = true;
- debug('length less than watermark', doRead);
- }
+ if (ts.transforming)
+ throw new Error('calling transform done when still transforming');
- // however, if we've ended, then there's no point, and if we're already
- // reading, then it's unnecessary.
- if (state.ended || state.reading) {
- doRead = false;
- debug('reading or ended', doRead);
- }
+ return stream.push(null);
+}
- if (doRead) {
- debug('do read');
- state.reading = true;
- state.sync = true;
- // if the length is currently zero, then we *need* a readable event.
- if (state.length === 0)
- state.needReadable = true;
- // call internal read method
- this._read(state.highWaterMark);
- state.sync = false;
- }
+},{"./_stream_duplex":23,"core-util-is":15,"inherits":47}],26:[function(require,module,exports){
+(function (process){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
- // If _read pushed data synchronously, then `reading` will be false,
- // and we need to re-evaluate how much data we can return to the user.
- if (doRead && !state.reading)
- n = howMuchToRead(nOrig, state);
+// A bit simpler than readable streams.
+// Implement an async ._write(chunk, cb), and it'll handle all
+// the drain event emission and buffering.
- var ret;
- if (n > 0)
- ret = fromList(n, state);
- else
- ret = null;
+module.exports = Writable;
- if (ret === null) {
- state.needReadable = true;
- n = 0;
- }
+/**/
+var Buffer = require('buffer').Buffer;
+/**/
- state.length -= n;
+Writable.WritableState = WritableState;
- // If we have nothing in the buffer, then we want to know
- // as soon as we *do* get something into the buffer.
- if (state.length === 0 && !state.ended)
- state.needReadable = true;
- // If we tried to read() past the EOF, then emit end on the next tick.
- if (nOrig !== n && state.ended && state.length === 0)
- endReadable(this);
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
- if (ret !== null)
- this.emit('data', ret);
+var Stream = require('stream');
- return ret;
-};
+util.inherits(Writable, Stream);
-function chunkInvalid(state, chunk) {
- var er = null;
- if (!(Buffer.isBuffer(chunk)) &&
- typeof chunk !== 'string' &&
- chunk !== null &&
- chunk !== undefined &&
- !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- return er;
+function WriteReq(chunk, encoding, cb) {
+ this.chunk = chunk;
+ this.encoding = encoding;
+ this.callback = cb;
}
+function WritableState(options, stream) {
+ options = options || {};
-function onEofChunk(stream, state) {
- if (state.ended) return;
- if (state.decoder) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) {
- state.buffer.push(chunk);
- state.length += state.objectMode ? 1 : chunk.length;
- }
- }
- state.ended = true;
+ // the point at which write() starts returning false
+ // Note: 0 is a valid value, means that we always return false if
+ // the entire buffer is not flushed immediately on write()
+ var hwm = options.highWaterMark;
+ this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
- // emit 'readable' now to make sure it gets picked up.
- emitReadable(stream);
-}
+ // object stream flag to indicate whether or not this stream
+ // contains buffers or objects.
+ this.objectMode = !!options.objectMode;
-// Don't emit readable right away in sync mode, because this can trigger
-// another read() call => stack overflow. This way, it might trigger
-// a nextTick recursion warning, but that's not so bad.
-function emitReadable(stream) {
- var state = stream._readableState;
- state.needReadable = false;
- if (!state.emittedReadable) {
- debug('emitReadable', state.flowing);
- state.emittedReadable = true;
- if (state.sync)
- processNextTick(emitReadable_, stream);
- else
- emitReadable_(stream);
- }
-}
+ // cast to ints.
+ this.highWaterMark = ~~this.highWaterMark;
-function emitReadable_(stream) {
- debug('emit readable');
- stream.emit('readable');
- flow(stream);
-}
+ this.needDrain = false;
+ // at the start of calling end()
+ this.ending = false;
+ // when end() has been called, and returned
+ this.ended = false;
+ // when 'finish' is emitted
+ this.finished = false;
+ // should we decode strings into buffers before passing to _write?
+ // this is here so that some node-core streams can optimize string
+ // handling at a lower level.
+ var noDecode = options.decodeStrings === false;
+ this.decodeStrings = !noDecode;
-// at this point, the user has presumably seen the 'readable' event,
-// and called read() to consume some data. that may have triggered
-// in turn another _read(n) call, in which case reading = true if
-// it's in progress.
-// However, if we're not ended, or reading, and the length < hwm,
-// then go ahead and try to read some more preemptively.
-function maybeReadMore(stream, state) {
- if (!state.readingMore) {
- state.readingMore = true;
- processNextTick(maybeReadMore_, stream, state);
- }
-}
+ // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+ this.defaultEncoding = options.defaultEncoding || 'utf8';
-function maybeReadMore_(stream, state) {
- var len = state.length;
- while (!state.reading && !state.flowing && !state.ended &&
- state.length < state.highWaterMark) {
- debug('maybeReadMore read 0');
- stream.read(0);
- if (len === state.length)
- // didn't get any data, stop spinning.
- break;
- else
- len = state.length;
- }
- state.readingMore = false;
-}
+ // not an actual buffer we keep track of, but a measurement
+ // of how much we're waiting to get pushed to some underlying
+ // socket or file.
+ this.length = 0;
-// abstract method. to be overridden in specific implementation classes.
-// call cb(er, data) where data is <= n in length.
-// for virtual (non-string, non-buffer) streams, "length" is somewhat
-// arbitrary, and perhaps not very meaningful.
-Readable.prototype._read = function(n) {
- this.emit('error', new Error('not implemented'));
-};
+ // a flag to see when we're in the middle of a write.
+ this.writing = false;
-Readable.prototype.pipe = function(dest, pipeOpts) {
- var src = this;
- var state = this._readableState;
+ // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, becuase any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+ this.sync = true;
+
+ // a flag to know if we're processing previously buffered items, which
+ // may call the _write() callback in the same tick, so that we don't
+ // end up in an overlapped onwrite situation.
+ this.bufferProcessing = false;
- switch (state.pipesCount) {
- case 0:
- state.pipes = dest;
- break;
- case 1:
- state.pipes = [state.pipes, dest];
- break;
- default:
- state.pipes.push(dest);
- break;
- }
- state.pipesCount += 1;
- debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
+ // the callback that's passed to _write(chunk,cb)
+ this.onwrite = function(er) {
+ onwrite(stream, er);
+ };
- var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
- dest !== process.stdout &&
- dest !== process.stderr;
+ // the callback that the user supplies to write(chunk,encoding,cb)
+ this.writecb = null;
- var endFn = doEnd ? onend : cleanup;
- if (state.endEmitted)
- processNextTick(endFn);
- else
- src.once('end', endFn);
+ // the amount that is being written when _write is called.
+ this.writelen = 0;
- dest.on('unpipe', onunpipe);
- function onunpipe(readable) {
- debug('onunpipe');
- if (readable === src) {
- cleanup();
- }
- }
+ this.buffer = [];
- function onend() {
- debug('onend');
- dest.end();
- }
+ // True if the error was already emitted and should not be thrown again
+ this.errorEmitted = false;
+}
- // when the dest drains, it reduces the awaitDrain counter
- // on the source. This would be more elegant with a .once()
- // handler in flow(), but adding and removing repeatedly is
- // too slow.
- var ondrain = pipeOnDrain(src);
- dest.on('drain', ondrain);
+function Writable(options) {
+ var Duplex = require('./_stream_duplex');
- function cleanup() {
- debug('cleanup');
- // cleanup event handlers once the pipe is broken
- dest.removeListener('close', onclose);
- dest.removeListener('finish', onfinish);
- dest.removeListener('drain', ondrain);
- dest.removeListener('error', onerror);
- dest.removeListener('unpipe', onunpipe);
- src.removeListener('end', onend);
- src.removeListener('end', cleanup);
- src.removeListener('data', ondata);
+ // Writable ctor is applied to Duplexes, though they're not
+ // instanceof Writable, they're instanceof Readable.
+ if (!(this instanceof Writable) && !(this instanceof Duplex))
+ return new Writable(options);
- // if the reader is waiting for a drain event from this
- // specific writer, then it would cause it to never start
- // flowing again.
- // So, if this is awaiting a drain, then we just call it now.
- // If we don't know, then assume that we are waiting for one.
- if (state.awaitDrain &&
- (!dest._writableState || dest._writableState.needDrain))
- ondrain();
- }
+ this._writableState = new WritableState(options, this);
- src.on('data', ondata);
- function ondata(chunk) {
- debug('ondata');
- var ret = dest.write(chunk);
- if (false === ret) {
- debug('false write response, pause',
- src._readableState.awaitDrain);
- src._readableState.awaitDrain++;
- src.pause();
- }
- }
+ // legacy.
+ this.writable = true;
- // if the dest has an error, then stop piping into it.
- // however, don't suppress the throwing behavior for this.
- function onerror(er) {
- debug('onerror', er);
- unpipe();
- dest.removeListener('error', onerror);
- if (EE.listenerCount(dest, 'error') === 0)
- dest.emit('error', er);
- }
- // This is a brutally ugly hack to make sure that our error handler
- // is attached before any userland ones. NEVER DO THIS.
- if (!dest._events || !dest._events.error)
- dest.on('error', onerror);
- else if (isArray(dest._events.error))
- dest._events.error.unshift(onerror);
- else
- dest._events.error = [onerror, dest._events.error];
+ Stream.call(this);
+}
+// Otherwise people can pipe Writable streams, which is just wrong.
+Writable.prototype.pipe = function() {
+ this.emit('error', new Error('Cannot pipe. Not readable.'));
+};
- // Both close and finish should trigger unpipe, but only once.
- function onclose() {
- dest.removeListener('finish', onfinish);
- unpipe();
- }
- dest.once('close', onclose);
- function onfinish() {
- debug('onfinish');
- dest.removeListener('close', onclose);
- unpipe();
- }
- dest.once('finish', onfinish);
+function writeAfterEnd(stream, state, cb) {
+ var er = new Error('write after end');
+ // TODO: defer error events consistently everywhere, not just the cb
+ stream.emit('error', er);
+ process.nextTick(function() {
+ cb(er);
+ });
+}
- function unpipe() {
- debug('unpipe');
- src.unpipe(dest);
+// If we get something that is not a buffer, string, null, or undefined,
+// and we're not in objectMode, then that's an error.
+// Otherwise stream chunks are all considered to be of length=1, and the
+// watermarks determine how many objects to keep in the buffer, rather than
+// how many bytes or characters.
+function validChunk(stream, state, chunk, cb) {
+ var valid = true;
+ if (!Buffer.isBuffer(chunk) &&
+ 'string' !== typeof chunk &&
+ chunk !== null &&
+ chunk !== undefined &&
+ !state.objectMode) {
+ var er = new TypeError('Invalid non-string/buffer chunk');
+ stream.emit('error', er);
+ process.nextTick(function() {
+ cb(er);
+ });
+ valid = false;
}
+ return valid;
+}
- // tell the dest that it's being piped to
- dest.emit('pipe', src);
+Writable.prototype.write = function(chunk, encoding, cb) {
+ var state = this._writableState;
+ var ret = false;
- // start the flow if it hasn't been started already.
- if (!state.flowing) {
- debug('pipe resume');
- src.resume();
+ if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
}
- return dest;
-};
+ if (Buffer.isBuffer(chunk))
+ encoding = 'buffer';
+ else if (!encoding)
+ encoding = state.defaultEncoding;
-function pipeOnDrain(src) {
- return function() {
- var state = src._readableState;
- debug('pipeOnDrain', state.awaitDrain);
- if (state.awaitDrain)
- state.awaitDrain--;
- if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
- state.flowing = true;
- flow(src);
- }
- };
-}
+ if (typeof cb !== 'function')
+ cb = function() {};
+
+ if (state.ended)
+ writeAfterEnd(this, state, cb);
+ else if (validChunk(this, state, chunk, cb))
+ ret = writeOrBuffer(this, state, chunk, encoding, cb);
+ return ret;
+};
-Readable.prototype.unpipe = function(dest) {
- var state = this._readableState;
+function decodeChunk(state, chunk, encoding) {
+ if (!state.objectMode &&
+ state.decodeStrings !== false &&
+ typeof chunk === 'string') {
+ chunk = new Buffer(chunk, encoding);
+ }
+ return chunk;
+}
- // if we're not piping anywhere, then do nothing.
- if (state.pipesCount === 0)
- return this;
+// if we're already writing something, then just put this
+// in the queue, and wait our turn. Otherwise, call _write
+// If we return false, then we need a drain event, so set that flag.
+function writeOrBuffer(stream, state, chunk, encoding, cb) {
+ chunk = decodeChunk(state, chunk, encoding);
+ if (Buffer.isBuffer(chunk))
+ encoding = 'buffer';
+ var len = state.objectMode ? 1 : chunk.length;
- // just one destination. most common case.
- if (state.pipesCount === 1) {
- // passed in one, but it's not the right one.
- if (dest && dest !== state.pipes)
- return this;
+ state.length += len;
- if (!dest)
- dest = state.pipes;
+ var ret = state.length < state.highWaterMark;
+ // we must ensure that previous needDrain will not be reset to false.
+ if (!ret)
+ state.needDrain = true;
- // got a match.
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
- if (dest)
- dest.emit('unpipe', this);
- return this;
- }
+ if (state.writing)
+ state.buffer.push(new WriteReq(chunk, encoding, cb));
+ else
+ doWrite(stream, state, len, chunk, encoding, cb);
- // slow case. multiple pipe destinations.
+ return ret;
+}
- if (!dest) {
- // remove all.
- var dests = state.pipes;
- var len = state.pipesCount;
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
+function doWrite(stream, state, len, chunk, encoding, cb) {
+ state.writelen = len;
+ state.writecb = cb;
+ state.writing = true;
+ state.sync = true;
+ stream._write(chunk, encoding, state.onwrite);
+ state.sync = false;
+}
- for (var i = 0; i < len; i++)
- dests[i].emit('unpipe', this);
- return this;
- }
+function onwriteError(stream, state, sync, er, cb) {
+ if (sync)
+ process.nextTick(function() {
+ cb(er);
+ });
+ else
+ cb(er);
- // try to find the right one.
- var i = indexOf(state.pipes, dest);
- if (i === -1)
- return this;
+ stream._writableState.errorEmitted = true;
+ stream.emit('error', er);
+}
- state.pipes.splice(i, 1);
- state.pipesCount -= 1;
- if (state.pipesCount === 1)
- state.pipes = state.pipes[0];
+function onwriteStateUpdate(state) {
+ state.writing = false;
+ state.writecb = null;
+ state.length -= state.writelen;
+ state.writelen = 0;
+}
- dest.emit('unpipe', this);
+function onwrite(stream, er) {
+ var state = stream._writableState;
+ var sync = state.sync;
+ var cb = state.writecb;
- return this;
-};
+ onwriteStateUpdate(state);
-// set up data events if they are asked for
-// Ensure readable listeners eventually get something
-Readable.prototype.on = function(ev, fn) {
- var res = Stream.prototype.on.call(this, ev, fn);
+ if (er)
+ onwriteError(stream, state, sync, er, cb);
+ else {
+ // Check if we're actually ready to finish, but don't emit yet
+ var finished = needFinish(stream, state);
- // If listening to data, and it has not explicitly been paused,
- // then call resume to start the flow of data on the next tick.
- if (ev === 'data' && false !== this._readableState.flowing) {
- this.resume();
- }
+ if (!finished && !state.bufferProcessing && state.buffer.length)
+ clearBuffer(stream, state);
- if (ev === 'readable' && this.readable) {
- var state = this._readableState;
- if (!state.readableListening) {
- state.readableListening = true;
- state.emittedReadable = false;
- state.needReadable = true;
- if (!state.reading) {
- processNextTick(nReadingNextTick, this);
- } else if (state.length) {
- emitReadable(this, state);
- }
+ if (sync) {
+ process.nextTick(function() {
+ afterWrite(stream, state, finished, cb);
+ });
+ } else {
+ afterWrite(stream, state, finished, cb);
}
}
-
- return res;
-};
-Readable.prototype.addListener = Readable.prototype.on;
-
-function nReadingNextTick(self) {
- debug('readable nexttick read 0');
- self.read(0);
}
-// pause() and resume() are remnants of the legacy readable stream API
-// If the user uses them, then switch into old mode.
-Readable.prototype.resume = function() {
- var state = this._readableState;
- if (!state.flowing) {
- debug('resume');
- state.flowing = true;
- resume(this, state);
- }
- return this;
-};
+function afterWrite(stream, state, finished, cb) {
+ if (!finished)
+ onwriteDrain(stream, state);
+ cb();
+ if (finished)
+ finishMaybe(stream, state);
+}
-function resume(stream, state) {
- if (!state.resumeScheduled) {
- state.resumeScheduled = true;
- processNextTick(resume_, stream, state);
+// Must force callback to be called on nextTick, so that we don't
+// emit 'drain' before the write() consumer gets the 'false' return
+// value, and has a chance to attach a 'drain' listener.
+function onwriteDrain(stream, state) {
+ if (state.length === 0 && state.needDrain) {
+ state.needDrain = false;
+ stream.emit('drain');
}
}
-function resume_(stream, state) {
- if (!state.reading) {
- debug('resume read 0');
- stream.read(0);
- }
- state.resumeScheduled = false;
- stream.emit('resume');
- flow(stream);
- if (state.flowing && !state.reading)
- stream.read(0);
-}
+// if there's something in the buffer waiting, then process it
+function clearBuffer(stream, state) {
+ state.bufferProcessing = true;
-Readable.prototype.pause = function() {
- debug('call pause flowing=%j', this._readableState.flowing);
- if (false !== this._readableState.flowing) {
- debug('pause');
- this._readableState.flowing = false;
- this.emit('pause');
- }
- return this;
-};
+ for (var c = 0; c < state.buffer.length; c++) {
+ var entry = state.buffer[c];
+ var chunk = entry.chunk;
+ var encoding = entry.encoding;
+ var cb = entry.callback;
+ var len = state.objectMode ? 1 : chunk.length;
-function flow(stream) {
- var state = stream._readableState;
- debug('flow', state.flowing);
- if (state.flowing) {
- do {
- var chunk = stream.read();
- } while (null !== chunk && state.flowing);
+ doWrite(stream, state, len, chunk, encoding, cb);
+
+ // if we didn't call the onwrite immediately, then
+ // it means that we need to wait until it does.
+ // also, that means that the chunk and cb are currently
+ // being processed, so move the buffer counter past them.
+ if (state.writing) {
+ c++;
+ break;
+ }
}
+
+ state.bufferProcessing = false;
+ if (c < state.buffer.length)
+ state.buffer = state.buffer.slice(c);
+ else
+ state.buffer.length = 0;
}
-// wrap an old-style stream as the async data source.
-// This is *not* part of the readable stream interface.
-// It is an ugly unfortunate mess of history.
-Readable.prototype.wrap = function(stream) {
- var state = this._readableState;
- var paused = false;
+Writable.prototype._write = function(chunk, encoding, cb) {
+ cb(new Error('not implemented'));
+};
- var self = this;
- stream.on('end', function() {
- debug('wrapped end');
- if (state.decoder && !state.ended) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length)
- self.push(chunk);
- }
+Writable.prototype.end = function(chunk, encoding, cb) {
+ var state = this._writableState;
- self.push(null);
- });
+ if (typeof chunk === 'function') {
+ cb = chunk;
+ chunk = null;
+ encoding = null;
+ } else if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
- stream.on('data', function(chunk) {
- debug('wrapped data');
- if (state.decoder)
- chunk = state.decoder.write(chunk);
+ if (typeof chunk !== 'undefined' && chunk !== null)
+ this.write(chunk, encoding);
- // don't skip over falsy values in objectMode
- if (state.objectMode && (chunk === null || chunk === undefined))
- return;
- else if (!state.objectMode && (!chunk || !chunk.length))
- return;
+ // ignore unnecessary end() calls.
+ if (!state.ending && !state.finished)
+ endWritable(this, state, cb);
+};
- var ret = self.push(chunk);
- if (!ret) {
- paused = true;
- stream.pause();
- }
- });
- // proxy all the other methods.
- // important when wrapping filters and duplexes.
- for (var i in stream) {
- if (this[i] === undefined && typeof stream[i] === 'function') {
- this[i] = function(method) { return function() {
- return stream[method].apply(stream, arguments);
- }; }(i);
- }
- }
+function needFinish(stream, state) {
+ return (state.ending &&
+ state.length === 0 &&
+ !state.finished &&
+ !state.writing);
+}
- // proxy certain important events.
- var events = ['error', 'close', 'destroy', 'pause', 'resume'];
- forEach(events, function(ev) {
- stream.on(ev, self.emit.bind(self, ev));
- });
+function finishMaybe(stream, state) {
+ var need = needFinish(stream, state);
+ if (need) {
+ state.finished = true;
+ stream.emit('finish');
+ }
+ return need;
+}
- // when we try to consume some more bytes, simply unpause the
- // underlying stream.
- self._read = function(n) {
- debug('wrapped _read', n);
- if (paused) {
- paused = false;
- stream.resume();
- }
- };
+function endWritable(stream, state, cb) {
+ state.ending = true;
+ finishMaybe(stream, state);
+ if (cb) {
+ if (state.finished)
+ process.nextTick(cb);
+ else
+ stream.once('finish', cb);
+ }
+ state.ended = true;
+}
- return self;
-};
+}).call(this,require('_process'))
+},{"./_stream_duplex":23,"_process":107,"buffer":8,"core-util-is":15,"inherits":47,"stream":124}],27:[function(require,module,exports){
+module.exports = require("./lib/_stream_transform.js")
+},{"./lib/_stream_transform.js":25}],28:[function(require,module,exports){
+(function (process){
+var Transform = require('readable-stream/transform')
+ , inherits = require('util').inherits
+ , xtend = require('xtend')
+function DestroyableTransform(opts) {
+ Transform.call(this, opts)
+ this._destroyed = false
+}
-// exposed for testing purposes only.
-Readable._fromList = fromList;
+inherits(DestroyableTransform, Transform)
-// Pluck off n bytes from an array of buffers.
-// Length is the combined lengths of all the buffers in the list.
-function fromList(n, state) {
- var list = state.buffer;
- var length = state.length;
- var stringMode = !!state.decoder;
- var objectMode = !!state.objectMode;
- var ret;
+DestroyableTransform.prototype.destroy = function(err) {
+ if (this._destroyed) return
+ this._destroyed = true
+
+ var self = this
+ process.nextTick(function() {
+ if (err)
+ self.emit('error', err)
+ self.emit('close')
+ })
+}
- // nothing in the list, definitely empty.
- if (list.length === 0)
- return null;
+// a noop _transform function
+function noop (chunk, enc, callback) {
+ callback(null, chunk)
+}
- if (length === 0)
- ret = null;
- else if (objectMode)
- ret = list.shift();
- else if (!n || n >= length) {
- // read it all, truncate the array.
- if (stringMode)
- ret = list.join('');
- else
- ret = Buffer.concat(list, length);
- list.length = 0;
- } else {
- // read just some of it.
- if (n < list[0].length) {
- // just take a part of the first list item.
- // slice is the same for buffers and strings.
- var buf = list[0];
- ret = buf.slice(0, n);
- list[0] = buf.slice(n);
- } else if (n === list[0].length) {
- // first list is a perfect match
- ret = list.shift();
- } else {
- // complex case.
- // we have enough to cover it, but it spans past the first buffer.
- if (stringMode)
- ret = '';
- else
- ret = new Buffer(n);
- var c = 0;
- for (var i = 0, l = list.length; i < l && c < n; i++) {
- var buf = list[0];
- var cpy = Math.min(n - c, buf.length);
+// create a new export function, used by both the main export and
+// the .ctor export, contains common logic for dealing with arguments
+function through2 (construct) {
+ return function (options, transform, flush) {
+ if (typeof options == 'function') {
+ flush = transform
+ transform = options
+ options = {}
+ }
- if (stringMode)
- ret += buf.slice(0, cpy);
- else
- buf.copy(ret, c, 0, cpy);
+ if (typeof transform != 'function')
+ transform = noop
- if (cpy < buf.length)
- list[0] = buf.slice(cpy);
- else
- list.shift();
+ if (typeof flush != 'function')
+ flush = null
- c += cpy;
- }
- }
+ return construct(options, transform, flush)
}
-
- return ret;
}
-function endReadable(stream) {
- var state = stream._readableState;
- // If we get here before consuming all the bytes, then that is a
- // bug in node. Should never happen.
- if (state.length > 0)
- throw new Error('endReadable called on non-empty stream');
+// main export, just make me a transform stream!
+module.exports = through2(function (options, transform, flush) {
+ var t2 = new DestroyableTransform(options)
- if (!state.endEmitted) {
- state.ended = true;
- processNextTick(endReadableNT, state, stream);
- }
-}
+ t2._transform = transform
-function endReadableNT(state, stream) {
- // Check that we didn't get one last unshift.
- if (!state.endEmitted && state.length === 0) {
- state.endEmitted = true;
- stream.readable = false;
- stream.emit('end');
- }
-}
+ if (flush)
+ t2._flush = flush
-function forEach (xs, f) {
- for (var i = 0, l = xs.length; i < l; i++) {
- f(xs[i], i);
- }
-}
+ return t2
+})
-function indexOf (xs, x) {
- for (var i = 0, l = xs.length; i < l; i++) {
- if (xs[i] === x) return i;
+
+// make me a reusable prototype that I can `new`, or implicitly `new`
+// with a constructor call
+module.exports.ctor = through2(function (options, transform, flush) {
+ function Through2 (override) {
+ if (!(this instanceof Through2))
+ return new Through2(override)
+
+ this.options = xtend(options, override)
+
+ DestroyableTransform.call(this, this.options)
}
- return -1;
-}
-}).call(this,require('_process'))
-},{"./_stream_duplex":70,"_process":64,"buffer":6,"core-util-is":11,"events":14,"inherits":18,"isarray":22,"process-nextick-args":63,"string_decoder/":86,"util":3}],73:[function(require,module,exports){
-// a transform stream is a readable/writable stream where you do
-// something with the data. Sometimes it's called a "filter",
-// but that's not a great name for it, since that implies a thing where
-// some bits pass through, and others are simply ignored. (That would
-// be a valid example of a transform, of course.)
-//
-// While the output is causally related to the input, it's not a
-// necessarily symmetric or synchronous transformation. For example,
-// a zlib stream might take multiple plain-text writes(), and then
-// emit a single compressed chunk some time in the future.
-//
-// Here's how this works:
-//
-// The Transform stream has all the aspects of the readable and writable
-// stream classes. When you write(chunk), that calls _write(chunk,cb)
-// internally, and returns false if there's a lot of pending writes
-// buffered up. When you call read(), that calls _read(n) until
-// there's enough pending readable data buffered up.
-//
-// In a transform stream, the written data is placed in a buffer. When
-// _read(n) is called, it transforms the queued up data, calling the
-// buffered _write cb's as it consumes chunks. If consuming a single
-// written chunk would result in multiple output chunks, then the first
-// outputted bit calls the readcb, and subsequent chunks just go into
-// the read buffer, and will cause it to emit 'readable' if necessary.
-//
-// This way, back-pressure is actually determined by the reading side,
-// since _read has to be called to start processing a new chunk. However,
-// a pathological inflate type of transform can cause excessive buffering
-// here. For example, imagine a stream where every byte of input is
-// interpreted as an integer from 0-255, and then results in that many
-// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
-// 1kb of data being output. In this case, you could write a very small
-// amount of input, and end up with a very large amount of output. In
-// such a pathological inflating mechanism, there'd be no way to tell
-// the system to stop doing the transform. A single 4MB write could
-// cause the system to run out of memory.
-//
-// However, even in such a pathological case, only a single written chunk
-// would be consumed, and then the rest would wait (un-transformed) until
-// the results of the previous transformed chunk were consumed.
+ inherits(Through2, DestroyableTransform)
-'use strict';
+ Through2.prototype._transform = transform
-module.exports = Transform;
+ if (flush)
+ Through2.prototype._flush = flush
-var Duplex = require('./_stream_duplex');
+ return Through2
+})
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
-util.inherits(Transform, Duplex);
+module.exports.obj = through2(function (options, transform, flush) {
+ var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options))
+ t2._transform = transform
-function TransformState(stream) {
- this.afterTransform = function(er, data) {
- return afterTransform(stream, er, data);
- };
+ if (flush)
+ t2._flush = flush
- this.needTransform = false;
- this.transforming = false;
- this.writecb = null;
- this.writechunk = null;
+ return t2
+})
+
+}).call(this,require('_process'))
+},{"_process":107,"readable-stream/transform":27,"util":138,"xtend":174}],29:[function(require,module,exports){
+(function (process){
+exports.alphasort = alphasort
+exports.alphasorti = alphasorti
+exports.setopts = setopts
+exports.ownProp = ownProp
+exports.makeAbs = makeAbs
+exports.finish = finish
+exports.mark = mark
+exports.isIgnored = isIgnored
+exports.childrenIgnored = childrenIgnored
+
+function ownProp (obj, field) {
+ return Object.prototype.hasOwnProperty.call(obj, field)
}
-function afterTransform(stream, er, data) {
- var ts = stream._transformState;
- ts.transforming = false;
+var path = require("path")
+var minimatch = require("minimatch")
+var isAbsolute = require("path-is-absolute")
+var Minimatch = minimatch.Minimatch
- var cb = ts.writecb;
+function alphasorti (a, b) {
+ return a.toLowerCase().localeCompare(b.toLowerCase())
+}
- if (!cb)
- return stream.emit('error', new Error('no writecb in Transform class'));
+function alphasort (a, b) {
+ return a.localeCompare(b)
+}
+
+function setupIgnores (self, options) {
+ self.ignore = options.ignore || []
- ts.writechunk = null;
- ts.writecb = null;
+ if (!Array.isArray(self.ignore))
+ self.ignore = [self.ignore]
- if (data !== null && data !== undefined)
- stream.push(data);
+ if (self.ignore.length) {
+ self.ignore = self.ignore.map(ignoreMap)
+ }
+}
- if (cb)
- cb(er);
+function ignoreMap (pattern) {
+ var gmatcher = null
+ if (pattern.slice(-3) === '/**') {
+ var gpattern = pattern.replace(/(\/\*\*)+$/, '')
+ gmatcher = new Minimatch(gpattern)
+ }
- var rs = stream._readableState;
- rs.reading = false;
- if (rs.needReadable || rs.length < rs.highWaterMark) {
- stream._read(rs.highWaterMark);
+ return {
+ matcher: new Minimatch(pattern),
+ gmatcher: gmatcher
}
}
+function setopts (self, pattern, options) {
+ if (!options)
+ options = {}
-function Transform(options) {
- if (!(this instanceof Transform))
- return new Transform(options);
+ // base-matching: just use globstar for that.
+ if (options.matchBase && -1 === pattern.indexOf("/")) {
+ if (options.noglobstar) {
+ throw new Error("base matching requires globstar")
+ }
+ pattern = "**/" + pattern
+ }
- Duplex.call(this, options);
+ self.silent = !!options.silent
+ self.pattern = pattern
+ self.strict = options.strict !== false
+ self.realpath = !!options.realpath
+ self.realpathCache = options.realpathCache || Object.create(null)
+ self.follow = !!options.follow
+ self.dot = !!options.dot
+ self.mark = !!options.mark
+ self.nodir = !!options.nodir
+ if (self.nodir)
+ self.mark = true
+ self.sync = !!options.sync
+ self.nounique = !!options.nounique
+ self.nonull = !!options.nonull
+ self.nosort = !!options.nosort
+ self.nocase = !!options.nocase
+ self.stat = !!options.stat
+ self.noprocess = !!options.noprocess
- this._transformState = new TransformState(this);
+ self.maxLength = options.maxLength || Infinity
+ self.cache = options.cache || Object.create(null)
+ self.statCache = options.statCache || Object.create(null)
+ self.symlinks = options.symlinks || Object.create(null)
- // when the writable side finishes, then flush out anything remaining.
- var stream = this;
+ setupIgnores(self, options)
- // start out asking for a readable event once data is transformed.
- this._readableState.needReadable = true;
+ self.changedCwd = false
+ var cwd = process.cwd()
+ if (!ownProp(options, "cwd"))
+ self.cwd = cwd
+ else {
+ self.cwd = options.cwd
+ self.changedCwd = path.resolve(options.cwd) !== cwd
+ }
- // we have implemented the _read method, and done the other things
- // that Readable wants before the first _read call, so unset the
- // sync guard flag.
- this._readableState.sync = false;
+ self.root = options.root || path.resolve(self.cwd, "/")
+ self.root = path.resolve(self.root)
+ if (process.platform === "win32")
+ self.root = self.root.replace(/\\/g, "/")
- if (options) {
- if (typeof options.transform === 'function')
- this._transform = options.transform;
+ self.nomount = !!options.nomount
- if (typeof options.flush === 'function')
- this._flush = options.flush;
- }
+ // disable comments and negation unless the user explicitly
+ // passes in false as the option.
+ options.nonegate = options.nonegate === false ? false : true
+ options.nocomment = options.nocomment === false ? false : true
+ deprecationWarning(options)
- this.once('prefinish', function() {
- if (typeof this._flush === 'function')
- this._flush(function(er) {
- done(stream, er);
- });
- else
- done(stream);
- });
+ self.minimatch = new Minimatch(pattern, options)
+ self.options = self.minimatch.options
}
-Transform.prototype.push = function(chunk, encoding) {
- this._transformState.needTransform = false;
- return Duplex.prototype.push.call(this, chunk, encoding);
-};
-
-// This is the part where you do stuff!
-// override this function in implementation classes.
-// 'chunk' is an input chunk.
-//
-// Call `push(newChunk)` to pass along transformed output
-// to the readable side. You may call 'push' zero or more times.
-//
-// Call `cb(err)` when you are done with this chunk. If you pass
-// an error, then that'll put the hurt on the whole operation. If you
-// never call cb(), then you'll never get another chunk.
-Transform.prototype._transform = function(chunk, encoding, cb) {
- throw new Error('not implemented');
-};
+// TODO(isaacs): remove entirely in v6
+// exported to reset in tests
+exports.deprecationWarned
+function deprecationWarning(options) {
+ if (!options.nonegate || !options.nocomment) {
+ if (process.noDeprecation !== true && !exports.deprecationWarned) {
+ var msg = 'glob WARNING: comments and negation will be disabled in v6'
+ if (process.throwDeprecation)
+ throw new Error(msg)
+ else if (process.traceDeprecation)
+ console.trace(msg)
+ else
+ console.error(msg)
-Transform.prototype._write = function(chunk, encoding, cb) {
- var ts = this._transformState;
- ts.writecb = cb;
- ts.writechunk = chunk;
- ts.writeencoding = encoding;
- if (!ts.transforming) {
- var rs = this._readableState;
- if (ts.needTransform ||
- rs.needReadable ||
- rs.length < rs.highWaterMark)
- this._read(rs.highWaterMark);
+ exports.deprecationWarned = true
+ }
}
-};
+}
-// Doesn't matter what the args are here.
-// _transform does all the work.
-// That we got here means that the readable side wants more data.
-Transform.prototype._read = function(n) {
- var ts = this._transformState;
+function finish (self) {
+ var nou = self.nounique
+ var all = nou ? [] : Object.create(null)
- if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
- ts.transforming = true;
- this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
- } else {
- // mark that we need a transform, so that any data that comes in
- // will get processed, now that we've asked for it.
- ts.needTransform = true;
+ for (var i = 0, l = self.matches.length; i < l; i ++) {
+ var matches = self.matches[i]
+ if (!matches || Object.keys(matches).length === 0) {
+ if (self.nonull) {
+ // do like the shell, and spit out the literal glob
+ var literal = self.minimatch.globSet[i]
+ if (nou)
+ all.push(literal)
+ else
+ all[literal] = true
+ }
+ } else {
+ // had matches
+ var m = Object.keys(matches)
+ if (nou)
+ all.push.apply(all, m)
+ else
+ m.forEach(function (m) {
+ all[m] = true
+ })
+ }
}
-};
-
-function done(stream, er) {
- if (er)
- return stream.emit('error', er);
+ if (!nou)
+ all = Object.keys(all)
- // if there's nothing in the write buffer, then that means
- // that nothing more will ever be provided
- var ws = stream._writableState;
- var ts = stream._transformState;
+ if (!self.nosort)
+ all = all.sort(self.nocase ? alphasorti : alphasort)
- if (ws.length)
- throw new Error('calling transform done when ws.length != 0');
+ // at *some* point we statted all of these
+ if (self.mark) {
+ for (var i = 0; i < all.length; i++) {
+ all[i] = self._mark(all[i])
+ }
+ if (self.nodir) {
+ all = all.filter(function (e) {
+ return !(/\/$/.test(e))
+ })
+ }
+ }
- if (ts.transforming)
- throw new Error('calling transform done when still transforming');
+ if (self.ignore.length)
+ all = all.filter(function(m) {
+ return !isIgnored(self, m)
+ })
- return stream.push(null);
+ self.found = all
}
-},{"./_stream_duplex":70,"core-util-is":11,"inherits":18}],74:[function(require,module,exports){
-// A bit simpler than readable streams.
-// Implement an async ._write(chunk, cb), and it'll handle all
-// the drain event emission and buffering.
+function mark (self, p) {
+ var abs = makeAbs(self, p)
+ var c = self.cache[abs]
+ var m = p
+ if (c) {
+ var isDir = c === 'DIR' || Array.isArray(c)
+ var slash = p.slice(-1) === '/'
-'use strict';
+ if (isDir && !slash)
+ m += '/'
+ else if (!isDir && slash)
+ m = m.slice(0, -1)
-module.exports = Writable;
+ if (m !== p) {
+ var mabs = makeAbs(self, m)
+ self.statCache[mabs] = self.statCache[abs]
+ self.cache[mabs] = self.cache[abs]
+ }
+ }
-/**/
-var processNextTick = require('process-nextick-args');
-/**/
+ return m
+}
+
+// lotta situps...
+function makeAbs (self, f) {
+ var abs = f
+ if (f.charAt(0) === '/') {
+ abs = path.join(self.root, f)
+ } else if (isAbsolute(f) || f === '') {
+ abs = f
+ } else if (self.changedCwd) {
+ abs = path.resolve(self.cwd, f)
+ } else {
+ abs = path.resolve(f)
+ }
+ return abs
+}
-/**/
-var Buffer = require('buffer').Buffer;
-/**/
+// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
+// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
+function isIgnored (self, path) {
+ if (!self.ignore.length)
+ return false
-Writable.WritableState = WritableState;
+ return self.ignore.some(function(item) {
+ return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
+ })
+}
+function childrenIgnored (self, path) {
+ if (!self.ignore.length)
+ return false
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+ return self.ignore.some(function(item) {
+ return !!(item.gmatcher && item.gmatcher.match(path))
+ })
+}
+}).call(this,require('_process'))
+},{"_process":107,"minimatch":84,"path":104,"path-is-absolute":105}],30:[function(require,module,exports){
+(function (process){
+// Approach:
+//
+// 1. Get the minimatch set
+// 2. For each pattern in the set, PROCESS(pattern, false)
+// 3. Store matches per-set, then uniq them
+//
+// PROCESS(pattern, inGlobStar)
+// Get the first [n] items from pattern that are all strings
+// Join these together. This is PREFIX.
+// If there is no more remaining, then stat(PREFIX) and
+// add to matches if it succeeds. END.
+//
+// If inGlobStar and PREFIX is symlink and points to dir
+// set ENTRIES = []
+// else readdir(PREFIX) as ENTRIES
+// If fail, END
+//
+// with ENTRIES
+// If pattern[n] is GLOBSTAR
+// // handle the case where the globstar match is empty
+// // by pruning it out, and testing the resulting pattern
+// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
+// // handle other cases.
+// for ENTRY in ENTRIES (not dotfiles)
+// // attach globstar + tail onto the entry
+// // Mark that this entry is a globstar match
+// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
+//
+// else // not globstar
+// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
+// Test ENTRY against pattern[n]
+// If fails, continue
+// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
+//
+// Caveat:
+// Cache all stats and readdirs results to minimize syscall. Since all
+// we ever care about is existence and directory-ness, we can just keep
+// `true` for files, and [children,...] for directories, or `false` for
+// things that don't exist.
+module.exports = glob
-/**/
-var Stream;
-(function (){try{
- Stream = require('st' + 'ream');
-}catch(_){}finally{
- if (!Stream)
- Stream = require('events').EventEmitter;
-}}())
-/**/
+var fs = require('fs')
+var minimatch = require('minimatch')
+var Minimatch = minimatch.Minimatch
+var inherits = require('inherits')
+var EE = require('events').EventEmitter
+var path = require('path')
+var assert = require('assert')
+var isAbsolute = require('path-is-absolute')
+var globSync = require('./sync.js')
+var common = require('./common.js')
+var alphasort = common.alphasort
+var alphasorti = common.alphasorti
+var setopts = common.setopts
+var ownProp = common.ownProp
+var inflight = require('inflight')
+var util = require('util')
+var childrenIgnored = common.childrenIgnored
+var isIgnored = common.isIgnored
-var Buffer = require('buffer').Buffer;
+var once = require('once')
-util.inherits(Writable, Stream);
+function glob (pattern, options, cb) {
+ if (typeof options === 'function') cb = options, options = {}
+ if (!options) options = {}
-function nop() {}
+ if (options.sync) {
+ if (cb)
+ throw new TypeError('callback provided to sync glob')
+ return globSync(pattern, options)
+ }
-function WriteReq(chunk, encoding, cb) {
- this.chunk = chunk;
- this.encoding = encoding;
- this.callback = cb;
- this.next = null;
+ return new Glob(pattern, options, cb)
}
-function WritableState(options, stream) {
- var Duplex = require('./_stream_duplex');
+glob.sync = globSync
+var GlobSync = glob.GlobSync = globSync.GlobSync
- options = options || {};
+// old api surface
+glob.glob = glob
- // object stream flag to indicate whether or not this stream
- // contains buffers or objects.
- this.objectMode = !!options.objectMode;
+glob.hasMagic = function (pattern, options_) {
+ var options = util._extend({}, options_)
+ options.noprocess = true
- if (stream instanceof Duplex)
- this.objectMode = this.objectMode || !!options.writableObjectMode;
+ var g = new Glob(pattern, options)
+ var set = g.minimatch.set
+ if (set.length > 1)
+ return true
- // the point at which write() starts returning false
- // Note: 0 is a valid value, means that we always return false if
- // the entire buffer is not flushed immediately on write()
- var hwm = options.highWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
- this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
+ for (var j = 0; j < set[0].length; j++) {
+ if (typeof set[0][j] !== 'string')
+ return true
+ }
- // cast to ints.
- this.highWaterMark = ~~this.highWaterMark;
+ return false
+}
- this.needDrain = false;
- // at the start of calling end()
- this.ending = false;
- // when end() has been called, and returned
- this.ended = false;
- // when 'finish' is emitted
- this.finished = false;
+glob.Glob = Glob
+inherits(Glob, EE)
+function Glob (pattern, options, cb) {
+ if (typeof options === 'function') {
+ cb = options
+ options = null
+ }
- // should we decode strings into buffers before passing to _write?
- // this is here so that some node-core streams can optimize string
- // handling at a lower level.
- var noDecode = options.decodeStrings === false;
- this.decodeStrings = !noDecode;
+ if (options && options.sync) {
+ if (cb)
+ throw new TypeError('callback provided to sync glob')
+ return new GlobSync(pattern, options)
+ }
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
+ if (!(this instanceof Glob))
+ return new Glob(pattern, options, cb)
- // not an actual buffer we keep track of, but a measurement
- // of how much we're waiting to get pushed to some underlying
- // socket or file.
- this.length = 0;
+ setopts(this, pattern, options)
+ this._didRealPath = false
- // a flag to see when we're in the middle of a write.
- this.writing = false;
+ // process each pattern in the minimatch set
+ var n = this.minimatch.set.length
- // when true all writes will be buffered until .uncork() call
- this.corked = 0;
+ // The matches are stored as {: true,...} so that
+ // duplicates are automagically pruned.
+ // Later, we do an Object.keys() on these.
+ // Keep them as a list so we can fill in when nonull is set.
+ this.matches = new Array(n)
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
+ if (typeof cb === 'function') {
+ cb = once(cb)
+ this.on('error', cb)
+ this.on('end', function (matches) {
+ cb(null, matches)
+ })
+ }
- // a flag to know if we're processing previously buffered items, which
- // may call the _write() callback in the same tick, so that we don't
- // end up in an overlapped onwrite situation.
- this.bufferProcessing = false;
+ var self = this
+ var n = this.minimatch.set.length
+ this._processing = 0
+ this.matches = new Array(n)
- // the callback that's passed to _write(chunk,cb)
- this.onwrite = function(er) {
- onwrite(stream, er);
- };
+ this._emitQueue = []
+ this._processQueue = []
+ this.paused = false
- // the callback that the user supplies to write(chunk,encoding,cb)
- this.writecb = null;
+ if (this.noprocess)
+ return this
- // the amount that is being written when _write is called.
- this.writelen = 0;
+ if (n === 0)
+ return done()
- this.bufferedRequest = null;
- this.lastBufferedRequest = null;
+ for (var i = 0; i < n; i ++) {
+ this._process(this.minimatch.set[i], i, false, done)
+ }
- // number of pending user-supplied write callbacks
- // this must be 0 before 'finish' can be emitted
- this.pendingcb = 0;
+ function done () {
+ --self._processing
+ if (self._processing <= 0)
+ self._finish()
+ }
+}
- // emit prefinish if the only thing we're waiting for is _write cbs
- // This is relevant for synchronous Transform streams
- this.prefinished = false;
+Glob.prototype._finish = function () {
+ assert(this instanceof Glob)
+ if (this.aborted)
+ return
+
+ if (this.realpath && !this._didRealpath)
+ return this._realpath()
- // True if the error was already emitted and should not be thrown again
- this.errorEmitted = false;
+ common.finish(this)
+ this.emit('end', this.found)
}
-WritableState.prototype.getBuffer = function writableStateGetBuffer() {
- var current = this.bufferedRequest;
- var out = [];
- while (current) {
- out.push(current);
- current = current.next;
- }
- return out;
-};
+Glob.prototype._realpath = function () {
+ if (this._didRealpath)
+ return
-(function (){try {
-Object.defineProperty(WritableState.prototype, 'buffer', {
- get: require('util-deprecate')(function() {
- return this.getBuffer();
- }, '_writableState.buffer is deprecated. Use ' +
- '_writableState.getBuffer() instead.')
-});
-}catch(_){}}());
+ this._didRealpath = true
+ var n = this.matches.length
+ if (n === 0)
+ return this._finish()
-function Writable(options) {
- var Duplex = require('./_stream_duplex');
+ var self = this
+ for (var i = 0; i < this.matches.length; i++)
+ this._realpathSet(i, next)
- // Writable ctor is applied to Duplexes, though they're not
- // instanceof Writable, they're instanceof Readable.
- if (!(this instanceof Writable) && !(this instanceof Duplex))
- return new Writable(options);
+ function next () {
+ if (--n === 0)
+ self._finish()
+ }
+}
- this._writableState = new WritableState(options, this);
+Glob.prototype._realpathSet = function (index, cb) {
+ var matchset = this.matches[index]
+ if (!matchset)
+ return cb()
- // legacy.
- this.writable = true;
+ var found = Object.keys(matchset)
+ var self = this
+ var n = found.length
- if (options) {
- if (typeof options.write === 'function')
- this._write = options.write;
+ if (n === 0)
+ return cb()
- if (typeof options.writev === 'function')
- this._writev = options.writev;
- }
+ var set = this.matches[index] = Object.create(null)
+ found.forEach(function (p, i) {
+ // If there's a problem with the stat, then it means that
+ // one or more of the links in the realpath couldn't be
+ // resolved. just return the abs value in that case.
+ p = self._makeAbs(p)
+ fs.realpath(p, self.realpathCache, function (er, real) {
+ if (!er)
+ set[real] = true
+ else if (er.syscall === 'stat')
+ set[p] = true
+ else
+ self.emit('error', er) // srsly wtf right here
- Stream.call(this);
+ if (--n === 0) {
+ self.matches[index] = set
+ cb()
+ }
+ })
+ })
}
-// Otherwise people can pipe Writable streams, which is just wrong.
-Writable.prototype.pipe = function() {
- this.emit('error', new Error('Cannot pipe. Not readable.'));
-};
+Glob.prototype._mark = function (p) {
+ return common.mark(this, p)
+}
+Glob.prototype._makeAbs = function (f) {
+ return common.makeAbs(this, f)
+}
-function writeAfterEnd(stream, cb) {
- var er = new Error('write after end');
- // TODO: defer error events consistently everywhere, not just the cb
- stream.emit('error', er);
- processNextTick(cb, er);
+Glob.prototype.abort = function () {
+ this.aborted = true
+ this.emit('abort')
}
-// If we get something that is not a buffer, string, null, or undefined,
-// and we're not in objectMode, then that's an error.
-// Otherwise stream chunks are all considered to be of length=1, and the
-// watermarks determine how many objects to keep in the buffer, rather than
-// how many bytes or characters.
-function validChunk(stream, state, chunk, cb) {
- var valid = true;
+Glob.prototype.pause = function () {
+ if (!this.paused) {
+ this.paused = true
+ this.emit('pause')
+ }
+}
- if (!(Buffer.isBuffer(chunk)) &&
- typeof chunk !== 'string' &&
- chunk !== null &&
- chunk !== undefined &&
- !state.objectMode) {
- var er = new TypeError('Invalid non-string/buffer chunk');
- stream.emit('error', er);
- processNextTick(cb, er);
- valid = false;
+Glob.prototype.resume = function () {
+ if (this.paused) {
+ this.emit('resume')
+ this.paused = false
+ if (this._emitQueue.length) {
+ var eq = this._emitQueue.slice(0)
+ this._emitQueue.length = 0
+ for (var i = 0; i < eq.length; i ++) {
+ var e = eq[i]
+ this._emitMatch(e[0], e[1])
+ }
+ }
+ if (this._processQueue.length) {
+ var pq = this._processQueue.slice(0)
+ this._processQueue.length = 0
+ for (var i = 0; i < pq.length; i ++) {
+ var p = pq[i]
+ this._processing--
+ this._process(p[0], p[1], p[2], p[3])
+ }
+ }
}
- return valid;
}
-Writable.prototype.write = function(chunk, encoding, cb) {
- var state = this._writableState;
- var ret = false;
+Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
+ assert(this instanceof Glob)
+ assert(typeof cb === 'function')
- if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
+ if (this.aborted)
+ return
- if (Buffer.isBuffer(chunk))
- encoding = 'buffer';
- else if (!encoding)
- encoding = state.defaultEncoding;
+ this._processing++
+ if (this.paused) {
+ this._processQueue.push([pattern, index, inGlobStar, cb])
+ return
+ }
- if (typeof cb !== 'function')
- cb = nop;
+ //console.error('PROCESS %d', this._processing, pattern)
- if (state.ended)
- writeAfterEnd(this, cb);
- else if (validChunk(this, state, chunk, cb)) {
- state.pendingcb++;
- ret = writeOrBuffer(this, state, chunk, encoding, cb);
+ // Get the first [n] parts of pattern that are all strings.
+ var n = 0
+ while (typeof pattern[n] === 'string') {
+ n ++
}
+ // now n is the index of the first one that is *not* a string.
- return ret;
-};
+ // see if there's anything else
+ var prefix
+ switch (n) {
+ // if not, then this is rather simple
+ case pattern.length:
+ this._processSimple(pattern.join('/'), index, cb)
+ return
-Writable.prototype.cork = function() {
- var state = this._writableState;
+ case 0:
+ // pattern *starts* with some non-trivial item.
+ // going to readdir(cwd), but not include the prefix in matches.
+ prefix = null
+ break
- state.corked++;
-};
+ default:
+ // pattern has some string bits in the front.
+ // whatever it starts with, whether that's 'absolute' like /foo/bar,
+ // or 'relative' like '../baz'
+ prefix = pattern.slice(0, n).join('/')
+ break
+ }
-Writable.prototype.uncork = function() {
- var state = this._writableState;
+ var remain = pattern.slice(n)
- if (state.corked) {
- state.corked--;
+ // get the list of entries.
+ var read
+ if (prefix === null)
+ read = '.'
+ else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
+ if (!prefix || !isAbsolute(prefix))
+ prefix = '/' + prefix
+ read = prefix
+ } else
+ read = prefix
- if (!state.writing &&
- !state.corked &&
- !state.finished &&
- !state.bufferProcessing &&
- state.bufferedRequest)
- clearBuffer(this, state);
- }
-};
+ var abs = this._makeAbs(read)
-Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
- // node::ParseEncoding() requires lower case.
- if (typeof encoding === 'string')
- encoding = encoding.toLowerCase();
- if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64',
-'ucs2', 'ucs-2','utf16le', 'utf-16le', 'raw']
-.indexOf((encoding + '').toLowerCase()) > -1))
- throw new TypeError('Unknown encoding: ' + encoding);
- this._writableState.defaultEncoding = encoding;
-};
+ //if ignored, skip _processing
+ if (childrenIgnored(this, read))
+ return cb()
-function decodeChunk(state, chunk, encoding) {
- if (!state.objectMode &&
- state.decodeStrings !== false &&
- typeof chunk === 'string') {
- chunk = new Buffer(chunk, encoding);
- }
- return chunk;
+ var isGlobStar = remain[0] === minimatch.GLOBSTAR
+ if (isGlobStar)
+ this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
+ else
+ this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
}
-// if we're already writing something, then just put this
-// in the queue, and wait our turn. Otherwise, call _write
-// If we return false, then we need a drain event, so set that flag.
-function writeOrBuffer(stream, state, chunk, encoding, cb) {
- chunk = decodeChunk(state, chunk, encoding);
+Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
+ var self = this
+ this._readdir(abs, inGlobStar, function (er, entries) {
+ return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
+ })
+}
- if (Buffer.isBuffer(chunk))
- encoding = 'buffer';
- var len = state.objectMode ? 1 : chunk.length;
+Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
- state.length += len;
+ // if the abs isn't a dir, then nothing can match!
+ if (!entries)
+ return cb()
- var ret = state.length < state.highWaterMark;
- // we must ensure that previous needDrain will not be reset to false.
- if (!ret)
- state.needDrain = true;
+ // It will only match dot entries if it starts with a dot, or if
+ // dot is set. Stuff like @(.foo|.bar) isn't allowed.
+ var pn = remain[0]
+ var negate = !!this.minimatch.negate
+ var rawGlob = pn._glob
+ var dotOk = this.dot || rawGlob.charAt(0) === '.'
- if (state.writing || state.corked) {
- var last = state.lastBufferedRequest;
- state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
- if (last) {
- last.next = state.lastBufferedRequest;
- } else {
- state.bufferedRequest = state.lastBufferedRequest;
+ var matchedEntries = []
+ for (var i = 0; i < entries.length; i++) {
+ var e = entries[i]
+ if (e.charAt(0) !== '.' || dotOk) {
+ var m
+ if (negate && !prefix) {
+ m = !e.match(pn)
+ } else {
+ m = e.match(pn)
+ }
+ if (m)
+ matchedEntries.push(e)
}
- } else {
- doWrite(stream, state, false, len, chunk, encoding, cb);
}
- return ret;
-}
-
-function doWrite(stream, state, writev, len, chunk, encoding, cb) {
- state.writelen = len;
- state.writecb = cb;
- state.writing = true;
- state.sync = true;
- if (writev)
- stream._writev(chunk, state.onwrite);
- else
- stream._write(chunk, encoding, state.onwrite);
- state.sync = false;
-}
-
-function onwriteError(stream, state, sync, er, cb) {
- --state.pendingcb;
- if (sync)
- processNextTick(cb, er);
- else
- cb(er);
-
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
-}
+ //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
-function onwriteStateUpdate(state) {
- state.writing = false;
- state.writecb = null;
- state.length -= state.writelen;
- state.writelen = 0;
-}
+ var len = matchedEntries.length
+ // If there are no matched entries, then nothing matches.
+ if (len === 0)
+ return cb()
-function onwrite(stream, er) {
- var state = stream._writableState;
- var sync = state.sync;
- var cb = state.writecb;
+ // if this is the last remaining pattern bit, then no need for
+ // an additional stat *unless* the user has specified mark or
+ // stat explicitly. We know they exist, since readdir returned
+ // them.
- onwriteStateUpdate(state);
+ if (remain.length === 1 && !this.mark && !this.stat) {
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null)
- if (er)
- onwriteError(stream, state, sync, er, cb);
- else {
- // Check if we're actually ready to finish, but don't emit yet
- var finished = needFinish(state);
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i]
+ if (prefix) {
+ if (prefix !== '/')
+ e = prefix + '/' + e
+ else
+ e = prefix + e
+ }
- if (!finished &&
- !state.corked &&
- !state.bufferProcessing &&
- state.bufferedRequest) {
- clearBuffer(stream, state);
+ if (e.charAt(0) === '/' && !this.nomount) {
+ e = path.join(this.root, e)
+ }
+ this._emitMatch(index, e)
}
+ // This was the last one, and no stats were needed
+ return cb()
+ }
- if (sync) {
- processNextTick(afterWrite, stream, state, finished, cb);
- } else {
- afterWrite(stream, state, finished, cb);
+ // now test all matched entries as stand-ins for that part
+ // of the pattern.
+ remain.shift()
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i]
+ var newPattern
+ if (prefix) {
+ if (prefix !== '/')
+ e = prefix + '/' + e
+ else
+ e = prefix + e
}
+ this._process([e].concat(remain), index, inGlobStar, cb)
}
+ cb()
}
-function afterWrite(stream, state, finished, cb) {
- if (!finished)
- onwriteDrain(stream, state);
- state.pendingcb--;
- cb();
- finishMaybe(stream, state);
-}
+Glob.prototype._emitMatch = function (index, e) {
+ if (this.aborted)
+ return
-// Must force callback to be called on nextTick, so that we don't
-// emit 'drain' before the write() consumer gets the 'false' return
-// value, and has a chance to attach a 'drain' listener.
-function onwriteDrain(stream, state) {
- if (state.length === 0 && state.needDrain) {
- state.needDrain = false;
- stream.emit('drain');
- }
-}
+ if (this.matches[index][e])
+ return
+ if (isIgnored(this, e))
+ return
-// if there's something in the buffer waiting, then process it
-function clearBuffer(stream, state) {
- state.bufferProcessing = true;
- var entry = state.bufferedRequest;
+ if (this.paused) {
+ this._emitQueue.push([index, e])
+ return
+ }
- if (stream._writev && entry && entry.next) {
- // Fast case, write everything using _writev()
- var buffer = [];
- var cbs = [];
- while (entry) {
- cbs.push(entry.callback);
- buffer.push(entry);
- entry = entry.next;
- }
+ var abs = this._makeAbs(e)
- // count the one we are adding, as well.
- // TODO(isaacs) clean this up
- state.pendingcb++;
- state.lastBufferedRequest = null;
- doWrite(stream, state, true, state.length, buffer, '', function(err) {
- for (var i = 0; i < cbs.length; i++) {
- state.pendingcb--;
- cbs[i](err);
- }
- });
+ if (this.nodir) {
+ var c = this.cache[abs]
+ if (c === 'DIR' || Array.isArray(c))
+ return
+ }
- // Clear buffer
- } else {
- // Slow case, write chunks one-by-one
- while (entry) {
- var chunk = entry.chunk;
- var encoding = entry.encoding;
- var cb = entry.callback;
- var len = state.objectMode ? 1 : chunk.length;
+ if (this.mark)
+ e = this._mark(e)
- doWrite(stream, state, false, len, chunk, encoding, cb);
- entry = entry.next;
- // if we didn't call the onwrite immediately, then
- // it means that we need to wait until it does.
- // also, that means that the chunk and cb are currently
- // being processed, so move the buffer counter past them.
- if (state.writing) {
- break;
- }
- }
+ this.matches[index][e] = true
- if (entry === null)
- state.lastBufferedRequest = null;
- }
- state.bufferedRequest = entry;
- state.bufferProcessing = false;
+ var st = this.statCache[abs]
+ if (st)
+ this.emit('stat', e, st)
+
+ this.emit('match', e)
}
-Writable.prototype._write = function(chunk, encoding, cb) {
- cb(new Error('not implemented'));
-};
+Glob.prototype._readdirInGlobStar = function (abs, cb) {
+ if (this.aborted)
+ return
-Writable.prototype._writev = null;
+ // follow all symlinked directories forever
+ // just proceed as if this is a non-globstar situation
+ if (this.follow)
+ return this._readdir(abs, false, cb)
-Writable.prototype.end = function(chunk, encoding, cb) {
- var state = this._writableState;
+ var lstatkey = 'lstat\0' + abs
+ var self = this
+ var lstatcb = inflight(lstatkey, lstatcb_)
- if (typeof chunk === 'function') {
- cb = chunk;
- chunk = null;
- encoding = null;
- } else if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
+ if (lstatcb)
+ fs.lstat(abs, lstatcb)
+
+ function lstatcb_ (er, lstat) {
+ if (er)
+ return cb()
+
+ var isSym = lstat.isSymbolicLink()
+ self.symlinks[abs] = isSym
+
+ // If it's not a symlink or a dir, then it's definitely a regular file.
+ // don't bother doing a readdir in that case.
+ if (!isSym && !lstat.isDirectory()) {
+ self.cache[abs] = 'FILE'
+ cb()
+ } else
+ self._readdir(abs, false, cb)
}
+}
- if (chunk !== null && chunk !== undefined)
- this.write(chunk, encoding);
+Glob.prototype._readdir = function (abs, inGlobStar, cb) {
+ if (this.aborted)
+ return
- // .end() fully uncorks
- if (state.corked) {
- state.corked = 1;
- this.uncork();
- }
+ cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
+ if (!cb)
+ return
- // ignore unnecessary end() calls.
- if (!state.ending && !state.finished)
- endWritable(this, state, cb);
-};
+ //console.error('RD %j %j', +inGlobStar, abs)
+ if (inGlobStar && !ownProp(this.symlinks, abs))
+ return this._readdirInGlobStar(abs, cb)
+ if (ownProp(this.cache, abs)) {
+ var c = this.cache[abs]
+ if (!c || c === 'FILE')
+ return cb()
-function needFinish(state) {
- return (state.ending &&
- state.length === 0 &&
- state.bufferedRequest === null &&
- !state.finished &&
- !state.writing);
+ if (Array.isArray(c))
+ return cb(null, c)
+ }
+
+ var self = this
+ fs.readdir(abs, readdirCb(this, abs, cb))
}
-function prefinish(stream, state) {
- if (!state.prefinished) {
- state.prefinished = true;
- stream.emit('prefinish');
+function readdirCb (self, abs, cb) {
+ return function (er, entries) {
+ if (er)
+ self._readdirError(abs, er, cb)
+ else
+ self._readdirEntries(abs, entries, cb)
}
}
-function finishMaybe(stream, state) {
- var need = needFinish(state);
- if (need) {
- if (state.pendingcb === 0) {
- prefinish(stream, state);
- state.finished = true;
- stream.emit('finish');
- } else {
- prefinish(stream, state);
+Glob.prototype._readdirEntries = function (abs, entries, cb) {
+ if (this.aborted)
+ return
+
+ // if we haven't asked to stat everything, then just
+ // assume that everything in there exists, so we can avoid
+ // having to stat it a second time.
+ if (!this.mark && !this.stat) {
+ for (var i = 0; i < entries.length; i ++) {
+ var e = entries[i]
+ if (abs === '/')
+ e = abs + e
+ else
+ e = abs + '/' + e
+ this.cache[e] = true
}
}
- return need;
+
+ this.cache[abs] = entries
+ return cb(null, entries)
}
-function endWritable(stream, state, cb) {
- state.ending = true;
- finishMaybe(stream, state);
- if (cb) {
- if (state.finished)
- processNextTick(cb);
- else
- stream.once('finish', cb);
+Glob.prototype._readdirError = function (f, er, cb) {
+ if (this.aborted)
+ return
+
+ // handle errors, and cache the information
+ switch (er.code) {
+ case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
+ case 'ENOTDIR': // totally normal. means it *does* exist.
+ this.cache[this._makeAbs(f)] = 'FILE'
+ break
+
+ case 'ENOENT': // not terribly unusual
+ case 'ELOOP':
+ case 'ENAMETOOLONG':
+ case 'UNKNOWN':
+ this.cache[this._makeAbs(f)] = false
+ break
+
+ default: // some unusual error. Treat as failure.
+ this.cache[this._makeAbs(f)] = false
+ if (this.strict) {
+ this.emit('error', er)
+ // If the error is handled, then we abort
+ // if not, we threw out of here
+ this.abort()
+ }
+ if (!this.silent)
+ console.error('glob error', er)
+ break
}
- state.ended = true;
+
+ return cb()
}
-},{"./_stream_duplex":70,"buffer":6,"core-util-is":11,"events":14,"inherits":18,"process-nextick-args":63,"util-deprecate":88}],75:[function(require,module,exports){
-module.exports = require("./lib/_stream_passthrough.js")
+Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
+ var self = this
+ this._readdir(abs, inGlobStar, function (er, entries) {
+ self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
+ })
+}
-},{"./lib/_stream_passthrough.js":71}],76:[function(require,module,exports){
-var Stream = (function (){
- try {
- return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
- } catch(_){}
-}());
-exports = module.exports = require('./lib/_stream_readable.js');
-exports.Stream = Stream || exports;
-exports.Readable = exports;
-exports.Writable = require('./lib/_stream_writable.js');
-exports.Duplex = require('./lib/_stream_duplex.js');
-exports.Transform = require('./lib/_stream_transform.js');
-exports.PassThrough = require('./lib/_stream_passthrough.js');
-},{"./lib/_stream_duplex.js":70,"./lib/_stream_passthrough.js":71,"./lib/_stream_readable.js":72,"./lib/_stream_transform.js":73,"./lib/_stream_writable.js":74}],77:[function(require,module,exports){
-module.exports = require("./lib/_stream_transform.js")
+Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
+ //console.error('pgs2', prefix, remain[0], entries)
-},{"./lib/_stream_transform.js":73}],78:[function(require,module,exports){
-module.exports = require("./lib/_stream_writable.js")
+ // no entries means not a dir, so it can never have matches
+ // foo.txt/** doesn't match foo.txt
+ if (!entries)
+ return cb()
-},{"./lib/_stream_writable.js":74}],79:[function(require,module,exports){
-var path = require('path');
+ // test without the globstar, and with every child both below
+ // and replacing the globstar.
+ var remainWithoutGlobStar = remain.slice(1)
+ var gspref = prefix ? [ prefix ] : []
+ var noGlobStar = gspref.concat(remainWithoutGlobStar)
-module.exports = function(npath, ext) {
- if (typeof npath !== 'string') return npath;
- if (npath.length === 0) return npath;
+ // the noGlobStar pattern exits the inGlobStar state
+ this._process(noGlobStar, index, false, cb)
- var nFileName = path.basename(npath, path.extname(npath))+ext;
- return path.join(path.dirname(npath), nFileName);
-};
-},{"path":62}],80:[function(require,module,exports){
-var Readable = require('stream').Readable;
-var PassThrough = require('stream').PassThrough;
+ var isSym = this.symlinks[abs]
+ var len = entries.length
-function SandwichStream(options) {
- Readable.call(this, options);
- options = options || {};
- this._streamsActive = false;
- this._streamsAdded = false;
- this._streams = [];
- this._currentStream = undefined;
- this._errorsEmitted = false;
+ // If it's a symlink, and we're in a globstar, then stop
+ if (isSym && inGlobStar)
+ return cb()
- if (options.head) {
- this._head = options.head;
- }
- if (options.tail) {
- this._tail = options.tail;
- }
- if (options.separator) {
- this._separator = options.separator;
+ for (var i = 0; i < len; i++) {
+ var e = entries[i]
+ if (e.charAt(0) === '.' && !this.dot)
+ continue
+
+ // these two cases enter the inGlobStar state
+ var instead = gspref.concat(entries[i], remainWithoutGlobStar)
+ this._process(instead, index, true, cb)
+
+ var below = gspref.concat(entries[i], remain)
+ this._process(below, index, true, cb)
}
+
+ cb()
}
-SandwichStream.prototype = Object.create(Readable.prototype, {
- constructor: SandwichStream
-});
+Glob.prototype._processSimple = function (prefix, index, cb) {
+ // XXX review this. Shouldn't it be doing the mounting etc
+ // before doing stat? kinda weird?
+ var self = this
+ this._stat(prefix, function (er, exists) {
+ self._processSimple2(prefix, index, er, exists, cb)
+ })
+}
+Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
-SandwichStream.prototype._read = function () {
- if (!this._streamsActive) {
- this._streamsActive = true;
- this._pushHead();
- this._streamNextStream();
- }
-};
+ //console.error('ps2', prefix, exists)
-SandwichStream.prototype.add = function (newStream) {
- if (!this._streamsActive) {
- this._streamsAdded = true;
- this._streams.push(newStream);
- newStream.on('error', this._substreamOnError.bind(this));
- }
- else {
- throw new Error('SandwichStream error adding new stream while streaming');
- }
-};
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null)
-SandwichStream.prototype._substreamOnError = function (error) {
- this._errorsEmitted = true;
- this.emit('error', error);
-};
+ // If it doesn't exist, then just mark the lack of results
+ if (!exists)
+ return cb()
-SandwichStream.prototype._pushHead = function () {
- if (this._head) {
- this.push(this._head);
+ if (prefix && isAbsolute(prefix) && !this.nomount) {
+ var trail = /[\/\\]$/.test(prefix)
+ if (prefix.charAt(0) === '/') {
+ prefix = path.join(this.root, prefix)
+ } else {
+ prefix = path.resolve(this.root, prefix)
+ if (trail)
+ prefix += '/'
+ }
}
-};
-SandwichStream.prototype._streamNextStream = function () {
- if (this._nextStream()) {
- this._bindCurrentStreamEvents();
- }
- else {
- this._pushTail();
- this.push(null);
- }
-};
+ if (process.platform === 'win32')
+ prefix = prefix.replace(/\\/g, '/')
+
+ // Mark this as a match
+ this._emitMatch(index, prefix)
+ cb()
+}
+
+// Returns either 'DIR', 'FILE', or false
+Glob.prototype._stat = function (f, cb) {
+ var abs = this._makeAbs(f)
+ var needDir = f.slice(-1) === '/'
-SandwichStream.prototype._nextStream = function () {
- this._currentStream = this._streams.shift();
- return this._currentStream !== undefined;
-};
+ if (f.length > this.maxLength)
+ return cb()
-SandwichStream.prototype._bindCurrentStreamEvents = function () {
- this._currentStream.on('readable', this._currentStreamOnReadable.bind(this));
- this._currentStream.on('end', this._currentStreamOnEnd.bind(this));
-};
+ if (!this.stat && ownProp(this.cache, abs)) {
+ var c = this.cache[abs]
-SandwichStream.prototype._currentStreamOnReadable = function () {
- this.push(this._currentStream.read() || '');
-};
+ if (Array.isArray(c))
+ c = 'DIR'
-SandwichStream.prototype._currentStreamOnEnd = function () {
- this._pushSeparator();
- this._streamNextStream();
-};
+ // It exists, but maybe not how we need it
+ if (!needDir || c === 'DIR')
+ return cb(null, c)
-SandwichStream.prototype._pushSeparator = function () {
- if (this._streams.length > 0 && this._separator) {
- this.push(this._separator);
+ if (needDir && c === 'FILE')
+ return cb()
+
+ // otherwise we have to stat, because maybe c=true
+ // if we know it exists, but not what it is.
}
-};
-SandwichStream.prototype._pushTail = function () {
- if (this._tail) {
- this.push(this._tail);
+ var exists
+ var stat = this.statCache[abs]
+ if (stat !== undefined) {
+ if (stat === false)
+ return cb(null, stat)
+ else {
+ var type = stat.isDirectory() ? 'DIR' : 'FILE'
+ if (needDir && type === 'FILE')
+ return cb()
+ else
+ return cb(null, type, stat)
+ }
}
-};
-function sandwichStream(options) {
- var stream = new SandwichStream(options);
- return stream;
-}
+ var self = this
+ var statcb = inflight('stat\0' + abs, lstatcb_)
+ if (statcb)
+ fs.lstat(abs, statcb)
-sandwichStream.SandwichStream = SandwichStream;
+ function lstatcb_ (er, lstat) {
+ if (lstat && lstat.isSymbolicLink()) {
+ // If it's a symlink, then treat it as the target, unless
+ // the target does not exist, then treat it as a file.
+ return fs.stat(abs, function (er, stat) {
+ if (er)
+ self._stat2(f, abs, null, lstat, cb)
+ else
+ self._stat2(f, abs, er, stat, cb)
+ })
+ } else {
+ self._stat2(f, abs, er, lstat, cb)
+ }
+ }
+}
-module.exports = sandwichStream;
+Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
+ if (er) {
+ this.statCache[abs] = false
+ return cb()
+ }
-},{"stream":81}],81:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+ var needDir = f.slice(-1) === '/'
+ this.statCache[abs] = stat
-module.exports = Stream;
+ if (abs.slice(-1) === '/' && !stat.isDirectory())
+ return cb(null, false, stat)
-var EE = require('events').EventEmitter;
-var inherits = require('inherits');
+ var c = stat.isDirectory() ? 'DIR' : 'FILE'
+ this.cache[abs] = this.cache[abs] || c
-inherits(Stream, EE);
-Stream.Readable = require('readable-stream/readable.js');
-Stream.Writable = require('readable-stream/writable.js');
-Stream.Duplex = require('readable-stream/duplex.js');
-Stream.Transform = require('readable-stream/transform.js');
-Stream.PassThrough = require('readable-stream/passthrough.js');
+ if (needDir && c !== 'DIR')
+ return cb()
-// Backwards-compat with node 0.4.x
-Stream.Stream = Stream;
+ return cb(null, c, stat)
+}
+}).call(this,require('_process'))
+},{"./common.js":29,"./sync.js":31,"_process":107,"assert":1,"events":18,"fs":6,"inflight":46,"inherits":47,"minimatch":84,"once":95,"path":104,"path-is-absolute":105,"util":138}],31:[function(require,module,exports){
+(function (process){
+module.exports = globSync
+globSync.GlobSync = GlobSync
+var fs = require('fs')
+var minimatch = require('minimatch')
+var Minimatch = minimatch.Minimatch
+var Glob = require('./glob.js').Glob
+var util = require('util')
+var path = require('path')
+var assert = require('assert')
+var isAbsolute = require('path-is-absolute')
+var common = require('./common.js')
+var alphasort = common.alphasort
+var alphasorti = common.alphasorti
+var setopts = common.setopts
+var ownProp = common.ownProp
+var childrenIgnored = common.childrenIgnored
-// old-style streams. Note that the pipe method (the only relevant
-// part of this class) is overridden in the Readable class.
+function globSync (pattern, options) {
+ if (typeof options === 'function' || arguments.length === 3)
+ throw new TypeError('callback provided to sync glob\n'+
+ 'See: https://github.com/isaacs/node-glob/issues/167')
-function Stream() {
- EE.call(this);
+ return new GlobSync(pattern, options).found
}
-Stream.prototype.pipe = function(dest, options) {
- var source = this;
+function GlobSync (pattern, options) {
+ if (!pattern)
+ throw new Error('must provide pattern')
- function ondata(chunk) {
- if (dest.writable) {
- if (false === dest.write(chunk) && source.pause) {
- source.pause();
- }
- }
- }
+ if (typeof options === 'function' || arguments.length === 3)
+ throw new TypeError('callback provided to sync glob\n'+
+ 'See: https://github.com/isaacs/node-glob/issues/167')
- source.on('data', ondata);
+ if (!(this instanceof GlobSync))
+ return new GlobSync(pattern, options)
- function ondrain() {
- if (source.readable && source.resume) {
- source.resume();
- }
- }
+ setopts(this, pattern, options)
- dest.on('drain', ondrain);
+ if (this.noprocess)
+ return this
- // If the 'end' option is not supplied, dest.end() will be called when
- // source gets the 'end' or 'close' events. Only dest.end() once.
- if (!dest._isStdio && (!options || options.end !== false)) {
- source.on('end', onend);
- source.on('close', onclose);
+ var n = this.minimatch.set.length
+ this.matches = new Array(n)
+ for (var i = 0; i < n; i ++) {
+ this._process(this.minimatch.set[i], i, false)
}
+ this._finish()
+}
- var didOnEnd = false;
- function onend() {
- if (didOnEnd) return;
- didOnEnd = true;
+GlobSync.prototype._finish = function () {
+ assert(this instanceof GlobSync)
+ if (this.realpath) {
+ var self = this
+ this.matches.forEach(function (matchset, index) {
+ var set = self.matches[index] = Object.create(null)
+ for (var p in matchset) {
+ try {
+ p = self._makeAbs(p)
+ var real = fs.realpathSync(p, self.realpathCache)
+ set[real] = true
+ } catch (er) {
+ if (er.syscall === 'stat')
+ set[self._makeAbs(p)] = true
+ else
+ throw er
+ }
+ }
+ })
+ }
+ common.finish(this)
+}
- dest.end();
+
+GlobSync.prototype._process = function (pattern, index, inGlobStar) {
+ assert(this instanceof GlobSync)
+
+ // Get the first [n] parts of pattern that are all strings.
+ var n = 0
+ while (typeof pattern[n] === 'string') {
+ n ++
}
+ // now n is the index of the first one that is *not* a string.
+ // See if there's anything else
+ var prefix
+ switch (n) {
+ // if not, then this is rather simple
+ case pattern.length:
+ this._processSimple(pattern.join('/'), index)
+ return
- function onclose() {
- if (didOnEnd) return;
- didOnEnd = true;
+ case 0:
+ // pattern *starts* with some non-trivial item.
+ // going to readdir(cwd), but not include the prefix in matches.
+ prefix = null
+ break
- if (typeof dest.destroy === 'function') dest.destroy();
+ default:
+ // pattern has some string bits in the front.
+ // whatever it starts with, whether that's 'absolute' like /foo/bar,
+ // or 'relative' like '../baz'
+ prefix = pattern.slice(0, n).join('/')
+ break
}
- // don't leave dangling pipes when there are errors.
- function onerror(er) {
- cleanup();
- if (EE.listenerCount(this, 'error') === 0) {
- throw er; // Unhandled stream error in pipe.
- }
- }
+ var remain = pattern.slice(n)
- source.on('error', onerror);
- dest.on('error', onerror);
+ // get the list of entries.
+ var read
+ if (prefix === null)
+ read = '.'
+ else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
+ if (!prefix || !isAbsolute(prefix))
+ prefix = '/' + prefix
+ read = prefix
+ } else
+ read = prefix
- // remove all the event listeners that were added.
- function cleanup() {
- source.removeListener('data', ondata);
- dest.removeListener('drain', ondrain);
+ var abs = this._makeAbs(read)
- source.removeListener('end', onend);
- source.removeListener('close', onclose);
+ //if ignored, skip processing
+ if (childrenIgnored(this, read))
+ return
- source.removeListener('error', onerror);
- dest.removeListener('error', onerror);
+ var isGlobStar = remain[0] === minimatch.GLOBSTAR
+ if (isGlobStar)
+ this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
+ else
+ this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
+}
- source.removeListener('end', cleanup);
- source.removeListener('close', cleanup);
- dest.removeListener('close', cleanup);
- }
+GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
+ var entries = this._readdir(abs, inGlobStar)
- source.on('end', cleanup);
- source.on('close', cleanup);
+ // if the abs isn't a dir, then nothing can match!
+ if (!entries)
+ return
- dest.on('close', cleanup);
+ // It will only match dot entries if it starts with a dot, or if
+ // dot is set. Stuff like @(.foo|.bar) isn't allowed.
+ var pn = remain[0]
+ var negate = !!this.minimatch.negate
+ var rawGlob = pn._glob
+ var dotOk = this.dot || rawGlob.charAt(0) === '.'
- dest.emit('pipe', source);
+ var matchedEntries = []
+ for (var i = 0; i < entries.length; i++) {
+ var e = entries[i]
+ if (e.charAt(0) !== '.' || dotOk) {
+ var m
+ if (negate && !prefix) {
+ m = !e.match(pn)
+ } else {
+ m = e.match(pn)
+ }
+ if (m)
+ matchedEntries.push(e)
+ }
+ }
- // Allow for unix-like usage: A.pipe(B).pipe(C)
- return dest;
-};
+ var len = matchedEntries.length
+ // If there are no matched entries, then nothing matches.
+ if (len === 0)
+ return
-},{"events":14,"inherits":18,"readable-stream/duplex.js":69,"readable-stream/passthrough.js":75,"readable-stream/readable.js":76,"readable-stream/transform.js":77,"readable-stream/writable.js":78}],82:[function(require,module,exports){
-var ClientRequest = require('./lib/request')
-var extend = require('xtend')
-var statusCodes = require('builtin-status-codes')
-var url = require('url')
+ // if this is the last remaining pattern bit, then no need for
+ // an additional stat *unless* the user has specified mark or
+ // stat explicitly. We know they exist, since readdir returned
+ // them.
-var http = exports
+ if (remain.length === 1 && !this.mark && !this.stat) {
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null)
-http.request = function (opts, cb) {
- if (typeof opts === 'string')
- opts = url.parse(opts)
- else
- opts = extend(opts)
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i]
+ if (prefix) {
+ if (prefix.slice(-1) !== '/')
+ e = prefix + '/' + e
+ else
+ e = prefix + e
+ }
- var protocol = opts.protocol || ''
- var host = opts.hostname || opts.host
- var port = opts.port
- var path = opts.path || '/'
+ if (e.charAt(0) === '/' && !this.nomount) {
+ e = path.join(this.root, e)
+ }
+ this.matches[index][e] = true
+ }
+ // This was the last one, and no stats were needed
+ return
+ }
- // Necessary for IPv6 addresses
- if (host && host.indexOf(':') !== -1)
- host = '[' + host + ']'
+ // now test all matched entries as stand-ins for that part
+ // of the pattern.
+ remain.shift()
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i]
+ var newPattern
+ if (prefix)
+ newPattern = [prefix, e]
+ else
+ newPattern = [e]
+ this._process(newPattern.concat(remain), index, inGlobStar)
+ }
+}
- // This may be a relative url. The browser should always be able to interpret it correctly.
- opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
- opts.method = (opts.method || 'GET').toUpperCase()
- opts.headers = opts.headers || {}
- // Also valid opts.auth, opts.mode
+GlobSync.prototype._emitMatch = function (index, e) {
+ var abs = this._makeAbs(e)
+ if (this.mark)
+ e = this._mark(e)
- var req = new ClientRequest(opts)
- if (cb)
- req.on('response', cb)
- return req
-}
+ if (this.matches[index][e])
+ return
-http.get = function get (opts, cb) {
- var req = http.request(opts, cb)
- req.end()
- return req
+ if (this.nodir) {
+ var c = this.cache[this._makeAbs(e)]
+ if (c === 'DIR' || Array.isArray(c))
+ return
+ }
+
+ this.matches[index][e] = true
+ if (this.stat)
+ this._stat(e)
}
-http.Agent = function () {}
-http.Agent.defaultMaxSockets = 4
-http.STATUS_CODES = statusCodes
+GlobSync.prototype._readdirInGlobStar = function (abs) {
+ // follow all symlinked directories forever
+ // just proceed as if this is a non-globstar situation
+ if (this.follow)
+ return this._readdir(abs, false)
-http.METHODS = [
- 'CHECKOUT',
- 'CONNECT',
- 'COPY',
- 'DELETE',
- 'GET',
- 'HEAD',
- 'LOCK',
- 'M-SEARCH',
- 'MERGE',
- 'MKACTIVITY',
- 'MKCOL',
- 'MOVE',
- 'NOTIFY',
- 'OPTIONS',
- 'PATCH',
- 'POST',
- 'PROPFIND',
- 'PROPPATCH',
- 'PURGE',
- 'PUT',
- 'REPORT',
- 'SEARCH',
- 'SUBSCRIBE',
- 'TRACE',
- 'UNLOCK',
- 'UNSUBSCRIBE'
-]
-},{"./lib/request":84,"builtin-status-codes":7,"url":87,"xtend":104}],83:[function(require,module,exports){
-(function (global){
-exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableByteStream)
+ var entries
+ var lstat
+ var stat
+ try {
+ lstat = fs.lstatSync(abs)
+ } catch (er) {
+ // lstat failed, doesn't exist
+ return null
+ }
-exports.blobConstructor = false
-try {
- new Blob([new ArrayBuffer(1)])
- exports.blobConstructor = true
-} catch (e) {}
+ var isSym = lstat.isSymbolicLink()
+ this.symlinks[abs] = isSym
-var xhr = new global.XMLHttpRequest()
-// If location.host is empty, e.g. if this page/worker was loaded
-// from a Blob, then use example.com to avoid an error
-xhr.open('GET', global.location.host ? '/' : 'https://example.com')
+ // If it's not a symlink or a dir, then it's definitely a regular file.
+ // don't bother doing a readdir in that case.
+ if (!isSym && !lstat.isDirectory())
+ this.cache[abs] = 'FILE'
+ else
+ entries = this._readdir(abs, false)
-function checkTypeSupport (type) {
- try {
- xhr.responseType = type
- return xhr.responseType === type
- } catch (e) {}
- return false
+ return entries
}
-// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.
-// Safari 7.1 appears to have fixed this bug.
-var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined'
-var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice)
+GlobSync.prototype._readdir = function (abs, inGlobStar) {
+ var entries
-exports.arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer')
-// These next two tests unavoidably show warnings in Chrome. Since fetch will always
-// be used if it's available, just return false for these to avoid the warnings.
-exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream')
-exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer &&
- checkTypeSupport('moz-chunked-arraybuffer')
-exports.overrideMimeType = isFunction(xhr.overrideMimeType)
-exports.vbArray = isFunction(global.VBArray)
+ if (inGlobStar && !ownProp(this.symlinks, abs))
+ return this._readdirInGlobStar(abs)
+
+ if (ownProp(this.cache, abs)) {
+ var c = this.cache[abs]
+ if (!c || c === 'FILE')
+ return null
+
+ if (Array.isArray(c))
+ return c
+ }
-function isFunction (value) {
- return typeof value === 'function'
+ try {
+ return this._readdirEntries(abs, fs.readdirSync(abs))
+ } catch (er) {
+ this._readdirError(abs, er)
+ return null
+ }
}
-xhr = null // Help gc
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],84:[function(require,module,exports){
-(function (process,global,Buffer){
-// var Base64 = require('Base64')
-var capability = require('./capability')
-var foreach = require('foreach')
-var indexOf = require('indexof')
-var inherits = require('inherits')
-var keys = require('object-keys')
-var response = require('./response')
-var stream = require('stream')
+GlobSync.prototype._readdirEntries = function (abs, entries) {
+ // if we haven't asked to stat everything, then just
+ // assume that everything in there exists, so we can avoid
+ // having to stat it a second time.
+ if (!this.mark && !this.stat) {
+ for (var i = 0; i < entries.length; i ++) {
+ var e = entries[i]
+ if (abs === '/')
+ e = abs + e
+ else
+ e = abs + '/' + e
+ this.cache[e] = true
+ }
+ }
-var IncomingMessage = response.IncomingMessage
-var rStates = response.readyStates
+ this.cache[abs] = entries
-function decideMode (preferBinary) {
- if (capability.fetch) {
- return 'fetch'
- } else if (capability.mozchunkedarraybuffer) {
- return 'moz-chunked-arraybuffer'
- } else if (capability.msstream) {
- return 'ms-stream'
- } else if (capability.arraybuffer && preferBinary) {
- return 'arraybuffer'
- } else if (capability.vbArray && preferBinary) {
- return 'text:vbarray'
- } else {
- return 'text'
- }
+ // mark and cache dir-ness
+ return entries
}
-var ClientRequest = module.exports = function (opts) {
- var self = this
- stream.Writable.call(self)
-
- self._opts = opts
- self._body = []
- self._headers = {}
- if (opts.auth)
- self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
- foreach(keys(opts.headers), function (name) {
- self.setHeader(name, opts.headers[name])
- })
+GlobSync.prototype._readdirError = function (f, er) {
+ // handle errors, and cache the information
+ switch (er.code) {
+ case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
+ case 'ENOTDIR': // totally normal. means it *does* exist.
+ this.cache[this._makeAbs(f)] = 'FILE'
+ break
- var preferBinary
- if (opts.mode === 'prefer-streaming') {
- // If streaming is a high priority but binary compatibility and
- // the accuracy of the 'content-type' header aren't
- preferBinary = false
- } else if (opts.mode === 'allow-wrong-content-type') {
- // If streaming is more important than preserving the 'content-type' header
- preferBinary = !capability.overrideMimeType
- } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
- // Use binary if text streaming may corrupt data or the content-type header, or for speed
- preferBinary = true
- } else {
- throw new Error('Invalid value for opts.mode')
- }
- self._mode = decideMode(preferBinary)
+ case 'ENOENT': // not terribly unusual
+ case 'ELOOP':
+ case 'ENAMETOOLONG':
+ case 'UNKNOWN':
+ this.cache[this._makeAbs(f)] = false
+ break
- self.on('finish', function () {
- self._onFinish()
- })
+ default: // some unusual error. Treat as failure.
+ this.cache[this._makeAbs(f)] = false
+ if (this.strict)
+ throw er
+ if (!this.silent)
+ console.error('glob error', er)
+ break
+ }
}
-inherits(ClientRequest, stream.Writable)
+GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
-ClientRequest.prototype.setHeader = function (name, value) {
- var self = this
- var lowerName = name.toLowerCase()
- // This check is not necessary, but it prevents warnings from browsers about setting unsafe
- // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
- // http-browserify did it, so I will too.
- if (indexOf(unsafeHeaders, lowerName) !== -1)
- return
+ var entries = this._readdir(abs, inGlobStar)
- self._headers[lowerName] = {
- name: name,
- value: value
- }
-}
+ // no entries means not a dir, so it can never have matches
+ // foo.txt/** doesn't match foo.txt
+ if (!entries)
+ return
-ClientRequest.prototype.getHeader = function (name) {
- var self = this
- return self._headers[name.toLowerCase()].value
-}
+ // test without the globstar, and with every child both below
+ // and replacing the globstar.
+ var remainWithoutGlobStar = remain.slice(1)
+ var gspref = prefix ? [ prefix ] : []
+ var noGlobStar = gspref.concat(remainWithoutGlobStar)
-ClientRequest.prototype.removeHeader = function (name) {
- var self = this
- delete self._headers[name.toLowerCase()]
-}
+ // the noGlobStar pattern exits the inGlobStar state
+ this._process(noGlobStar, index, false)
-ClientRequest.prototype._onFinish = function () {
- var self = this
+ var len = entries.length
+ var isSym = this.symlinks[abs]
- if (self._destroyed)
- return
- var opts = self._opts
+ // If it's a symlink, and we're in a globstar, then stop
+ if (isSym && inGlobStar)
+ return
- var headersObj = self._headers
- var body
- if (opts.method === 'POST' || opts.method === 'PUT') {
- if (capability.blobConstructor) {
- body = new global.Blob(self._body.map(function (buffer) {
- return buffer.toArrayBuffer()
- }), {
- type: (headersObj['content-type'] || {}).value || ''
- })
- } else {
- // get utf8 string
- body = Buffer.concat(self._body).toString()
- }
- }
+ for (var i = 0; i < len; i++) {
+ var e = entries[i]
+ if (e.charAt(0) === '.' && !this.dot)
+ continue
- if (self._mode === 'fetch') {
- var headers = keys(headersObj).map(function (name) {
- return [headersObj[name].name, headersObj[name].value]
- })
+ // these two cases enter the inGlobStar state
+ var instead = gspref.concat(entries[i], remainWithoutGlobStar)
+ this._process(instead, index, true)
- global.fetch(self._opts.url, {
- method: self._opts.method,
- headers: headers,
- body: body,
- mode: 'cors',
- credentials: opts.withCredentials ? 'include' : 'same-origin'
- }).then(function (response) {
- self._fetchResponse = response
- self._connect()
- }).then(undefined, function (reason) {
- self.emit('error', reason)
- })
- } else {
- var xhr = self._xhr = new global.XMLHttpRequest()
- try {
- xhr.open(self._opts.method, self._opts.url, true)
- } catch (err) {
- process.nextTick(function () {
- self.emit('error', err)
- })
- return
- }
+ var below = gspref.concat(entries[i], remain)
+ this._process(below, index, true)
+ }
+}
- // Can't set responseType on really old browsers
- if ('responseType' in xhr)
- xhr.responseType = self._mode.split(':')[0]
+GlobSync.prototype._processSimple = function (prefix, index) {
+ // XXX review this. Shouldn't it be doing the mounting etc
+ // before doing stat? kinda weird?
+ var exists = this._stat(prefix)
- if ('withCredentials' in xhr)
- xhr.withCredentials = !!opts.withCredentials
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null)
- if (self._mode === 'text' && 'overrideMimeType' in xhr)
- xhr.overrideMimeType('text/plain; charset=x-user-defined')
+ // If it doesn't exist, then just mark the lack of results
+ if (!exists)
+ return
- foreach(keys(headersObj), function (name) {
- xhr.setRequestHeader(headersObj[name].name, headersObj[name].value)
- })
+ if (prefix && isAbsolute(prefix) && !this.nomount) {
+ var trail = /[\/\\]$/.test(prefix)
+ if (prefix.charAt(0) === '/') {
+ prefix = path.join(this.root, prefix)
+ } else {
+ prefix = path.resolve(this.root, prefix)
+ if (trail)
+ prefix += '/'
+ }
+ }
- self._response = null
- xhr.onreadystatechange = function () {
- switch (xhr.readyState) {
- case rStates.LOADING:
- case rStates.DONE:
- self._onXHRProgress()
- break
- }
- }
- // Necessary for streaming in Firefox, since xhr.response is ONLY defined
- // in onprogress, not in onreadystatechange with xhr.readyState = 3
- if (self._mode === 'moz-chunked-arraybuffer') {
- xhr.onprogress = function () {
- self._onXHRProgress()
- }
- }
+ if (process.platform === 'win32')
+ prefix = prefix.replace(/\\/g, '/')
+
+ // Mark this as a match
+ this.matches[index][prefix] = true
+}
+
+// Returns either 'DIR', 'FILE', or false
+GlobSync.prototype._stat = function (f) {
+ var abs = this._makeAbs(f)
+ var needDir = f.slice(-1) === '/'
- xhr.onerror = function () {
- if (self._destroyed)
- return
- self.emit('error', new Error('XHR error'))
- }
+ if (f.length > this.maxLength)
+ return false
- try {
- xhr.send(body)
- } catch (err) {
- process.nextTick(function () {
- self.emit('error', err)
- })
- return
- }
- }
-}
+ if (!this.stat && ownProp(this.cache, abs)) {
+ var c = this.cache[abs]
-/**
- * Checks if xhr.status is readable. Even though the spec says it should
- * be available in readyState 3, accessing it throws an exception in IE8
- */
-function statusValid (xhr) {
- try {
- return (xhr.status !== null)
- } catch (e) {
- return false
- }
-}
+ if (Array.isArray(c))
+ c = 'DIR'
-ClientRequest.prototype._onXHRProgress = function () {
- var self = this
+ // It exists, but maybe not how we need it
+ if (!needDir || c === 'DIR')
+ return c
- if (!statusValid(self._xhr) || self._destroyed)
- return
+ if (needDir && c === 'FILE')
+ return false
- if (!self._response)
- self._connect()
+ // otherwise we have to stat, because maybe c=true
+ // if we know it exists, but not what it is.
+ }
- self._response._onXHRProgress()
-}
+ var exists
+ var stat = this.statCache[abs]
+ if (!stat) {
+ var lstat
+ try {
+ lstat = fs.lstatSync(abs)
+ } catch (er) {
+ return false
+ }
-ClientRequest.prototype._connect = function () {
- var self = this
+ if (lstat.isSymbolicLink()) {
+ try {
+ stat = fs.statSync(abs)
+ } catch (er) {
+ stat = lstat
+ }
+ } else {
+ stat = lstat
+ }
+ }
- if (self._destroyed)
- return
+ this.statCache[abs] = stat
- self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
- self.emit('response', self._response)
-}
+ var c = stat.isDirectory() ? 'DIR' : 'FILE'
+ this.cache[abs] = this.cache[abs] || c
-ClientRequest.prototype._write = function (chunk, encoding, cb) {
- var self = this
+ if (needDir && c !== 'DIR')
+ return false
- self._body.push(chunk)
- cb()
+ return c
}
-ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
- var self = this
- self._destroyed = true
- if (self._response)
- self._response._destroyed = true
- if (self._xhr)
- self._xhr.abort()
- // Currently, there isn't a way to truly abort a fetch.
- // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27
+GlobSync.prototype._mark = function (p) {
+ return common.mark(this, p)
}
-ClientRequest.prototype.end = function (data, encoding, cb) {
- var self = this
- if (typeof data === 'function') {
- cb = data
- data = undefined
- }
-
- stream.Writable.prototype.end.call(self, data, encoding, cb)
+GlobSync.prototype._makeAbs = function (f) {
+ return common.makeAbs(this, f)
}
-ClientRequest.prototype.flushHeaders = function () {}
-ClientRequest.prototype.setTimeout = function () {}
-ClientRequest.prototype.setNoDelay = function () {}
-ClientRequest.prototype.setSocketKeepAlive = function () {}
+}).call(this,require('_process'))
+},{"./common.js":29,"./glob.js":30,"_process":107,"assert":1,"fs":6,"minimatch":84,"path":104,"path-is-absolute":105,"util":138}],32:[function(require,module,exports){
+'use strict';
-// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
-var unsafeHeaders = [
- 'accept-charset',
- 'accept-encoding',
- 'access-control-request-headers',
- 'access-control-request-method',
- 'connection',
- 'content-length',
- 'cookie',
- 'cookie2',
- 'date',
- 'dnt',
- 'expect',
- 'host',
- 'keep-alive',
- 'origin',
- 'referer',
- 'te',
- 'trailer',
- 'transfer-encoding',
- 'upgrade',
- 'user-agent',
- 'via'
-]
+var path = require('path');
+var findIndex = require('find-index');
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
-},{"./capability":83,"./response":85,"_process":64,"buffer":6,"foreach":15,"indexof":17,"inherits":18,"object-keys":58,"stream":81}],85:[function(require,module,exports){
-(function (process,global,Buffer){
-var capability = require('./capability')
-var foreach = require('foreach')
-var inherits = require('inherits')
-var stream = require('stream')
+var flattenGlob = function(arr){
+ var out = [];
+ var flat = true;
+ for(var i = 0; i < arr.length; i++) {
+ if (typeof arr[i] !== 'string') {
+ flat = false;
+ break;
+ }
+ out.push(arr[i]);
+ }
-var rStates = exports.readyStates = {
- UNSENT: 0,
- OPENED: 1,
- HEADERS_RECEIVED: 2,
- LOADING: 3,
- DONE: 4
-}
+ // last one is a file or specific dir
+ // so we pop it off
+ if (flat) {
+ out.pop();
+ }
+ return out;
+};
-var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) {
- var self = this
- stream.Readable.call(self)
+var flattenExpansion = function(set) {
+ var first = set[0];
+ var toCompare = set.slice(1);
- self._mode = mode
- self.headers = {}
- self.rawHeaders = []
- self.trailers = {}
- self.rawTrailers = []
+ // find index where the diff is
+ var idx = findIndex(first, function(v, idx){
+ if (typeof v !== 'string') {
+ return true;
+ }
- // Fake the 'close' event, but only once 'end' fires
- self.on('end', function () {
- // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
- process.nextTick(function () {
- self.emit('close')
- })
- })
+ var matched = toCompare.every(function(arr){
+ return v === arr[idx];
+ });
- if (mode === 'fetch') {
- self._fetchResponse = response
+ return !matched;
+ });
- self.statusCode = response.status
- self.statusMessage = response.statusText
- // backwards compatible version of for (- of ):
- // for (var
- ,_i,_it = [Symbol.iterator]();
- = (_i = _it.next()).value,!_i.done;)
- for (var header, _i, _it = response.headers[Symbol.iterator](); header = (_i = _it.next()).value, !_i.done;) {
- self.headers[header[0].toLowerCase()] = header[1]
- self.rawHeaders.push(header[0], header[1])
- }
+ return first.slice(0, idx);
+};
- // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed
- var reader = response.body.getReader()
- function read () {
- reader.read().then(function (result) {
- if (self._destroyed)
- return
- if (result.done) {
- self.push(null)
- return
- }
- self.push(new Buffer(result.value))
- read()
- })
- }
- read()
+var setToBase = function(set) {
+ // normal something/*.js
+ if (set.length <= 1) {
+ return flattenGlob(set[0]);
+ }
+ // has expansion
+ return flattenExpansion(set);
+};
- } else {
- self._xhr = xhr
- self._pos = 0
+module.exports = function(glob) {
+ var set = glob.minimatch.set;
+ var baseParts = setToBase(set);
+ var basePath = path.normalize(baseParts.join(path.sep))+path.sep;
+ return basePath;
+};
- self.statusCode = xhr.status
- self.statusMessage = xhr.statusText
- var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
- foreach(headers, function (header) {
- var matches = header.match(/^([^:]+):\s*(.*)/)
- if (matches) {
- var key = matches[1].toLowerCase()
- if (self.headers[key] !== undefined)
- self.headers[key] += ', ' + matches[2]
- else
- self.headers[key] = matches[2]
- self.rawHeaders.push(matches[1], matches[2])
- }
- })
+},{"find-index":19,"path":104}],33:[function(require,module,exports){
+'use strict'
+
+var fs = require('fs')
- self._charset = 'x-user-defined'
- if (!capability.overrideMimeType) {
- var mimeType = self.rawHeaders['mime-type']
- if (mimeType) {
- var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
- if (charsetMatch) {
- self._charset = charsetMatch[1].toLowerCase()
- }
- }
- if (!self._charset)
- self._charset = 'utf-8' // best guess
- }
- }
-}
+module.exports = clone(fs)
-inherits(IncomingMessage, stream.Readable)
+function clone (obj) {
+ if (obj === null || typeof obj !== 'object')
+ return obj
-IncomingMessage.prototype._read = function () {}
+ if (obj instanceof Object)
+ var copy = { __proto__: obj.__proto__ }
+ else
+ var copy = Object.create(null)
-IncomingMessage.prototype._onXHRProgress = function () {
- var self = this
+ Object.getOwnPropertyNames(obj).forEach(function (key) {
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))
+ })
- var xhr = self._xhr
+ return copy
+}
- var response = null
- switch (self._mode) {
- case 'text:vbarray': // For IE9
- if (xhr.readyState !== rStates.DONE)
- break
- try {
- // This fails in IE8
- response = new global.VBArray(xhr.responseBody).toArray()
- } catch (e) {}
- if (response !== null) {
- self.push(new Buffer(response))
- break
- }
- // Falls through in IE8
- case 'text':
- try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4
- response = xhr.responseText
- } catch (e) {
- self._mode = 'text:vbarray'
- break
- }
- if (response.length > self._pos) {
- var newData = response.substr(self._pos)
- if (self._charset === 'x-user-defined') {
- var buffer = new Buffer(newData.length)
- for (var i = 0; i < newData.length; i++)
- buffer[i] = newData.charCodeAt(i) & 0xff
+},{"fs":6}],34:[function(require,module,exports){
+(function (process){
+var fs = require('fs')
+var polyfills = require('./polyfills.js')
+var legacy = require('./legacy-streams.js')
+var queue = []
- self.push(buffer)
- } else {
- self.push(newData, self._charset)
- }
- self._pos = response.length
- }
- break
- case 'arraybuffer':
- if (xhr.readyState !== rStates.DONE)
- break
- response = xhr.response
- self.push(new Buffer(new Uint8Array(response)))
- break
- case 'moz-chunked-arraybuffer': // take whole
- response = xhr.response
- if (xhr.readyState !== rStates.LOADING || !response)
- break
- self.push(new Buffer(new Uint8Array(response)))
- break
- case 'ms-stream':
- response = xhr.response
- if (xhr.readyState !== rStates.LOADING)
- break
- var reader = new global.MSStreamReader()
- reader.onprogress = function () {
- if (reader.result.byteLength > self._pos) {
- self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))))
- self._pos = reader.result.byteLength
- }
- }
- reader.onload = function () {
- self.push(null)
- }
- // reader.onerror = ??? // TODO: this
- reader.readAsArrayBuffer(response)
- break
- }
+var util = require('util')
- // The ms-stream case handles end separately in reader.onload()
- if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
- self.push(null)
- }
+function noop () {}
+
+var debug = noop
+if (util.debuglog)
+ debug = util.debuglog('gfs4')
+else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
+ debug = function() {
+ var m = util.format.apply(util, arguments)
+ m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
+ console.error(m)
+ }
+
+if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
+ process.on('exit', function() {
+ debug(queue)
+ require('assert').equal(queue.length, 0)
+ })
}
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
-},{"./capability":83,"_process":64,"buffer":6,"foreach":15,"inherits":18,"stream":81}],86:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+module.exports = patch(require('./fs.js'))
+if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) {
+ module.exports = patch(fs)
+}
-var Buffer = require('buffer').Buffer;
+// Always patch fs.close/closeSync, because we want to
+// retry() whenever a close happens *anywhere* in the program.
+// This is essential when multiple graceful-fs instances are
+// in play at the same time.
+fs.close = (function (fs$close) { return function (fd, cb) {
+ return fs$close.call(fs, fd, function (err) {
+ if (!err)
+ retry()
-var isBufferEncoding = Buffer.isEncoding
- || function(encoding) {
- switch (encoding && encoding.toLowerCase()) {
- case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
- default: return false;
- }
- }
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ })
+}})(fs.close)
+fs.closeSync = (function (fs$closeSync) { return function (fd) {
+ // Note that graceful-fs also retries when fs.closeSync() fails.
+ // Looks like a bug to me, although it's probably a harmless one.
+ var rval = fs$closeSync.apply(fs, arguments)
+ retry()
+ return rval
+}})(fs.closeSync)
-function assertEncoding(encoding) {
- if (encoding && !isBufferEncoding(encoding)) {
- throw new Error('Unknown encoding: ' + encoding);
+function patch (fs) {
+ // Everything that references the open() function needs to be in here
+ polyfills(fs)
+ fs.gracefulify = patch
+ fs.FileReadStream = ReadStream; // Legacy name.
+ fs.FileWriteStream = WriteStream; // Legacy name.
+ fs.createReadStream = createReadStream
+ fs.createWriteStream = createWriteStream
+ var fs$readFile = fs.readFile
+ fs.readFile = readFile
+ function readFile (path, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null
+
+ return go$readFile(path, options, cb)
+
+ function go$readFile (path, options, cb) {
+ return fs$readFile(path, options, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$readFile, [path, options, cb]])
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ retry()
+ }
+ })
+ }
}
-}
-// StringDecoder provides an interface for efficiently splitting a series of
-// buffers into a series of JS strings without breaking apart multi-byte
-// characters. CESU-8 is handled as part of the UTF-8 encoding.
-//
-// @TODO Handling all encodings inside a single object makes it very difficult
-// to reason about this code, so it should be split up in the future.
-// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
-// points as used by CESU-8.
-var StringDecoder = exports.StringDecoder = function(encoding) {
- this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
- assertEncoding(encoding);
- switch (this.encoding) {
- case 'utf8':
- // CESU-8 represents each of Surrogate Pair by 3-bytes
- this.surrogateSize = 3;
- break;
- case 'ucs2':
- case 'utf16le':
- // UTF-16 represents each of Surrogate Pair by 2-bytes
- this.surrogateSize = 2;
- this.detectIncompleteChar = utf16DetectIncompleteChar;
- break;
- case 'base64':
- // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
- this.surrogateSize = 3;
- this.detectIncompleteChar = base64DetectIncompleteChar;
- break;
- default:
- this.write = passThroughWrite;
- return;
+ var fs$writeFile = fs.writeFile
+ fs.writeFile = writeFile
+ function writeFile (path, data, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null
+
+ return go$writeFile(path, data, options, cb)
+
+ function go$writeFile (path, data, options, cb) {
+ return fs$writeFile(path, data, options, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$writeFile, [path, data, options, cb]])
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ retry()
+ }
+ })
+ }
}
- // Enough space to store all bytes of a single character. UTF-8 needs 4
- // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
- this.charBuffer = new Buffer(6);
- // Number of bytes received for the current incomplete multi-byte character.
- this.charReceived = 0;
- // Number of bytes expected for the current incomplete multi-byte character.
- this.charLength = 0;
-};
+ var fs$appendFile = fs.appendFile
+ if (fs$appendFile)
+ fs.appendFile = appendFile
+ function appendFile (path, data, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null
+
+ return go$appendFile(path, data, options, cb)
+ function go$appendFile (path, data, options, cb) {
+ return fs$appendFile(path, data, options, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$appendFile, [path, data, options, cb]])
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ retry()
+ }
+ })
+ }
+ }
-// write decodes the given buffer and returns it as JS string that is
-// guaranteed to not contain any partial multi-byte characters. Any partial
-// character found at the end of the buffer is buffered up, and will be
-// returned when calling write again with the remaining bytes.
-//
-// Note: Converting a Buffer containing an orphan surrogate to a String
-// currently works, but converting a String to a Buffer (via `new Buffer`, or
-// Buffer#write) will replace incomplete surrogates with the unicode
-// replacement character. See https://codereview.chromium.org/121173009/ .
-StringDecoder.prototype.write = function(buffer) {
- var charStr = '';
- // if our last write ended with an incomplete multibyte character
- while (this.charLength) {
- // determine how many remaining bytes this buffer has to offer for this char
- var available = (buffer.length >= this.charLength - this.charReceived) ?
- this.charLength - this.charReceived :
- buffer.length;
+ var fs$readdir = fs.readdir
+ fs.readdir = readdir
+ function readdir (path, cb) {
+ return go$readdir(path, cb)
- // add the new bytes to the char buffer
- buffer.copy(this.charBuffer, this.charReceived, 0, available);
- this.charReceived += available;
+ function go$readdir () {
+ return fs$readdir(path, function (err, files) {
+ if (files && files.sort)
+ files.sort(); // Backwards compatibility with graceful-fs.
- if (this.charReceived < this.charLength) {
- // still not enough chars in this buffer? wait for more ...
- return '';
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$readdir, [path, cb]])
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ retry()
+ }
+ })
}
+ }
- // remove bytes belonging to the current character from the buffer
- buffer = buffer.slice(available, buffer.length);
- // get the character that was split
- charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
+ if (process.version.substr(0, 4) === 'v0.8') {
+ var legStreams = legacy(fs)
+ ReadStream = legStreams.ReadStream
+ WriteStream = legStreams.WriteStream
+ }
- // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
- var charCode = charStr.charCodeAt(charStr.length - 1);
- if (charCode >= 0xD800 && charCode <= 0xDBFF) {
- this.charLength += this.surrogateSize;
- charStr = '';
- continue;
- }
- this.charReceived = this.charLength = 0;
+ var fs$ReadStream = fs.ReadStream
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype)
+ ReadStream.prototype.open = ReadStream$open
- // if there are no more bytes in this buffer, just emit our char
- if (buffer.length === 0) {
- return charStr;
- }
- break;
+ var fs$WriteStream = fs.WriteStream
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype)
+ WriteStream.prototype.open = WriteStream$open
+
+ fs.ReadStream = ReadStream
+ fs.WriteStream = WriteStream
+
+ function ReadStream (path, options) {
+ if (this instanceof ReadStream)
+ return fs$ReadStream.apply(this, arguments), this
+ else
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
}
- // determine and set charLength / charReceived
- this.detectIncompleteChar(buffer);
+ function ReadStream$open () {
+ var that = this
+ open(that.path, that.flags, that.mode, function (err, fd) {
+ if (err) {
+ if (that.autoClose)
+ that.destroy()
- var end = buffer.length;
- if (this.charLength) {
- // buffer the incomplete character bytes we got
- buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
- end -= this.charReceived;
+ that.emit('error', err)
+ } else {
+ that.fd = fd
+ that.emit('open', fd)
+ that.read()
+ }
+ })
}
- charStr += buffer.toString(this.encoding, 0, end);
+ function WriteStream (path, options) {
+ if (this instanceof WriteStream)
+ return fs$WriteStream.apply(this, arguments), this
+ else
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
+ }
- var end = charStr.length - 1;
- var charCode = charStr.charCodeAt(end);
- // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
- if (charCode >= 0xD800 && charCode <= 0xDBFF) {
- var size = this.surrogateSize;
- this.charLength += size;
- this.charReceived += size;
- this.charBuffer.copy(this.charBuffer, size, 0, size);
- buffer.copy(this.charBuffer, 0, 0, size);
- return charStr.substring(0, end);
+ function WriteStream$open () {
+ var that = this
+ open(that.path, that.flags, that.mode, function (err, fd) {
+ if (err) {
+ that.destroy()
+ that.emit('error', err)
+ } else {
+ that.fd = fd
+ that.emit('open', fd)
+ }
+ })
}
- // or just emit the charStr
- return charStr;
-};
+ function createReadStream (path, options) {
+ return new ReadStream(path, options)
+ }
-// detectIncompleteChar determines if there is an incomplete UTF-8 character at
-// the end of the given buffer. If so, it sets this.charLength to the byte
-// length that character, and sets this.charReceived to the number of bytes
-// that are available for this character.
-StringDecoder.prototype.detectIncompleteChar = function(buffer) {
- // determine how many bytes we have to check at the end of this buffer
- var i = (buffer.length >= 3) ? 3 : buffer.length;
+ function createWriteStream (path, options) {
+ return new WriteStream(path, options)
+ }
- // Figure out if one of the last i bytes of our buffer announces an
- // incomplete char.
- for (; i > 0; i--) {
- var c = buffer[buffer.length - i];
+ var fs$open = fs.open
+ fs.open = open
+ function open (path, flags, mode, cb) {
+ if (typeof mode === 'function')
+ cb = mode, mode = null
- // See http://en.wikipedia.org/wiki/UTF-8#Description
+ return go$open(path, flags, mode, cb)
- // 110XXXXX
- if (i == 1 && c >> 5 == 0x06) {
- this.charLength = 2;
- break;
+ function go$open (path, flags, mode, cb) {
+ return fs$open(path, flags, mode, function (err, fd) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$open, [path, flags, mode, cb]])
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ retry()
+ }
+ })
}
+ }
- // 1110XXXX
- if (i <= 2 && c >> 4 == 0x0E) {
- this.charLength = 3;
- break;
- }
+ return fs
+}
- // 11110XXX
- if (i <= 3 && c >> 3 == 0x1E) {
- this.charLength = 4;
- break;
- }
+function enqueue (elem) {
+ debug('ENQUEUE', elem[0].name, elem[1])
+ queue.push(elem)
+}
+
+function retry () {
+ var elem = queue.shift()
+ if (elem) {
+ debug('RETRY', elem[0].name, elem[1])
+ elem[0].apply(null, elem[1])
}
- this.charReceived = i;
-};
+}
-StringDecoder.prototype.end = function(buffer) {
- var res = '';
- if (buffer && buffer.length)
- res = this.write(buffer);
+}).call(this,require('_process'))
+},{"./fs.js":33,"./legacy-streams.js":35,"./polyfills.js":36,"_process":107,"assert":1,"fs":6,"util":138}],35:[function(require,module,exports){
+(function (process){
+var Stream = require('stream').Stream
- if (this.charReceived) {
- var cr = this.charReceived;
- var buf = this.charBuffer;
- var enc = this.encoding;
- res += buf.slice(0, cr).toString(enc);
+module.exports = legacy
+
+function legacy (fs) {
+ return {
+ ReadStream: ReadStream,
+ WriteStream: WriteStream
}
- return res;
-};
+ function ReadStream (path, options) {
+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);
-function passThroughWrite(buffer) {
- return buffer.toString(this.encoding);
-}
+ Stream.call(this);
+
+ var self = this;
+
+ this.path = path;
+ this.fd = null;
+ this.readable = true;
+ this.paused = false;
+
+ this.flags = 'r';
+ this.mode = 438; /*=0666*/
+ this.bufferSize = 64 * 1024;
-function utf16DetectIncompleteChar(buffer) {
- this.charReceived = buffer.length % 2;
- this.charLength = this.charReceived ? 2 : 0;
-}
+ options = options || {};
-function base64DetectIncompleteChar(buffer) {
- this.charReceived = buffer.length % 3;
- this.charLength = this.charReceived ? 3 : 0;
-}
+ // Mixin options into this
+ var keys = Object.keys(options);
+ for (var index = 0, length = keys.length; index < length; index++) {
+ var key = keys[index];
+ this[key] = options[key];
+ }
-},{"buffer":6}],87:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+ if (this.encoding) this.setEncoding(this.encoding);
-var punycode = require('punycode');
+ if (this.start !== undefined) {
+ if ('number' !== typeof this.start) {
+ throw TypeError('start must be a Number');
+ }
+ if (this.end === undefined) {
+ this.end = Infinity;
+ } else if ('number' !== typeof this.end) {
+ throw TypeError('end must be a Number');
+ }
-exports.parse = urlParse;
-exports.resolve = urlResolve;
-exports.resolveObject = urlResolveObject;
-exports.format = urlFormat;
+ if (this.start > this.end) {
+ throw new Error('start must be <= end');
+ }
-exports.Url = Url;
+ this.pos = this.start;
+ }
-function Url() {
- this.protocol = null;
- this.slashes = null;
- this.auth = null;
- this.host = null;
- this.port = null;
- this.hostname = null;
- this.hash = null;
- this.search = null;
- this.query = null;
- this.pathname = null;
- this.path = null;
- this.href = null;
-}
+ if (this.fd !== null) {
+ process.nextTick(function() {
+ self._read();
+ });
+ return;
+ }
-// Reference: RFC 3986, RFC 1808, RFC 2396
+ fs.open(this.path, this.flags, this.mode, function (err, fd) {
+ if (err) {
+ self.emit('error', err);
+ self.readable = false;
+ return;
+ }
-// define these here so at least they only have to be
-// compiled once on the first module load.
-var protocolPattern = /^([a-z0-9.+-]+:)/i,
- portPattern = /:[0-9]*$/,
+ self.fd = fd;
+ self.emit('open', fd);
+ self._read();
+ })
+ }
- // RFC 2396: characters reserved for delimiting URLs.
- // We actually just auto-escape these.
- delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
+ function WriteStream (path, options) {
+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);
- // RFC 2396: characters not allowed for various reasons.
- unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
+ Stream.call(this);
- // Allowed by RFCs, but cause of XSS attacks. Always escape these.
- autoEscape = ['\''].concat(unwise),
- // Characters that are never ever allowed in a hostname.
- // Note that any invalid chars are also handled, but these
- // are the ones that are *expected* to be seen, so we fast-path
- // them.
- nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
- hostEndingChars = ['/', '?', '#'],
- hostnameMaxLen = 255,
- hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
- hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
- // protocols that can allow "unsafe" and "unwise" chars.
- unsafeProtocol = {
- 'javascript': true,
- 'javascript:': true
- },
- // protocols that never have a hostname.
- hostlessProtocol = {
- 'javascript': true,
- 'javascript:': true
- },
- // protocols that always contain a // bit.
- slashedProtocol = {
- 'http': true,
- 'https': true,
- 'ftp': true,
- 'gopher': true,
- 'file': true,
- 'http:': true,
- 'https:': true,
- 'ftp:': true,
- 'gopher:': true,
- 'file:': true
- },
- querystring = require('querystring');
+ this.path = path;
+ this.fd = null;
+ this.writable = true;
-function urlParse(url, parseQueryString, slashesDenoteHost) {
- if (url && isObject(url) && url instanceof Url) return url;
+ this.flags = 'w';
+ this.encoding = 'binary';
+ this.mode = 438; /*=0666*/
+ this.bytesWritten = 0;
- var u = new Url;
- u.parse(url, parseQueryString, slashesDenoteHost);
- return u;
-}
+ options = options || {};
-Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
- if (!isString(url)) {
- throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
- }
+ // Mixin options into this
+ var keys = Object.keys(options);
+ for (var index = 0, length = keys.length; index < length; index++) {
+ var key = keys[index];
+ this[key] = options[key];
+ }
- var rest = url;
+ if (this.start !== undefined) {
+ if ('number' !== typeof this.start) {
+ throw TypeError('start must be a Number');
+ }
+ if (this.start < 0) {
+ throw new Error('start must be >= zero');
+ }
- // trim before proceeding.
- // This is to support parse stuff like " http://foo.com \n"
- rest = rest.trim();
+ this.pos = this.start;
+ }
- var proto = protocolPattern.exec(rest);
- if (proto) {
- proto = proto[0];
- var lowerProto = proto.toLowerCase();
- this.protocol = lowerProto;
- rest = rest.substr(proto.length);
- }
+ this.busy = false;
+ this._queue = [];
- // figure out if it's got a host
- // user@server is *always* interpreted as a hostname, and url
- // resolution will treat //foo/bar as host=foo,path=bar because that's
- // how the browser resolves relative URLs.
- if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
- var slashes = rest.substr(0, 2) === '//';
- if (slashes && !(proto && hostlessProtocol[proto])) {
- rest = rest.substr(2);
- this.slashes = true;
+ if (this.fd === null) {
+ this._open = fs.open;
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
+ this.flush();
}
}
+}
- if (!hostlessProtocol[proto] &&
- (slashes || (proto && !slashedProtocol[proto]))) {
+}).call(this,require('_process'))
+},{"_process":107,"stream":124}],36:[function(require,module,exports){
+(function (process){
+var fs = require('./fs.js')
+var constants = require('constants')
- // there's a hostname.
- // the first instance of /, ?, ;, or # ends the host.
- //
- // If there is an @ in the hostname, then non-host chars *are* allowed
- // to the left of the last @ sign, unless some host-ending character
- // comes *before* the @-sign.
- // URLs are obnoxious.
- //
- // ex:
- // http://a@b@c/ => user:a@b host:c
- // http://a@b?@c => user:a host:c path:/?@c
+var origCwd = process.cwd
+var cwd = null
+process.cwd = function() {
+ if (!cwd)
+ cwd = origCwd.call(process)
+ return cwd
+}
+try {
+ process.cwd()
+} catch (er) {}
- // v0.12 TODO(isaacs): This is not quite how Chrome does things.
- // Review our test case against browsers more comprehensively.
+var chdir = process.chdir
+process.chdir = function(d) {
+ cwd = null
+ chdir.call(process, d)
+}
- // find the first instance of any hostEndingChars
- var hostEnd = -1;
- for (var i = 0; i < hostEndingChars.length; i++) {
- var hec = rest.indexOf(hostEndingChars[i]);
- if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
- hostEnd = hec;
- }
+module.exports = patch
- // at this point, either we have an explicit point where the
- // auth portion cannot go past, or the last @ char is the decider.
- var auth, atSign;
- if (hostEnd === -1) {
- // atSign can be anywhere.
- atSign = rest.lastIndexOf('@');
- } else {
- // atSign must be in auth portion.
- // http://a@b/c@d => host:b auth:a path:/c@d
- atSign = rest.lastIndexOf('@', hostEnd);
- }
+function patch (fs) {
+ // (re-)implement some things that are known busted or missing.
+
+ // lchmod, broken prior to 0.6.2
+ // back-port the fix here.
+ if (constants.hasOwnProperty('O_SYMLINK') &&
+ process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
+ patchLchmod(fs)
+ }
- // Now we have a portion which is definitely the auth.
- // Pull that off.
- if (atSign !== -1) {
- auth = rest.slice(0, atSign);
- rest = rest.slice(atSign + 1);
- this.auth = decodeURIComponent(auth);
- }
+ // lutimes implementation, or no-op
+ if (!fs.lutimes) {
+ patchLutimes(fs)
+ }
- // the host is the remaining to the left of the first non-host char
- hostEnd = -1;
- for (var i = 0; i < nonHostChars.length; i++) {
- var hec = rest.indexOf(nonHostChars[i]);
- if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
- hostEnd = hec;
- }
- // if we still have not hit it, then the entire thing is a host.
- if (hostEnd === -1)
- hostEnd = rest.length;
+ // https://github.com/isaacs/node-graceful-fs/issues/4
+ // Chown should not fail on einval or eperm if non-root.
+ // It should not fail on enosys ever, as this just indicates
+ // that a fs doesn't support the intended operation.
- this.host = rest.slice(0, hostEnd);
- rest = rest.slice(hostEnd);
+ fs.chown = chownFix(fs.chown)
+ fs.fchown = chownFix(fs.fchown)
+ fs.lchown = chownFix(fs.lchown)
- // pull out port.
- this.parseHost();
+ fs.chmod = chownFix(fs.chmod)
+ fs.fchmod = chownFix(fs.fchmod)
+ fs.lchmod = chownFix(fs.lchmod)
- // we've indicated that there is a hostname,
- // so even if it's empty, it has to be present.
- this.hostname = this.hostname || '';
+ fs.chownSync = chownFixSync(fs.chownSync)
+ fs.fchownSync = chownFixSync(fs.fchownSync)
+ fs.lchownSync = chownFixSync(fs.lchownSync)
- // if hostname begins with [ and ends with ]
- // assume that it's an IPv6 address.
- var ipv6Hostname = this.hostname[0] === '[' &&
- this.hostname[this.hostname.length - 1] === ']';
+ fs.chmodSync = chownFix(fs.chmodSync)
+ fs.fchmodSync = chownFix(fs.fchmodSync)
+ fs.lchmodSync = chownFix(fs.lchmodSync)
- // validate a little.
- if (!ipv6Hostname) {
- var hostparts = this.hostname.split(/\./);
- for (var i = 0, l = hostparts.length; i < l; i++) {
- var part = hostparts[i];
- if (!part) continue;
- if (!part.match(hostnamePartPattern)) {
- var newpart = '';
- for (var j = 0, k = part.length; j < k; j++) {
- if (part.charCodeAt(j) > 127) {
- // we replace non-ASCII char with a temporary placeholder
- // we need this to make sure size of hostname is not
- // broken by replacing non-ASCII by nothing
- newpart += 'x';
- } else {
- newpart += part[j];
- }
- }
- // we test again with ASCII char only
- if (!newpart.match(hostnamePartPattern)) {
- var validParts = hostparts.slice(0, i);
- var notHost = hostparts.slice(i + 1);
- var bit = part.match(hostnamePartStart);
- if (bit) {
- validParts.push(bit[1]);
- notHost.unshift(bit[2]);
- }
- if (notHost.length) {
- rest = '/' + notHost.join('.') + rest;
- }
- this.hostname = validParts.join('.');
- break;
- }
- }
- }
+ // if lchmod/lchown do not exist, then make them no-ops
+ if (!fs.lchmod) {
+ fs.lchmod = function (path, mode, cb) {
+ process.nextTick(cb)
}
-
- if (this.hostname.length > hostnameMaxLen) {
- this.hostname = '';
- } else {
- // hostnames are always lower case.
- this.hostname = this.hostname.toLowerCase();
+ fs.lchmodSync = function () {}
+ }
+ if (!fs.lchown) {
+ fs.lchown = function (path, uid, gid, cb) {
+ process.nextTick(cb)
}
+ fs.lchownSync = function () {}
+ }
- if (!ipv6Hostname) {
- // IDNA Support: Returns a puny coded representation of "domain".
- // It only converts the part of the domain name that
- // has non ASCII characters. I.e. it dosent matter if
- // you call it with a domain that already is in ASCII.
- var domainArray = this.hostname.split('.');
- var newOut = [];
- for (var i = 0; i < domainArray.length; ++i) {
- var s = domainArray[i];
- newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
- 'xn--' + punycode.encode(s) : s);
+ // on Windows, A/V software can lock the directory, causing this
+ // to fail with an EACCES or EPERM if the directory contains newly
+ // created files. Try again on failure, for up to 1 second.
+ if (process.platform === "win32") {
+ fs.rename = (function (fs$rename) { return function (from, to, cb) {
+ var start = Date.now()
+ fs$rename(from, to, function CB (er) {
+ if (er
+ && (er.code === "EACCES" || er.code === "EPERM")
+ && Date.now() - start < 1000) {
+ return fs$rename(from, to, CB)
+ }
+ if (cb) cb(er)
+ })
+ }})(fs.rename)
+ }
+
+ // if read() returns EAGAIN, then just try it again.
+ fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) {
+ var callback
+ if (callback_ && typeof callback_ === 'function') {
+ var eagCounter = 0
+ callback = function (er, _, __) {
+ if (er && er.code === 'EAGAIN' && eagCounter < 10) {
+ eagCounter ++
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
+ }
+ callback_.apply(this, arguments)
}
- this.hostname = newOut.join('.');
}
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
+ }})(fs.read)
- var p = this.port ? ':' + this.port : '';
- var h = this.hostname || '';
- this.host = h + p;
- this.href += this.host;
-
- // strip [ and ] from the hostname
- // the host field still retains them, though
- if (ipv6Hostname) {
- this.hostname = this.hostname.substr(1, this.hostname.length - 2);
- if (rest[0] !== '/') {
- rest = '/' + rest;
+ fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
+ var eagCounter = 0
+ while (true) {
+ try {
+ return fs$readSync.call(fs, fd, buffer, offset, length, position)
+ } catch (er) {
+ if (er.code === 'EAGAIN' && eagCounter < 10) {
+ eagCounter ++
+ continue
+ }
+ throw er
}
}
+ }})(fs.readSync)
+}
+
+function patchLchmod (fs) {
+ fs.lchmod = function (path, mode, callback) {
+ callback = callback || noop
+ fs.open( path
+ , constants.O_WRONLY | constants.O_SYMLINK
+ , mode
+ , function (err, fd) {
+ if (err) {
+ callback(err)
+ return
+ }
+ // prefer to return the chmod error, if one occurs,
+ // but still try to close, and report closing errors if they occur.
+ fs.fchmod(fd, mode, function (err) {
+ fs.close(fd, function(err2) {
+ callback(err || err2)
+ })
+ })
+ })
}
- // now rest is set to the post-host stuff.
- // chop off any delim chars.
- if (!unsafeProtocol[lowerProto]) {
+ fs.lchmodSync = function (path, mode) {
+ var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
- // First, make 100% sure that any "autoEscape" chars get
- // escaped, even if encodeURIComponent doesn't think they
- // need to be.
- for (var i = 0, l = autoEscape.length; i < l; i++) {
- var ae = autoEscape[i];
- var esc = encodeURIComponent(ae);
- if (esc === ae) {
- esc = escape(ae);
+ // prefer to return the chmod error, if one occurs,
+ // but still try to close, and report closing errors if they occur.
+ var threw = true
+ var ret
+ try {
+ ret = fs.fchmodSync(fd, mode)
+ threw = false
+ } finally {
+ if (threw) {
+ try {
+ fs.closeSync(fd)
+ } catch (er) {}
+ } else {
+ fs.closeSync(fd)
}
- rest = rest.split(ae).join(esc);
}
+ return ret
}
+}
+function patchLutimes (fs) {
+ if (constants.hasOwnProperty("O_SYMLINK")) {
+ fs.lutimes = function (path, at, mt, cb) {
+ fs.open(path, constants.O_SYMLINK, function (er, fd) {
+ cb = cb || noop
+ if (er) return cb(er)
+ fs.futimes(fd, at, mt, function (er) {
+ fs.close(fd, function (er2) {
+ return cb(er || er2)
+ })
+ })
+ })
+ }
- // chop off from the tail first.
- var hash = rest.indexOf('#');
- if (hash !== -1) {
- // got a fragment string.
- this.hash = rest.substr(hash);
- rest = rest.slice(0, hash);
- }
- var qm = rest.indexOf('?');
- if (qm !== -1) {
- this.search = rest.substr(qm);
- this.query = rest.substr(qm + 1);
- if (parseQueryString) {
- this.query = querystring.parse(this.query);
+ fs.lutimesSync = function (path, at, mt) {
+ var fd = fs.openSync(path, constants.O_SYMLINK)
+ var ret
+ var threw = true
+ try {
+ ret = fs.futimesSync(fd, at, mt)
+ threw = false
+ } finally {
+ if (threw) {
+ try {
+ fs.closeSync(fd)
+ } catch (er) {}
+ } else {
+ fs.closeSync(fd)
+ }
+ }
+ return ret
}
- rest = rest.slice(0, qm);
- } else if (parseQueryString) {
- // no query string, but parseQueryString still requested
- this.search = '';
- this.query = {};
+
+ } else {
+ fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) }
+ fs.lutimesSync = function () {}
}
- if (rest) this.pathname = rest;
- if (slashedProtocol[lowerProto] &&
- this.hostname && !this.pathname) {
- this.pathname = '/';
+}
+
+function chownFix (orig) {
+ if (!orig) return orig
+ return function (target, uid, gid, cb) {
+ return orig.call(fs, target, uid, gid, function (er, res) {
+ if (chownErOk(er)) er = null
+ cb(er, res)
+ })
}
+}
- //to support http.request
- if (this.pathname || this.search) {
- var p = this.pathname || '';
- var s = this.search || '';
- this.path = p + s;
+function chownFixSync (orig) {
+ if (!orig) return orig
+ return function (target, uid, gid) {
+ try {
+ return orig.call(fs, target, uid, gid)
+ } catch (er) {
+ if (!chownErOk(er)) throw er
+ }
}
+}
- // finally, reconstruct the href based on what has been validated.
- this.href = this.format();
- return this;
-};
+// ENOSYS means that the fs doesn't support the op. Just ignore
+// that, because it doesn't matter.
+//
+// if there's no getuid, or if getuid() is something other
+// than 0, and the error is EINVAL or EPERM, then just ignore
+// it.
+//
+// This specific case is a silent failure in cp, install, tar,
+// and most other unix tools that manage permissions.
+//
+// When running as root, or if other types of errors are
+// encountered, then it's strict.
+function chownErOk (er) {
+ if (!er)
+ return true
-// format a parsed object into a url string
-function urlFormat(obj) {
- // ensure it's an object, and not a string url.
- // If it's an obj, this is a no-op.
- // this way, you can call url_format() on strings
- // to clean up potentially wonky urls.
- if (isString(obj)) obj = urlParse(obj);
- if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
- return obj.format();
-}
+ if (er.code === "ENOSYS")
+ return true
-Url.prototype.format = function() {
- var auth = this.auth || '';
- if (auth) {
- auth = encodeURIComponent(auth);
- auth = auth.replace(/%3A/i, ':');
- auth += '@';
+ var nonroot = !process.getuid || process.getuid() !== 0
+ if (nonroot) {
+ if (er.code === "EINVAL" || er.code === "EPERM")
+ return true
}
- var protocol = this.protocol || '',
- pathname = this.pathname || '',
- hash = this.hash || '',
- host = false,
- query = '';
+ return false
+}
- if (this.host) {
- host = auth + this.host;
- } else if (this.hostname) {
- host = auth + (this.hostname.indexOf(':') === -1 ?
- this.hostname :
- '[' + this.hostname + ']');
- if (this.port) {
- host += ':' + this.port;
- }
- }
+}).call(this,require('_process'))
+},{"./fs.js":33,"_process":107,"constants":13}],37:[function(require,module,exports){
+(function (Buffer){
+'use strict';
+var through = require('through2');
+var fs = require('graceful-fs');
+var path = require('path');
+var File = require('vinyl');
+var convert = require('convert-source-map');
+var stripBom = require('strip-bom');
- if (this.query &&
- isObject(this.query) &&
- Object.keys(this.query).length) {
- query = querystring.stringify(this.query);
- }
+var PLUGIN_NAME = 'gulp-sourcemap';
+var urlRegex = /^(https?|webpack(-[^:]+)?):\/\//;
- var search = this.search || (query && ('?' + query)) || '';
+/**
+ * Initialize source mapping chain
+ */
+module.exports.init = function init(options) {
+ function sourceMapInit(file, encoding, callback) {
+ /*jshint validthis:true */
- if (protocol && protocol.substr(-1) !== ':') protocol += ':';
+ // pass through if file is null or already has a source map
+ if (file.isNull() || file.sourceMap) {
+ this.push(file);
+ return callback();
+ }
- // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
- // unless they had them to begin with.
- if (this.slashes ||
- (!protocol || slashedProtocol[protocol]) && host !== false) {
- host = '//' + (host || '');
- if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
- } else if (!host) {
- host = '';
- }
+ if (file.isStream()) {
+ return callback(new Error(PLUGIN_NAME + '-init: Streaming not supported'));
+ }
- if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
- if (search && search.charAt(0) !== '?') search = '?' + search;
+ var fileContent = file.contents.toString();
+ var sourceMap;
- pathname = pathname.replace(/[?#]/g, function(match) {
- return encodeURIComponent(match);
- });
- search = search.replace('#', '%23');
+ if (options && options.loadMaps) {
+ var sourcePath = ''; //root path for the sources in the map
- return protocol + host + pathname + search + hash;
-};
+ // Try to read inline source map
+ sourceMap = convert.fromSource(fileContent);
+ if (sourceMap) {
+ sourceMap = sourceMap.toObject();
+ // sources in map are relative to the source file
+ sourcePath = path.dirname(file.path);
+ fileContent = convert.removeComments(fileContent);
+ } else {
+ // look for source map comment referencing a source map file
+ var mapComment = convert.mapFileCommentRegex.exec(fileContent);
-function urlResolve(source, relative) {
- return urlParse(source, false, true).resolve(relative);
-}
+ var mapFile;
+ if (mapComment) {
+ mapFile = path.resolve(path.dirname(file.path), mapComment[1] || mapComment[2]);
+ fileContent = convert.removeMapFileComments(fileContent);
+ // if no comment try map file with same name as source file
+ } else {
+ mapFile = file.path + '.map';
+ }
-Url.prototype.resolve = function(relative) {
- return this.resolveObject(urlParse(relative, false, true)).format();
-};
+ // sources in external map are relative to map file
+ sourcePath = path.dirname(mapFile);
-function urlResolveObject(source, relative) {
- if (!source) return relative;
- return urlParse(source, false, true).resolveObject(relative);
-}
+ try {
+ sourceMap = JSON.parse(stripBom(fs.readFileSync(mapFile, 'utf8')));
+ } catch(e) {}
+ }
-Url.prototype.resolveObject = function(relative) {
- if (isString(relative)) {
- var rel = new Url();
- rel.parse(relative, false, true);
- relative = rel;
- }
+ // fix source paths and sourceContent for imported source map
+ if (sourceMap) {
+ sourceMap.sourcesContent = sourceMap.sourcesContent || [];
+ sourceMap.sources.forEach(function(source, i) {
+ if (source.match(urlRegex)) {
+ sourceMap.sourcesContent[i] = sourceMap.sourcesContent[i] || null;
+ return;
+ }
+ var absPath = path.resolve(sourcePath, source);
+ sourceMap.sources[i] = unixStylePath(path.relative(file.base, absPath));
- var result = new Url();
- Object.keys(this).forEach(function(k) {
- result[k] = this[k];
- }, this);
+ if (!sourceMap.sourcesContent[i]) {
+ var sourceContent = null;
+ if (sourceMap.sourceRoot) {
+ if (sourceMap.sourceRoot.match(urlRegex)) {
+ sourceMap.sourcesContent[i] = null;
+ return;
+ }
+ absPath = path.resolve(sourcePath, sourceMap.sourceRoot, source);
+ }
- // hash is always overridden, no matter what.
- // even href="" will remove it.
- result.hash = relative.hash;
+ // if current file: use content
+ if (absPath === file.path) {
+ sourceContent = fileContent;
- // if the relative url is empty, then there's nothing left to do here.
- if (relative.href === '') {
- result.href = result.format();
- return result;
- }
+ // else load content from file
+ } else {
+ try {
+ if (options.debug)
+ console.log(PLUGIN_NAME + '-init: No source content for "' + source + '". Loading from file.');
+ sourceContent = stripBom(fs.readFileSync(absPath, 'utf8'));
+ } catch (e) {
+ if (options.debug)
+ console.warn(PLUGIN_NAME + '-init: source file not found: ' + absPath);
+ }
+ }
+ sourceMap.sourcesContent[i] = sourceContent;
+ }
+ });
- // hrefs like //foo/bar always cut to the protocol.
- if (relative.slashes && !relative.protocol) {
- // take everything except the protocol from relative
- Object.keys(relative).forEach(function(k) {
- if (k !== 'protocol')
- result[k] = relative[k];
- });
+ // remove source map comment from source
+ file.contents = new Buffer(fileContent, 'utf8');
+ }
+ }
- //urlParse appends trailing / to urls like http://www.example.com
- if (slashedProtocol[result.protocol] &&
- result.hostname && !result.pathname) {
- result.path = result.pathname = '/';
+ if (!sourceMap) {
+ // Make an empty source map
+ sourceMap = {
+ version : 3,
+ names: [],
+ mappings: '',
+ sources: [unixStylePath(file.relative)],
+ sourcesContent: [fileContent]
+ };
}
- result.href = result.format();
- return result;
+ sourceMap.file = unixStylePath(file.relative);
+ file.sourceMap = sourceMap;
+
+ this.push(file);
+ callback();
}
- if (relative.protocol && relative.protocol !== result.protocol) {
- // if it's a known url protocol, then changing
- // the protocol does weird things
- // first, if it's not file:, then we MUST have a host,
- // and if there was a path
- // to begin with, then we MUST have a path.
- // if it is file:, then the host is dropped,
- // because that's known to be hostless.
- // anything else is assumed to be absolute.
- if (!slashedProtocol[relative.protocol]) {
- Object.keys(relative).forEach(function(k) {
- result[k] = relative[k];
- });
- result.href = result.format();
- return result;
- }
+ return through.obj(sourceMapInit);
+};
- result.protocol = relative.protocol;
- if (!relative.host && !hostlessProtocol[relative.protocol]) {
- var relPath = (relative.pathname || '').split('/');
- while (relPath.length && !(relative.host = relPath.shift()));
- if (!relative.host) relative.host = '';
- if (!relative.hostname) relative.hostname = '';
- if (relPath[0] !== '') relPath.unshift('');
- if (relPath.length < 2) relPath.unshift('');
- result.pathname = relPath.join('/');
- } else {
- result.pathname = relative.pathname;
- }
- result.search = relative.search;
- result.query = relative.query;
- result.host = relative.host || '';
- result.auth = relative.auth;
- result.hostname = relative.hostname || relative.host;
- result.port = relative.port;
- // to support http.request
- if (result.pathname || result.search) {
- var p = result.pathname || '';
- var s = result.search || '';
- result.path = p + s;
- }
- result.slashes = result.slashes || relative.slashes;
- result.href = result.format();
- return result;
+/**
+ * Write the source map
+ *
+ * @param options options to change the way the source map is written
+ *
+ */
+module.exports.write = function write(destPath, options) {
+ if (options === undefined && Object.prototype.toString.call(destPath) === '[object Object]') {
+ options = destPath;
+ destPath = undefined;
}
+ options = options || {};
- var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
- isRelAbs = (
- relative.host ||
- relative.pathname && relative.pathname.charAt(0) === '/'
- ),
- mustEndAbs = (isRelAbs || isSourceAbs ||
- (result.host && relative.pathname)),
- removeAllDots = mustEndAbs,
- srcPath = result.pathname && result.pathname.split('/') || [],
- relPath = relative.pathname && relative.pathname.split('/') || [],
- psychotic = result.protocol && !slashedProtocol[result.protocol];
+ // set defaults for options if unset
+ if (options.includeContent === undefined)
+ options.includeContent = true;
+ if (options.addComment === undefined)
+ options.addComment = true;
- // if the url is a non-slashed url, then relative
- // links like ../.. should be able
- // to crawl up to the hostname, as well. This is strange.
- // result.protocol has already been set by now.
- // Later on, put the first path part into the host field.
- if (psychotic) {
- result.hostname = '';
- result.port = null;
- if (result.host) {
- if (srcPath[0] === '') srcPath[0] = result.host;
- else srcPath.unshift(result.host);
- }
- result.host = '';
- if (relative.protocol) {
- relative.hostname = null;
- relative.port = null;
- if (relative.host) {
- if (relPath[0] === '') relPath[0] = relative.host;
- else relPath.unshift(relative.host);
- }
- relative.host = null;
- }
- mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
- }
+ function sourceMapWrite(file, encoding, callback) {
+ /*jshint validthis:true */
- if (isRelAbs) {
- // it's absolute.
- result.host = (relative.host || relative.host === '') ?
- relative.host : result.host;
- result.hostname = (relative.hostname || relative.hostname === '') ?
- relative.hostname : result.hostname;
- result.search = relative.search;
- result.query = relative.query;
- srcPath = relPath;
- // fall through to the dot-handling below.
- } else if (relPath.length) {
- // it's relative
- // throw away the existing file, and take the new path instead.
- if (!srcPath) srcPath = [];
- srcPath.pop();
- srcPath = srcPath.concat(relPath);
- result.search = relative.search;
- result.query = relative.query;
- } else if (!isNullOrUndefined(relative.search)) {
- // just pull out the search.
- // like href='?foo'.
- // Put this after the other two cases because it simplifies the booleans
- if (psychotic) {
- result.hostname = result.host = srcPath.shift();
- //occationaly the auth can get stuck only in host
- //this especialy happens in cases like
- //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
- var authInHost = result.host && result.host.indexOf('@') > 0 ?
- result.host.split('@') : false;
- if (authInHost) {
- result.auth = authInHost.shift();
- result.host = result.hostname = authInHost.shift();
- }
+ if (file.isNull() || !file.sourceMap) {
+ this.push(file);
+ return callback();
}
- result.search = relative.search;
- result.query = relative.query;
- //to support http.request
- if (!isNull(result.pathname) || !isNull(result.search)) {
- result.path = (result.pathname ? result.pathname : '') +
- (result.search ? result.search : '');
+
+ if (file.isStream()) {
+ return callback(new Error(PLUGIN_NAME + '-write: Streaming not supported'));
}
- result.href = result.format();
- return result;
- }
- if (!srcPath.length) {
- // no path at all. easy.
- // we've already handled the other stuff above.
- result.pathname = null;
- //to support http.request
- if (result.search) {
- result.path = '/' + result.search;
+ var sourceMap = file.sourceMap;
+ // fix paths if Windows style paths
+ sourceMap.file = unixStylePath(file.relative);
+ sourceMap.sources = sourceMap.sources.map(function(filePath) {
+ return unixStylePath(filePath);
+ });
+
+ if (typeof options.sourceRoot === 'function') {
+ sourceMap.sourceRoot = options.sourceRoot(file);
} else {
- result.path = null;
+ sourceMap.sourceRoot = options.sourceRoot;
}
- result.href = result.format();
- return result;
- }
- // if a url ENDs in . or .., then it must get a trailing slash.
- // however, if it ends in anything else non-slashy,
- // then it must NOT get a trailing slash.
- var last = srcPath.slice(-1)[0];
- var hasTrailingSlash = (
- (result.host || relative.host) && (last === '.' || last === '..') ||
- last === '');
+ if (options.includeContent) {
+ sourceMap.sourcesContent = sourceMap.sourcesContent || [];
- // strip single dots, resolve double dots to parent dir
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = srcPath.length; i >= 0; i--) {
- last = srcPath[i];
- if (last == '.') {
- srcPath.splice(i, 1);
- } else if (last === '..') {
- srcPath.splice(i, 1);
- up++;
- } else if (up) {
- srcPath.splice(i, 1);
- up--;
+ // load missing source content
+ for (var i = 0; i < file.sourceMap.sources.length; i++) {
+ if (!sourceMap.sourcesContent[i]) {
+ var sourcePath = path.resolve(sourceMap.sourceRoot || file.base, sourceMap.sources[i]);
+ try {
+ if (options.debug)
+ console.log(PLUGIN_NAME + '-write: No source content for "' + sourceMap.sources[i] + '". Loading from file.');
+ sourceMap.sourcesContent[i] = stripBom(fs.readFileSync(sourcePath, 'utf8'));
+ } catch (e) {
+ if (options.debug)
+ console.warn(PLUGIN_NAME + '-write: source file not found: ' + sourcePath);
+ }
+ }
+ }
+ if (sourceMap.sourceRoot === undefined) {
+ sourceMap.sourceRoot = '/source/';
+ } else if (sourceMap.sourceRoot === null) {
+ sourceMap.sourceRoot = undefined;
+ }
+ } else {
+ delete sourceMap.sourcesContent;
}
- }
- // if the path is allowed to go above the root, restore leading ..s
- if (!mustEndAbs && !removeAllDots) {
- for (; up--; up) {
- srcPath.unshift('..');
+ var extension = file.relative.split('.').pop();
+ var commentFormatter;
+
+ switch (extension) {
+ case 'css':
+ commentFormatter = function(url) { return "\n/*# sourceMappingURL=" + url + " */\n"; };
+ break;
+ case 'js':
+ commentFormatter = function(url) { return "\n//# sourceMappingURL=" + url + "\n"; };
+ break;
+ default:
+ commentFormatter = function(url) { return ""; };
}
- }
- if (mustEndAbs && srcPath[0] !== '' &&
- (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
- srcPath.unshift('');
- }
+ var comment, sourceMappingURLPrefix;
+ if (!destPath) {
+ // encode source map into comment
+ var base64Map = new Buffer(JSON.stringify(sourceMap)).toString('base64');
+ comment = commentFormatter('data:application/json;base64,' + base64Map);
+ } else {
+ var sourceMapPath = path.join(file.base, destPath, file.relative) + '.map';
+ // add new source map file to stream
+ var sourceMapFile = new File({
+ cwd: file.cwd,
+ base: file.base,
+ path: sourceMapPath,
+ contents: new Buffer(JSON.stringify(sourceMap)),
+ stat: {
+ isFile: function () { return true; },
+ isDirectory: function () { return false; },
+ isBlockDevice: function () { return false; },
+ isCharacterDevice: function () { return false; },
+ isSymbolicLink: function () { return false; },
+ isFIFO: function () { return false; },
+ isSocket: function () { return false; }
+ }
+ });
+ this.push(sourceMapFile);
- if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
- srcPath.push('');
- }
+ var sourceMapPathRelative = path.relative(path.dirname(file.path), sourceMapPath);
- var isAbsolute = srcPath[0] === '' ||
- (srcPath[0] && srcPath[0].charAt(0) === '/');
+ if (options.sourceMappingURLPrefix) {
+ var prefix = '';
+ if (typeof options.sourceMappingURLPrefix === 'function') {
+ prefix = options.sourceMappingURLPrefix(file);
+ } else {
+ prefix = options.sourceMappingURLPrefix;
+ }
+ sourceMapPathRelative = prefix+path.join('/', sourceMapPathRelative);
+ }
+ comment = commentFormatter(unixStylePath(sourceMapPathRelative));
- // put the host back
- if (psychotic) {
- result.hostname = result.host = isAbsolute ? '' :
- srcPath.length ? srcPath.shift() : '';
- //occationaly the auth can get stuck only in host
- //this especialy happens in cases like
- //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
- var authInHost = result.host && result.host.indexOf('@') > 0 ?
- result.host.split('@') : false;
- if (authInHost) {
- result.auth = authInHost.shift();
- result.host = result.hostname = authInHost.shift();
+ if (options.sourceMappingURL && typeof options.sourceMappingURL === 'function') {
+ comment = commentFormatter(options.sourceMappingURL(file));
+ }
}
- }
- mustEndAbs = mustEndAbs || (result.host && srcPath.length);
-
- if (mustEndAbs && !isAbsolute) {
- srcPath.unshift('');
- }
+ // append source map comment
+ if (options.addComment)
+ file.contents = Buffer.concat([file.contents, new Buffer(comment)]);
- if (!srcPath.length) {
- result.pathname = null;
- result.path = null;
- } else {
- result.pathname = srcPath.join('/');
+ this.push(file);
+ callback();
}
- //to support request.http
- if (!isNull(result.pathname) || !isNull(result.search)) {
- result.path = (result.pathname ? result.pathname : '') +
- (result.search ? result.search : '');
- }
- result.auth = relative.auth || result.auth;
- result.slashes = result.slashes || relative.slashes;
- result.href = result.format();
- return result;
+ return through.obj(sourceMapWrite);
};
-Url.prototype.parseHost = function() {
- var host = this.host;
- var port = portPattern.exec(host);
- if (port) {
- port = port[0];
- if (port !== ':') {
- this.port = port.substr(1);
- }
- host = host.substr(0, host.length - port.length);
+function unixStylePath(filePath) {
+ return filePath.split(path.sep).join('/');
+}
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":8,"convert-source-map":14,"graceful-fs":34,"path":104,"strip-bom":131,"through2":133,"vinyl":38}],38:[function(require,module,exports){
+(function (process){
+var path = require('path');
+var clone = require('clone');
+var cloneStats = require('clone-stats');
+var cloneBuffer = require('./lib/cloneBuffer');
+var isBuffer = require('./lib/isBuffer');
+var isStream = require('./lib/isStream');
+var isNull = require('./lib/isNull');
+var inspectStream = require('./lib/inspectStream');
+var Stream = require('stream');
+var replaceExt = require('replace-ext');
+
+function File(file) {
+ if (!file) {
+ file = {};
}
- if (host) this.hostname = host;
-};
-function isString(arg) {
- return typeof arg === "string";
-}
+ // Record path change
+ var history = file.path ? [file.path] : file.history;
+ this.history = history || [];
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
+ this.cwd = file.cwd || process.cwd();
+ this.base = file.base || this.cwd;
-function isNull(arg) {
- return arg === null;
-}
-function isNullOrUndefined(arg) {
- return arg == null;
+ // Stat = files stats object
+ this.stat = file.stat || null;
+
+ // Contents = stream, buffer, or null if not read
+ this.contents = file.contents || null;
+
+ this._isVinyl = true;
}
-},{"punycode":65,"querystring":68}],88:[function(require,module,exports){
-(function (global){
+File.prototype.isBuffer = function() {
+ return isBuffer(this.contents);
+};
-/**
- * Module exports.
- */
+File.prototype.isStream = function() {
+ return isStream(this.contents);
+};
-module.exports = deprecate;
+File.prototype.isNull = function() {
+ return isNull(this.contents);
+};
-/**
- * Mark that a method should not be used.
- * Returns a modified function which warns once by default.
- *
- * If `localStorage.noDeprecation = true` is set, then it is a no-op.
- *
- * If `localStorage.throwDeprecation = true` is set, then deprecated functions
- * will throw an Error when invoked.
- *
- * If `localStorage.traceDeprecation = true` is set, then deprecated functions
- * will invoke `console.trace()` instead of `console.error()`.
- *
- * @param {Function} fn - the function to deprecate
- * @param {String} msg - the string to print to the console when `fn` is invoked
- * @returns {Function} a new "deprecated" version of `fn`
- * @api public
- */
+// TODO: Should this be moved to vinyl-fs?
+File.prototype.isDirectory = function() {
+ return this.isNull() && this.stat && this.stat.isDirectory();
+};
-function deprecate (fn, msg) {
- if (config('noDeprecation')) {
- return fn;
+File.prototype.clone = function(opt) {
+ if (typeof opt === 'boolean') {
+ opt = {
+ deep: opt,
+ contents: true,
+ };
+ } else if (!opt) {
+ opt = {
+ deep: true,
+ contents: true,
+ };
+ } else {
+ opt.deep = opt.deep === true;
+ opt.contents = opt.contents !== false;
}
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (config('throwDeprecation')) {
- throw new Error(msg);
- } else if (config('traceDeprecation')) {
- console.trace(msg);
- } else {
- console.warn(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
+ // Clone our file contents
+ var contents;
+ if (this.isStream()) {
+ contents = this.contents.pipe(new Stream.PassThrough());
+ this.contents = this.contents.pipe(new Stream.PassThrough());
+ } else if (this.isBuffer()) {
+ contents = opt.contents ? cloneBuffer(this.contents) : this.contents;
}
- return deprecated;
-}
-
-/**
- * Checks `localStorage` for boolean values for the given `name`.
- *
- * @param {String} name
- * @returns {Boolean}
- * @api private
- */
-
-function config (name) {
- if (!global.localStorage) return false;
- var val = global.localStorage[name];
- if (null == val) return false;
- return String(val).toLowerCase() === 'true';
-}
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],89:[function(require,module,exports){
-module.exports = function isBuffer(arg) {
- return arg && typeof arg === 'object'
- && typeof arg.copy === 'function'
- && typeof arg.fill === 'function'
- && typeof arg.readUInt8 === 'function';
-}
-},{}],90:[function(require,module,exports){
-(function (process,global){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+ var file = new File({
+ cwd: this.cwd,
+ base: this.base,
+ stat: (this.stat ? cloneStats(this.stat) : null),
+ history: this.history.slice(),
+ contents: contents,
+ });
-var formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
+ // Clone our custom properties
+ Object.keys(this).forEach(function(key) {
+ // Ignore built-in fields
+ if (key === '_contents' || key === 'stat' ||
+ key === 'history' || key === 'path' ||
+ key === 'base' || key === 'cwd') {
+ return;
}
- return objects.join(' ');
+ file[key] = opt.deep ? clone(this[key], true) : this[key];
+ }, this);
+ return file;
+};
+
+File.prototype.pipe = function(stream, opt) {
+ if (!opt) {
+ opt = {};
+ }
+ if (typeof opt.end === 'undefined') {
+ opt.end = true;
}
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
+ if (this.isStream()) {
+ return this.contents.pipe(stream, opt);
+ }
+ if (this.isBuffer()) {
+ if (opt.end) {
+ stream.end(this.contents);
} else {
- str += ' ' + inspect(x);
+ stream.write(this.contents);
}
+ return stream;
}
- return str;
+
+ // Check if isNull
+ if (opt.end) {
+ stream.end();
+ }
+ return stream;
};
+File.prototype.inspect = function() {
+ var inspect = [];
-// Mark that a method should not be used.
-// Returns a modified function which warns once by default.
-// If --no-deprecation is set, then it is a no-op.
-exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
+ // Use relative path if possible
+ var filePath = (this.base && this.path) ? this.relative : this.path;
+
+ if (filePath) {
+ inspect.push('"' + filePath + '"');
}
- if (process.noDeprecation === true) {
- return fn;
+ if (this.isBuffer()) {
+ inspect.push(this.contents.inspect());
}
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
+ if (this.isStream()) {
+ inspect.push(inspectStream(this.contents));
}
- return deprecated;
+ return '';
};
+File.isVinyl = function(file) {
+ return file && file._isVinyl === true;
+};
-var debugs = {};
-var debugEnviron;
-exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
+// Virtual attributes
+// Or stuff with extra logic
+Object.defineProperty(File.prototype, 'contents', {
+ get: function() {
+ return this._contents;
+ },
+ set: function(val) {
+ if (!isBuffer(val) && !isStream(val) && !isNull(val)) {
+ throw new Error('File.contents can only be a Buffer, a Stream, or null.');
}
- }
- return debugs[set];
-};
+ this._contents = val;
+ },
+});
+// TODO: Should this be moved to vinyl-fs?
+Object.defineProperty(File.prototype, 'relative', {
+ get: function() {
+ if (!this.base) {
+ throw new Error('No base specified! Can not get relative.');
+ }
+ if (!this.path) {
+ throw new Error('No path specified! Can not get relative.');
+ }
+ return path.relative(this.base, this.path);
+ },
+ set: function() {
+ throw new Error('File.relative is generated from the base and path attributes. Do not modify it.');
+ },
+});
-/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
-/* legacy: obj, showHidden, depth, colors*/
-function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
-}
-exports.inspect = inspect;
+Object.defineProperty(File.prototype, 'dirname', {
+ get: function() {
+ if (!this.path) {
+ throw new Error('No path specified! Can not get dirname.');
+ }
+ return path.dirname(this.path);
+ },
+ set: function(dirname) {
+ if (!this.path) {
+ throw new Error('No path specified! Can not set dirname.');
+ }
+ this.path = path.join(dirname, path.basename(this.path));
+ },
+});
+Object.defineProperty(File.prototype, 'basename', {
+ get: function() {
+ if (!this.path) {
+ throw new Error('No path specified! Can not get basename.');
+ }
+ return path.basename(this.path);
+ },
+ set: function(basename) {
+ if (!this.path) {
+ throw new Error('No path specified! Can not set basename.');
+ }
+ this.path = path.join(path.dirname(this.path), basename);
+ },
+});
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
-inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
-};
+// Property for getting/setting stem of the filename.
+Object.defineProperty(File.prototype, 'stem', {
+ get: function() {
+ if (!this.path) {
+ throw new Error('No path specified! Can not get stem.');
+ }
+ return path.basename(this.path, this.extname);
+ },
+ set: function(stem) {
+ if (!this.path) {
+ throw new Error('No PassThrough specified! Can not set stem.');
+ }
+ this.path = path.join(path.dirname(this.path), stem + this.extname);
+ },
+});
-// Don't use 'blue' not visible on cmd.exe
-inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
-};
+Object.defineProperty(File.prototype, 'extname', {
+ get: function() {
+ if (!this.path) {
+ throw new Error('No path specified! Can not get extname.');
+ }
+ return path.extname(this.path);
+ },
+ set: function(extname) {
+ if (!this.path) {
+ throw new Error('No path specified! Can not set extname.');
+ }
+ this.path = replaceExt(this.path, extname);
+ },
+});
+Object.defineProperty(File.prototype, 'path', {
+ get: function() {
+ return this.history[this.history.length - 1];
+ },
+ set: function(path) {
+ if (typeof path !== 'string') {
+ throw new Error('path should be string');
+ }
-function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
+ // Record history only when path changed
+ if (path && path !== this.path) {
+ this.history.push(path);
+ }
+ },
+});
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
-}
+module.exports = File;
+}).call(this,require('_process'))
+},{"./lib/cloneBuffer":39,"./lib/inspectStream":40,"./lib/isBuffer":41,"./lib/isNull":42,"./lib/isStream":43,"_process":107,"clone":11,"clone-stats":10,"path":104,"replace-ext":122,"stream":124}],39:[function(require,module,exports){
+var Buffer = require('buffer').Buffer;
-function stylizeNoColor(str, styleType) {
- return str;
-}
+module.exports = function(buf) {
+ var out = new Buffer(buf.length);
+ buf.copy(out);
+ return out;
+};
+},{"buffer":8}],40:[function(require,module,exports){
+var isStream = require('./isStream');
-function arrayToHash(array) {
- var hash = {};
+module.exports = function(stream) {
+ if (!isStream(stream)) {
+ return;
+ }
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
+ var streamType = stream.constructor.name;
+ // Avoid StreamStream
+ if (streamType === 'Stream') {
+ streamType = '';
+ }
- return hash;
-}
+ return '<' + streamType + 'Stream>';
+};
+},{"./isStream":43}],41:[function(require,module,exports){
+module.exports = require('buffer').Buffer.isBuffer;
-function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
+},{"buffer":8}],42:[function(require,module,exports){
+module.exports = function(v) {
+ return v === null;
+};
+
+},{}],43:[function(require,module,exports){
+var Stream = require('stream').Stream;
+
+module.exports = function(o) {
+ return !!o && o instanceof Stream;
+};
+
+},{"stream":124}],44:[function(require,module,exports){
+exports.read = function (buffer, offset, isLE, mLen, nBytes) {
+ var e, m
+ var eLen = nBytes * 8 - mLen - 1
+ var eMax = (1 << eLen) - 1
+ var eBias = eMax >> 1
+ var nBits = -7
+ var i = isLE ? (nBytes - 1) : 0
+ var d = isLE ? -1 : 1
+ var s = buffer[offset + i]
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
+ i += d
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
+ e = s & ((1 << (-nBits)) - 1)
+ s >>= (-nBits)
+ nBits += eLen
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
+ m = e & ((1 << (-nBits)) - 1)
+ e >>= (-nBits)
+ nBits += mLen
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
- // IE doesn't make error fields non-enumerable
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
- if (isError(value)
- && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
- return formatError(value);
+ if (e === 0) {
+ e = 1 - eBias
+ } else if (e === eMax) {
+ return m ? NaN : ((s ? -1 : 1) * Infinity)
+ } else {
+ m = m + Math.pow(2, mLen)
+ e = e - eBias
}
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
+}
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
+exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
+ var e, m, c
+ var eLen = nBytes * 8 - mLen - 1
+ var eMax = (1 << eLen) - 1
+ var eBias = eMax >> 1
+ var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
+ var i = isLE ? 0 : (nBytes - 1)
+ var d = isLE ? 1 : -1
+ var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
+
+ value = Math.abs(value)
+
+ if (isNaN(value) || value === Infinity) {
+ m = isNaN(value) ? 1 : 0
+ e = eMax
+ } else {
+ e = Math.floor(Math.log(value) / Math.LN2)
+ if (value * (c = Math.pow(2, -e)) < 1) {
+ e--
+ c *= 2
}
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+ if (e + eBias >= 1) {
+ value += rt / c
+ } else {
+ value += rt * Math.pow(2, 1 - eBias)
}
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
+ if (value * c >= 2) {
+ e++
+ c /= 2
}
- if (isError(value)) {
- return formatError(value);
+
+ if (e + eBias >= eMax) {
+ m = 0
+ e = eMax
+ } else if (e + eBias >= 1) {
+ m = (value * c - 1) * Math.pow(2, mLen)
+ e = e + eBias
+ } else {
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
+ e = 0
}
}
- var base = '', array = false, braces = ['{', '}'];
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
+ e = (e << mLen) | m
+ eLen += mLen
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
+ buffer[offset + i - d] |= s * 128
+}
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
+},{}],45:[function(require,module,exports){
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
+var indexOf = [].indexOf;
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
+module.exports = function(arr, obj){
+ if (indexOf) return arr.indexOf(obj);
+ for (var i = 0; i < arr.length; ++i) {
+ if (arr[i] === obj) return i;
}
+ return -1;
+};
+},{}],46:[function(require,module,exports){
+(function (process){
+var wrappy = require('wrappy')
+var reqs = Object.create(null)
+var once = require('once')
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
+module.exports = wrappy(inflight)
+
+function inflight (key, cb) {
+ if (reqs[key]) {
+ reqs[key].push(cb)
+ return null
+ } else {
+ reqs[key] = [cb]
+ return makeres(key)
}
+}
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+function makeres (key) {
+ return once(function RES () {
+ var cbs = reqs[key]
+ var len = cbs.length
+ var args = slice(arguments)
+ for (var i = 0; i < len; i++) {
+ cbs[i].apply(null, args)
+ }
+ if (cbs.length > len) {
+ // added more in the interim.
+ // de-zalgo, just in case, but don't call again.
+ cbs.splice(0, len)
+ process.nextTick(function () {
+ RES.apply(null, args)
+ })
} else {
- return ctx.stylize('[Object]', 'special');
+ delete reqs[key]
}
- }
-
- ctx.seen.push(value);
-
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
+ })
+}
- ctx.seen.pop();
+function slice (args) {
+ var length = args.length
+ var array = []
- return reduceToSingleString(output, base, braces);
+ for (var i = 0; i < length; i++) array[i] = args[i]
+ return array
}
-
-function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
+}).call(this,require('_process'))
+},{"_process":107,"once":95,"wrappy":173}],47:[function(require,module,exports){
+if (typeof Object.create === 'function') {
+ // implementation from standard node.js 'util' module
+ module.exports = function inherits(ctor, superCtor) {
+ ctor.super_ = superCtor
+ ctor.prototype = Object.create(superCtor.prototype, {
+ constructor: {
+ value: ctor,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+ });
+ };
+} else {
+ // old school shim for old browsers
+ module.exports = function inherits(ctor, superCtor) {
+ ctor.super_ = superCtor
+ var TempCtor = function () {}
+ TempCtor.prototype = superCtor.prototype
+ ctor.prototype = new TempCtor()
+ ctor.prototype.constructor = ctor
}
- if (isNumber(value))
- return ctx.stylize('' + value, 'number');
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
}
+},{}],48:[function(require,module,exports){
+var ip = exports,
+ Buffer = require('buffer').Buffer,
+ os = require('os');
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
-}
-
+ip.toBuffer = function toBuffer(ip, buff, offset) {
+ offset = ~~offset;
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
-}
+ var result;
+ if (/^(\d{1,3}\.){3,3}\d{1,3}$/.test(ip)) {
+ result = buff || new Buffer(offset + 4);
+ ip.split(/\./g).map(function(byte) {
+ result[offset++] = parseInt(byte, 10) & 0xff;
+ });
+ } else if (/^[a-f0-9:]+$/.test(ip)) {
+ var s = ip.split(/::/g, 2),
+ head = (s[0] || '').split(/:/g, 8),
+ tail = (s[1] || '').split(/:/g, 8);
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
+ if (tail.length === 0) {
+ // xxxx::
+ while (head.length < 8) head.push('0000');
+ } else if (head.length === 0) {
+ // ::xxxx
+ while (tail.length < 8) tail.unshift('0000');
} else {
- str = ctx.stylize('[Getter]', 'special');
+ // xxxx::xxxx
+ while (head.length + tail.length < 8) head.push('0000');
}
+
+ result = buff || new Buffer(offset + 16);
+ head.concat(tail).map(function(word) {
+ word = parseInt(word, 16);
+ result[offset++] = (word >> 8) & 0xff;
+ result[offset++] = word & 0xff;
+ });
} else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
+ throw Error('Invalid ip address: ' + ip);
}
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
+
+ return result;
+};
+
+ip.toString = function toString(buff, offset, length) {
+ offset = ~~offset;
+ length = length || (buff.length - offset);
+
+ var result = [];
+ if (length === 4) {
+ // IPv4
+ for (var i = 0; i < length; i++) {
+ result.push(buff[offset + i]);
}
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
+ result = result.join('.');
+ } else if (length === 16) {
+ // IPv6
+ for (var i = 0; i < length; i += 2) {
+ result.push(buff.readUInt16BE(offset + i).toString(16));
}
+ result = result.join(':');
+ result = result.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3');
+ result = result.replace(/:{3,4}/, '::');
}
- return name + ': ' + str;
-}
-
+ return result;
+};
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
+ip.fromPrefixLen = function fromPrefixLen(prefixlen, family) {
+ if (prefixlen > 32) {
+ family = 'ipv6';
+ } else {
+ family = _normalizeFamily(family);
+ }
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
+ var len = 4;
+ if (family === 'ipv6') {
+ len = 16;
}
+ var buff = new Buffer(len);
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
+ for (var i = 0, n = buff.length; i < n; ++i) {
+ var bits = 8;
+ if (prefixlen < 8) {
+ bits = prefixlen;
+ }
+ prefixlen -= bits;
+ buff[i] = ~(0xff >> bits);
+ }
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
-function isArray(ar) {
- return Array.isArray(ar);
-}
-exports.isArray = isArray;
+ return ip.toString(buff);
+};
-function isBoolean(arg) {
- return typeof arg === 'boolean';
-}
-exports.isBoolean = isBoolean;
+ip.mask = function mask(addr, mask) {
+ addr = ip.toBuffer(addr);
+ mask = ip.toBuffer(mask);
-function isNull(arg) {
- return arg === null;
-}
-exports.isNull = isNull;
+ var result = new Buffer(Math.max(addr.length, mask.length));
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
+ // Same protocol - do bitwise and
+ if (addr.length === mask.length) {
+ for (var i = 0; i < addr.length; i++) {
+ result[i] = addr[i] & mask[i];
+ }
+ } else if (mask.length === 4) {
+ // IPv6 address and IPv4 mask
+ // (Mask low bits)
+ for (var i = 0; i < mask.length; i++) {
+ result[i] = addr[addr.length - 4 + i] & mask[i];
+ }
+ } else {
+ // IPv6 mask and IPv4 addr
+ for (var i = 0; i < result.length - 6; i++) {
+ result[i] = 0;
+ }
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-exports.isNumber = isNumber;
+ // ::ffff:ipv4
+ result[10] = 0xff;
+ result[11] = 0xff;
+ for (var i = 0; i < addr.length; i++) {
+ result[i + 12] = addr[i] & mask[i + 12];
+ }
+ }
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
+ return ip.toString(result);
+};
-function isSymbol(arg) {
- return typeof arg === 'symbol';
-}
-exports.isSymbol = isSymbol;
+ip.cidr = function cidr(cidrString) {
+ var cidrParts = cidrString.split('/');
-function isUndefined(arg) {
- return arg === void 0;
-}
-exports.isUndefined = isUndefined;
+ if (cidrParts.length != 2)
+ throw new Error('invalid CIDR subnet: ' + addr);
-function isRegExp(re) {
- return isObject(re) && objectToString(re) === '[object RegExp]';
-}
-exports.isRegExp = isRegExp;
+ var addr = cidrParts[0];
+ var mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10));
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
+ return ip.mask(addr, mask);
}
-exports.isObject = isObject;
-function isDate(d) {
- return isObject(d) && objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
+ip.subnet = function subnet(addr, mask) {
+ var networkAddress = ip.toLong(ip.mask(addr, mask));
-function isError(e) {
- return isObject(e) &&
- (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
+ // Calculate the mask's length.
+ var maskBuffer = ip.toBuffer(mask);
+ var maskLength = 0;
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-exports.isFunction = isFunction;
+ for (var i = 0; i < maskBuffer.length; i++) {
+ if (maskBuffer[i] == 0xff) {
+ maskLength += 8;
+ } else {
+ var octet = maskBuffer[i] & 0xff;
+ while (octet) {
+ octet = (octet << 1) & 0xff;
+ maskLength++;
+ }
+ }
+ }
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
+ var numberOfAddresses = Math.pow(2, 32 - maskLength);
+
+ return {
+ networkAddress: ip.fromLong(networkAddress),
+ firstAddress: numberOfAddresses <= 2 ?
+ ip.fromLong(networkAddress) :
+ ip.fromLong(networkAddress + 1),
+ lastAddress: numberOfAddresses <= 2 ?
+ ip.fromLong(networkAddress + numberOfAddresses - 1) :
+ ip.fromLong(networkAddress + numberOfAddresses - 2),
+ broadcastAddress: ip.fromLong(networkAddress + numberOfAddresses - 1),
+ subnetMask: mask,
+ subnetMaskLength: maskLength,
+ numHosts: numberOfAddresses <= 2 ?
+ numberOfAddresses : numberOfAddresses - 2,
+ length: numberOfAddresses
+ };
}
-exports.isPrimitive = isPrimitive;
-exports.isBuffer = require('./support/isBuffer');
+ip.cidrSubnet = function cidrSubnet(cidrString) {
+ var cidrParts = cidrString.split('/');
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
+ if (cidrParts.length !== 2)
+ throw new Error('invalid CIDR subnet: ' + addr);
+ var addr = cidrParts[0];
+ var mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10));
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
+ return ip.subnet(addr, mask);
}
+ip.not = function not(addr) {
+ var buff = ip.toBuffer(addr);
+ for (var i = 0; i < buff.length; i++) {
+ buff[i] = 0xff ^ buff[i];
+ }
+ return ip.toString(buff);
+};
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
+ip.or = function or(a, b) {
+ a = ip.toBuffer(a);
+ b = ip.toBuffer(b);
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
-}
+ // same protocol
+ if (a.length == b.length) {
+ for (var i = 0; i < a.length; ++i) {
+ a[i] |= b[i];
+ }
+ return ip.toString(a);
+
+ // mixed protocols
+ } else {
+ var buff = a;
+ var other = b;
+ if (b.length > a.length) {
+ buff = b;
+ other = a;
+ }
+ var offset = buff.length - other.length;
+ for (var i = offset; i < buff.length; ++i) {
+ buff[i] |= other[i - offset];
+ }
-// log is just a thin wrapper to console.log that prepends a timestamp
-exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
+ return ip.toString(buff);
+ }
};
+ip.isEqual = function isEqual(a, b) {
+ a = ip.toBuffer(a);
+ b = ip.toBuffer(b);
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
-exports.inherits = require('inherits');
+ // Same protocol
+ if (a.length === b.length) {
+ for (var i = 0; i < a.length; i++) {
+ if (a[i] !== b[i]) return false;
+ }
+ return true;
+ }
-exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
+ // Swap
+ if (b.length === 4) {
+ var t = b;
+ b = a;
+ a = t;
+ }
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
+ // a - IPv4, b - IPv6
+ for (var i = 0; i < 10; i++) {
+ if (b[i] !== 0) return false;
}
- return origin;
+
+ var word = b.readUInt16BE(10);
+ if (word !== 0 && word !== 0xffff) return false;
+
+ for (var i = 0; i < 4; i++) {
+ if (a[i] !== b[i + 12]) return false;
+ }
+
+ return true;
};
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
+ip.isPrivate = function isPrivate(addr) {
+ return addr.match(/^10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
+ addr.match(/^192\.168\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
+ addr.match(
+ /^172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
+ addr.match(/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
+ addr.match(/^169\.254\.([0-9]{1,3})\.([0-9]{1,3})/) != null ||
+ addr.match(/^fc00:/) != null || addr.match(/^fe80:/) != null ||
+ addr.match(/^::1$/) != null || addr.match(/^::$/) != null;
+};
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./support/isBuffer":89,"_process":64,"inherits":18}],91:[function(require,module,exports){
-var Path = require('path')
+ip.isPublic = function isPublic(addr) {
+ return !ip.isPrivate(addr);
+}
-module.exports = collect
+ip.isLoopback = function isLoopback(addr) {
+ return /^127\.0\.0\.1$/.test(addr)
+ || /^fe80::1$/.test(addr)
+ || /^::1$/.test(addr)
+ || /^::$/.test(addr);
+};
-function collect(stream, cb) {
+ip.loopback = function loopback(family) {
+ //
+ // Default to `ipv4`
+ //
+ family = _normalizeFamily(family);
- // we create a collection of objects, where
- // - names is a list of all paths
- // - there are per-file objects: { file: , children [ paths ] }
- // - named is a map { path: fo }
- var files = {
- paths: [],
- named: {}, // wrapped files.
- unnamed: [], // wrapped files.
+ if (family !== 'ipv4' && family !== 'ipv6') {
+ throw new Error('family must be ipv4 or ipv6');
}
- function get(name) {
- if (!files.named[name]) {
- files.named[name] = {
- children: [],
- }
- }
- return files.named[name]
- }
+ return family === 'ipv4'
+ ? '127.0.0.1'
+ : 'fe80::1';
+};
- stream.on('data', function(file) {
- if (cb === null) {
- // already errored, or no way to externalize result
- stream.on('data', function() {}) // de-register
- return // do nothing.
- }
+//
+// ### function address (name, family)
+// #### @name {string|'public'|'private'} **Optional** Name or security
+// of the network interface.
+// #### @family {ipv4|ipv6} **Optional** IP family of the address (defaults
+// to ipv4).
+//
+// Returns the address for the network interface on the current system with
+// the specified `name`:
+// * String: First `family` address of the interface.
+// If not found see `undefined`.
+// * 'public': the first public ip address of family.
+// * 'private': the first private ip address of family.
+// * undefined: First address with `ipv4` or loopback addres `127.0.0.1`.
+//
+ip.address = function address(name, family) {
+ var interfaces = os.networkInterfaces(),
+ all;
- if (file.path) {
- // add file to named
- var fo = get(file.path)
- fo.file = file
+ //
+ // Default to `ipv4`
+ //
+ family = _normalizeFamily(family);
- // add reference to file at parent
- var po = get(Path.dirname(file.path))
- if (fo !== po) po.children.push(fo)
+ //
+ // If a specific network interface has been named,
+ // return the address.
+ //
+ if (name && !~['public', 'private'].indexOf(name)) {
+ return interfaces[name].filter(function (details) {
+ details.family = details.family.toLowerCase();
+ return details.family === family;
+ })[0].address;
+ }
- // add name to names list.
- files.paths.push(file.path)
- } else {
- files.unnamed.push({ file: file, children: [] })
- }
- })
+ var all = Object.keys(interfaces).map(function (nic) {
+ //
+ // Note: name will only be `public` or `private`
+ // when this is called.
+ //
+ var addresses = interfaces[nic].filter(function (details) {
+ details.family = details.family.toLowerCase();
+ if (details.family !== family || ip.isLoopback(details.address)) {
+ return false;
+ }
+ else if (!name) {
+ return true;
+ }
- stream.on('error', function(err) {
- cb && cb(err)
- cb = null
- })
+ return name === 'public'
+ ? !ip.isPrivate(details.address)
+ : ip.isPrivate(details.address)
+ });
- stream.on('end', function() {
- cb && cb(null, files)
- cb = null
- })
-}
+ return addresses.length
+ ? addresses[0].address
+ : undefined;
+ }).filter(Boolean);
+
+ return !all.length
+ ? ip.loopback(family)
+ : all[0];
+};
+
+ip.toLong = function toInt(ip){
+ var ipl=0;
+ ip.split('.').forEach(function( octet ) {
+ ipl<<=8;
+ ipl+=parseInt(octet);
+ });
+ return(ipl >>>0);
+};
-},{"path":62}],92:[function(require,module,exports){
-var x = module.exports = {}
-x.randomString = randomString
-x.cleanPath = cleanPath
+ip.fromLong = function fromInt(ipl){
+ return ( (ipl>>>24) +'.' +
+ (ipl>>16 & 255) +'.' +
+ (ipl>>8 & 255) +'.' +
+ (ipl & 255) );
+};
-function randomString () {
- return Math.random().toString(36).slice(2) +
- Math.random().toString(36).slice(2) +
- Math.random().toString(36).slice(2) +
- Math.random().toString(36).slice(2)
+function _normalizeFamily(family) {
+ return family ? family.toLowerCase() : 'ipv4';
}
-function cleanPath(path, base) {
- if (!path) return ''
- if (!base) return path
+},{"buffer":8,"os":103}],49:[function(require,module,exports){
- if (base[base.length-1] != '/') {
- base += "/"
- }
+/**
+ * isArray
+ */
- // remove base from path
- path = path.replace(base, '')
- path = path.replace(/[\/]+/g, '/')
- return path
-}
+var isArray = Array.isArray;
-},{}],93:[function(require,module,exports){
-var flat = require('./mp2v_flat')
-var tree = require('./mp2v_tree')
+/**
+ * toString
+ */
-var x = module.exports = tree
-x.flat = flat
-x.tree = tree
+var str = Object.prototype.toString;
-},{"./mp2v_flat":94,"./mp2v_tree":95}],94:[function(require,module,exports){
-var Multipart = require('multipart-stream')
-var duplexify = require('duplexify')
-var stream = require('stream')
-var common = require('./common')
-randomString = common.randomString
+/**
+ * Whether or not the given `val`
+ * is an array.
+ *
+ * example:
+ *
+ * isArray([]);
+ * // > true
+ * isArray(arguments);
+ * // > false
+ * isArray('');
+ * // > false
+ *
+ * @param {mixed} val
+ * @return {bool}
+ */
-module.exports = v2mpFlat
+module.exports = isArray || function (val) {
+ return !! val && '[object Array]' == str.call(val);
+};
-// we'll create three streams:
-// - w: a writable stream. it receives vinyl files
-// - mp: a multipart stream
-// - r: a readable stream. it outputs multipart data
-function v2mpFlat(opts) {
- opts = opts || {}
- opts.boundary = opts.boundary || randomString()
+},{}],50:[function(require,module,exports){
+/**
+ * Determine if an object is Buffer
+ *
+ * Author: Feross Aboukhadijeh
+ * License: MIT
+ *
+ * `npm install is-buffer`
+ */
- var w = new stream.Writable({objectMode: true})
- var r = new stream.PassThrough({objectMode: true})
- var mp = new Multipart(opts.boundary)
+module.exports = function (obj) {
+ return !!(obj != null &&
+ (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor)
+ (obj.constructor &&
+ typeof obj.constructor.isBuffer === 'function' &&
+ obj.constructor.isBuffer(obj))
+ ))
+}
- // connect w -> mp
- w._write = function(file, enc, cb) {
- writePart(mp, file, cb)
- }
+},{}],51:[function(require,module,exports){
- // connect mp -> r
- w.on('finish', function() {
- // apparently cannot add parts while streaming :(
- mp.pipe(r)
- })
+exports = module.exports = function(bytes)
+{
+ var i = 0;
+ while(i < bytes.length)
+ {
+ if( (// ASCII
+ bytes[i] == 0x09 ||
+ bytes[i] == 0x0A ||
+ bytes[i] == 0x0D ||
+ (0x20 <= bytes[i] && bytes[i] <= 0x7E)
+ )
+ ) {
+ i += 1;
+ continue;
+ }
- var out = duplexify.obj(w, r)
- out.boundary = opts.boundary
- return out
-}
+ if( (// non-overlong 2-byte
+ (0xC2 <= bytes[i] && bytes[i] <= 0xDF) &&
+ (0x80 <= bytes[i+1] && bytes[i+1] <= 0xBF)
+ )
+ ) {
+ i += 2;
+ continue;
+ }
-function writePart(mp, file, cb) {
- var c = file.contents
- if (c === null)
- c = emptyStream()
+ if( (// excluding overlongs
+ bytes[i] == 0xE0 &&
+ (0xA0 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
+ (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
+ ) ||
+ (// straight 3-byte
+ ((0xE1 <= bytes[i] && bytes[i] <= 0xEC) ||
+ bytes[i] == 0xEE ||
+ bytes[i] == 0xEF) &&
+ (0x80 <= bytes[i + 1] && bytes[i+1] <= 0xBF) &&
+ (0x80 <= bytes[i+2] && bytes[i+2] <= 0xBF)
+ ) ||
+ (// excluding surrogates
+ bytes[i] == 0xED &&
+ (0x80 <= bytes[i+1] && bytes[i+1] <= 0x9F) &&
+ (0x80 <= bytes[i+2] && bytes[i+2] <= 0xBF)
+ )
+ ) {
+ i += 3;
+ continue;
+ }
- mp.addPart({
- body: file.contents,
- headers: headersForFile(file),
- })
- cb(null)
- // TODO: call cb when file.contents ends instead.
-}
+ if( (// planes 1-3
+ bytes[i] == 0xF0 &&
+ (0x90 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
+ (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
+ (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
+ ) ||
+ (// planes 4-15
+ (0xF1 <= bytes[i] && bytes[i] <= 0xF3) &&
+ (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
+ (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
+ (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
+ ) ||
+ (// plane 16
+ bytes[i] == 0xF4 &&
+ (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x8F) &&
+ (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
+ (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
+ )
+ ) {
+ i += 4;
+ continue;
+ }
-function emptyStream() {
- var s = new stream.PassThrough({objectMode: true})
- s.write(null)
- return s
-}
+ return false;
+ }
-function headersForFile(file) {
- var fpath = common.cleanPath(file.path, file.base)
+ return true;
+}
- var h = {}
- h['Content-Disposition'] = 'file; filename="' +fpath+ '"'
+},{}],52:[function(require,module,exports){
+'use strict';
- if (file.isDirectory()) {
- h['Content-Type'] = 'text/directory'
- } else {
- h['Content-Type'] = 'application/octet-stream'
+module.exports = function isValidGlob(glob) {
+ if (typeof glob === 'string' && glob.length > 0) {
+ return true;
+ }
+ if (Array.isArray(glob)) {
+ return glob.length !== 0 && every(glob);
}
+ return false;
+};
- return h
+function every(arr) {
+ var len = arr.length;
+ while (len--) {
+ if (typeof arr[len] !== 'string' || arr[len].length <= 0) {
+ return false;
+ }
+ }
+ return true;
}
-function randomString () {
- return Math.random().toString(36).slice(2) +
- Math.random().toString(36).slice(2) +
- Math.random().toString(36).slice(2) +
- Math.random().toString(36).slice(2)
-}
+},{}],53:[function(require,module,exports){
+module.exports = Array.isArray || function (arr) {
+ return Object.prototype.toString.call(arr) == '[object Array]';
+};
-},{"./common":92,"duplexify":12,"multipart-stream":57,"stream":81}],95:[function(require,module,exports){
-var Multipart = require('multipart-stream')
-var duplexify = require('duplexify')
+},{}],54:[function(require,module,exports){
var stream = require('stream')
-var Path = require('path')
-var collect = require('./collect')
-var common = require('./common')
-randomString = common.randomString
-
-module.exports = v2mpTree
-// we'll create three streams:
-// - w: a writable stream. it receives vinyl files
-// - mps: a multipart stream in between.
-// - r: a readable stream. it outputs text. needed to
-// give the caller something, while w finishes.
-//
-// we do all processing on the incoming vinyl metadata
-// before we transform to multipart, that's becasue we
-// need a complete view of the filesystem. (/ the code
-// i lifted did that and it's convoluted enough not to
-// want to change it...)
-function v2mpTree(opts) {
- opts = opts || {}
- opts.boundary = opts.boundary || randomString()
- var r = new stream.PassThrough({objectMode: true})
- var w = new stream.PassThrough({objectMode: true})
- var out = duplexify.obj(w, r)
- out.boundary = opts.boundary
+function isStream (obj) {
+ return obj instanceof stream.Stream
+}
- collect(w, function(err, files) {
- if (err) {
- r.emit('error', err)
- return
- }
- try {
- // construct the multipart streams from these files
- var mp = streamForCollection(opts.boundary, files)
+function isReadable (obj) {
+ return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object'
+}
- // let the user know what the content-type header is.
- // this is because multipart is such a grossly defined protocol :(
- out.multipartHdr = "Content-Type: multipart/mixed; boundary=" + mp.boundary
- if (opts.writeHeader) {
- r.write(out.multipartHdr + "\r\n")
- r.write("\r\n")
- }
- // now we pipe the multipart stream to
- // the readable thing we returned.
- // now the user will start receiving data.
- mp.pipe(r)
- } catch (e) {
- r.emit('error', e)
- }
- })
+function isWritable (obj) {
+ return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object'
+}
- return out
+
+function isDuplex (obj) {
+ return isReadable(obj) && isWritable(obj)
}
-function streamForCollection(boundary, files) {
- var parts = []
- // walk through all the named files in order.
- files.paths.sort()
- for (var i = 0; i < files.paths.length; i++) {
- var n = files.paths[i]
- var s = streamForPath(files, n)
- if (!s) continue // already processed.
- parts.push({ body: s, headers: headersForFile(files.named[n])})
- }
+module.exports = isStream
+module.exports.isReadable = isReadable
+module.exports.isWritable = isWritable
+module.exports.isDuplex = isDuplex
- // then add all the unnamed files.
- for (var i = 0; i < files.unnamed.length; i++) {
- var f = files.unnamed[i] // raw vinyl files.
- var s = streamForWrapped(files, f)
- if (!s) continue // already processed.
- parts.push({ body: s, headers: headersForFile(f)})
- }
+},{"stream":124}],55:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
- if (parts.length == 0) { // avoid multipart bug.
- var s = streamForString("--" + boundary + "--\r\n") // close multipart.
- s.boundary = boundary
- return s
- }
+/** Used to pool arrays and objects used internally */
+var arrayPool = [];
- // write out multipart.
- var mp = new Multipart(boundary)
- for (var i = 0; i < parts.length; i++) {
- mp.addPart(parts[i])
+module.exports = arrayPool;
+
+},{}],56:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var baseCreate = require('lodash._basecreate'),
+ isObject = require('lodash.isobject'),
+ setBindData = require('lodash._setbinddata'),
+ slice = require('lodash._slice');
+
+/**
+ * Used for `Array` method references.
+ *
+ * Normally `Array.prototype` would suffice, however, using an array literal
+ * avoids issues in Narwhal.
+ */
+var arrayRef = [];
+
+/** Native method shortcuts */
+var push = arrayRef.push;
+
+/**
+ * The base implementation of `_.bind` that creates the bound function and
+ * sets its meta data.
+ *
+ * @private
+ * @param {Array} bindData The bind data array.
+ * @returns {Function} Returns the new bound function.
+ */
+function baseBind(bindData) {
+ var func = bindData[0],
+ partialArgs = bindData[2],
+ thisArg = bindData[4];
+
+ function bound() {
+ // `Function#bind` spec
+ // http://es5.github.io/#x15.3.4.5
+ if (partialArgs) {
+ // avoid `arguments` object deoptimizations by using `slice` instead
+ // of `Array.prototype.slice.call` and not assigning `arguments` to a
+ // variable as a ternary expression
+ var args = slice(partialArgs);
+ push.apply(args, arguments);
+ }
+ // mimic the constructor's `return` behavior
+ // http://es5.github.io/#x13.2.2
+ if (this instanceof bound) {
+ // ensure `new bound` is an instance of `func`
+ var thisBinding = baseCreate(func.prototype),
+ result = func.apply(thisBinding, args || arguments);
+ return isObject(result) ? result : thisBinding;
+ }
+ return func.apply(thisArg, args || arguments);
}
- return mp
+ setBindData(bound, bindData);
+ return bound;
}
-function streamForString(str) {
- var s = new stream.PassThrough()
- s.end(str)
- return s
+module.exports = baseBind;
+
+},{"lodash._basecreate":57,"lodash._setbinddata":67,"lodash._slice":69,"lodash.isobject":77}],57:[function(require,module,exports){
+(function (global){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var isNative = require('lodash._isnative'),
+ isObject = require('lodash.isobject'),
+ noop = require('lodash.noop');
+
+/* Native method shortcuts for methods with the same name as other `lodash` methods */
+var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate;
+
+/**
+ * The base implementation of `_.create` without support for assigning
+ * properties to the created object.
+ *
+ * @private
+ * @param {Object} prototype The object to inherit from.
+ * @returns {Object} Returns the new object.
+ */
+function baseCreate(prototype, properties) {
+ return isObject(prototype) ? nativeCreate(prototype) : {};
+}
+// fallback for browsers without `Object.create`
+if (!nativeCreate) {
+ baseCreate = (function() {
+ function Object() {}
+ return function(prototype) {
+ if (isObject(prototype)) {
+ Object.prototype = prototype;
+ var result = new Object;
+ Object.prototype = null;
+ }
+ return result || global.Object();
+ };
+ }());
}
-function streamForPath(files, path) {
- var o = files.named[path]
- if (!o) {
- throw new Error("no object for path. lib error.")
- }
+module.exports = baseCreate;
- if (!o.file) { // no vinyl file, so no need to process this one.
- return
- }
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"lodash._isnative":63,"lodash.isobject":77,"lodash.noop":80}],58:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var bind = require('lodash.bind'),
+ identity = require('lodash.identity'),
+ setBindData = require('lodash._setbinddata'),
+ support = require('lodash.support');
- // avoid processing twice.
- if (o.done) return null // already processed it
- o.done = true // mark it as already processed.
+/** Used to detected named functions */
+var reFuncName = /^\s*function[ \n\r\t]+\w/;
- return streamForWrapped(files, o)
-}
+/** Used to detect functions containing a `this` reference */
+var reThis = /\bthis\b/;
-function streamForWrapped(files, f) {
- if (f.file.isDirectory()) {
- return multipartForDir(files, f)
+/** Native method shortcuts */
+var fnToString = Function.prototype.toString;
+
+/**
+ * The base implementation of `_.createCallback` without support for creating
+ * "_.pluck" or "_.where" style callbacks.
+ *
+ * @private
+ * @param {*} [func=identity] The value to convert to a callback.
+ * @param {*} [thisArg] The `this` binding of the created callback.
+ * @param {number} [argCount] The number of arguments the callback accepts.
+ * @returns {Function} Returns a callback function.
+ */
+function baseCreateCallback(func, thisArg, argCount) {
+ if (typeof func != 'function') {
+ return identity;
+ }
+ // exit early for no `thisArg` or already bound by `Function#bind`
+ if (typeof thisArg == 'undefined' || !('prototype' in func)) {
+ return func;
+ }
+ var bindData = func.__bindData__;
+ if (typeof bindData == 'undefined') {
+ if (support.funcNames) {
+ bindData = !func.name;
+ }
+ bindData = bindData || !support.funcDecomp;
+ if (!bindData) {
+ var source = fnToString.call(func);
+ if (!support.funcNames) {
+ bindData = !reFuncName.test(source);
+ }
+ if (!bindData) {
+ // checks if `func` references the `this` keyword and stores the result
+ bindData = reThis.test(source);
+ setBindData(func, bindData);
+ }
+ }
+ }
+ // exit early if there are no `this` references or `func` is bound
+ if (bindData === false || (bindData !== true && bindData[1] & 1)) {
+ return func;
}
-
- // stream for a file
- if (f.children.length > 0) { // sanity check
- throw new Error("non-directory has children. lib error")
+ switch (argCount) {
+ case 1: return function(value) {
+ return func.call(thisArg, value);
+ };
+ case 2: return function(a, b) {
+ return func.call(thisArg, a, b);
+ };
+ case 3: return function(value, index, collection) {
+ return func.call(thisArg, value, index, collection);
+ };
+ case 4: return function(accumulator, value, index, collection) {
+ return func.call(thisArg, accumulator, value, index, collection);
+ };
}
-
- return f.file.contents
+ return bind(func, thisArg);
}
-function multipartForDir(files, dir) {
- // we still write the boundary for the headers
- dir.boundary = randomString()
+module.exports = baseCreateCallback;
- if (!dir.children || dir.children.length < 1) {
- // we have to intercept this here and return an empty stream.
- // because multipart lib fails if there are no parts. see
- // https://github.com/hendrikcech/multipart-stream/issues/1
- return streamForString("--" + dir.boundary + "--\r\n") // close multipart.
- }
+},{"lodash._setbinddata":67,"lodash.bind":70,"lodash.identity":75,"lodash.support":82}],59:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var baseCreate = require('lodash._basecreate'),
+ isObject = require('lodash.isobject'),
+ setBindData = require('lodash._setbinddata'),
+ slice = require('lodash._slice');
- var mp = new Multipart(dir.boundary)
- for (var i = 0; i < dir.children.length; i++) {
- var child = dir.children[i]
- if (!child.file) {
- throw new Error("child has no file. lib error")
- }
+/**
+ * Used for `Array` method references.
+ *
+ * Normally `Array.prototype` would suffice, however, using an array literal
+ * avoids issues in Narwhal.
+ */
+var arrayRef = [];
- var s = streamForPath(files, child.file.path)
- mp.addPart({ body: s, headers: headersForFile(child) })
- }
- return mp
-}
+/** Native method shortcuts */
+var push = arrayRef.push;
-function headersForFile(o) {
- var fpath = common.cleanPath(o.file.path, o.file.base)
+/**
+ * The base implementation of `createWrapper` that creates the wrapper and
+ * sets its meta data.
+ *
+ * @private
+ * @param {Array} bindData The bind data array.
+ * @returns {Function} Returns the new function.
+ */
+function baseCreateWrapper(bindData) {
+ var func = bindData[0],
+ bitmask = bindData[1],
+ partialArgs = bindData[2],
+ partialRightArgs = bindData[3],
+ thisArg = bindData[4],
+ arity = bindData[5];
- var h = {}
- h['Content-Disposition'] = 'file; filename="' + fpath + '"'
+ var isBind = bitmask & 1,
+ isBindKey = bitmask & 2,
+ isCurry = bitmask & 4,
+ isCurryBound = bitmask & 8,
+ key = func;
- if (o.file.isDirectory()) {
- h['Content-Type'] = 'multipart/mixed; boundary=' + o.boundary
- } else {
- h['Content-Type'] = 'application/octet-stream'
+ function bound() {
+ var thisBinding = isBind ? thisArg : this;
+ if (partialArgs) {
+ var args = slice(partialArgs);
+ push.apply(args, arguments);
+ }
+ if (partialRightArgs || isCurry) {
+ args || (args = slice(arguments));
+ if (partialRightArgs) {
+ push.apply(args, partialRightArgs);
+ }
+ if (isCurry && args.length < arity) {
+ bitmask |= 16 & ~32;
+ return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
+ }
+ }
+ args || (args = arguments);
+ if (isBindKey) {
+ func = thisBinding[key];
+ }
+ if (this instanceof bound) {
+ thisBinding = baseCreate(func.prototype);
+ var result = func.apply(thisBinding, args);
+ return isObject(result) ? result : thisBinding;
+ }
+ return func.apply(thisBinding, args);
}
-
- return h
+ setBindData(bound, bindData);
+ return bound;
}
-},{"./collect":91,"./common":92,"duplexify":12,"multipart-stream":57,"path":62,"stream":81}],96:[function(require,module,exports){
-(function (process){
-var path = require('path');
-var clone = require('clone');
-var cloneStats = require('clone-stats');
-var cloneBuffer = require('./lib/cloneBuffer');
-var isBuffer = require('./lib/isBuffer');
-var isStream = require('./lib/isStream');
-var isNull = require('./lib/isNull');
-var inspectStream = require('./lib/inspectStream');
-var Stream = require('stream');
-var replaceExt = require('replace-ext');
-
-function File(file) {
- if (!file) file = {};
-
- // record path change
- var history = file.path ? [file.path] : file.history;
- this.history = history || [];
-
- this.cwd = file.cwd || process.cwd();
- this.base = file.base || this.cwd;
-
- // stat = files stats object
- this.stat = file.stat || null;
+module.exports = baseCreateWrapper;
- // contents = stream, buffer, or null if not read
- this.contents = file.contents || null;
+},{"lodash._basecreate":57,"lodash._setbinddata":67,"lodash._slice":69,"lodash.isobject":77}],60:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var forIn = require('lodash.forin'),
+ getArray = require('lodash._getarray'),
+ isFunction = require('lodash.isfunction'),
+ objectTypes = require('lodash._objecttypes'),
+ releaseArray = require('lodash._releasearray');
- this._isVinyl = true;
-}
+/** `Object#toString` result shortcuts */
+var argsClass = '[object Arguments]',
+ arrayClass = '[object Array]',
+ boolClass = '[object Boolean]',
+ dateClass = '[object Date]',
+ numberClass = '[object Number]',
+ objectClass = '[object Object]',
+ regexpClass = '[object RegExp]',
+ stringClass = '[object String]';
-File.prototype.isBuffer = function() {
- return isBuffer(this.contents);
-};
+/** Used for native method references */
+var objectProto = Object.prototype;
-File.prototype.isStream = function() {
- return isStream(this.contents);
-};
+/** Used to resolve the internal [[Class]] of values */
+var toString = objectProto.toString;
-File.prototype.isNull = function() {
- return isNull(this.contents);
-};
+/** Native method shortcuts */
+var hasOwnProperty = objectProto.hasOwnProperty;
-// TODO: should this be moved to vinyl-fs?
-File.prototype.isDirectory = function() {
- return this.isNull() && this.stat && this.stat.isDirectory();
-};
+/**
+ * The base implementation of `_.isEqual`, without support for `thisArg` binding,
+ * that allows partial "_.where" style comparisons.
+ *
+ * @private
+ * @param {*} a The value to compare.
+ * @param {*} b The other value to compare.
+ * @param {Function} [callback] The function to customize comparing values.
+ * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
+ * @param {Array} [stackA=[]] Tracks traversed `a` objects.
+ * @param {Array} [stackB=[]] Tracks traversed `b` objects.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ */
+function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
+ // used to indicate that when comparing objects, `a` has at least the properties of `b`
+ if (callback) {
+ var result = callback(a, b);
+ if (typeof result != 'undefined') {
+ return !!result;
+ }
+ }
+ // exit early for identical values
+ if (a === b) {
+ // treat `+0` vs. `-0` as not equal
+ return a !== 0 || (1 / a == 1 / b);
+ }
+ var type = typeof a,
+ otherType = typeof b;
-File.prototype.clone = function(opt) {
- if (typeof opt === 'boolean') {
- opt = {
- deep: opt,
- contents: true
- };
- } else if (!opt) {
- opt = {
- deep: true,
- contents: true
- };
- } else {
- opt.deep = opt.deep === true;
- opt.contents = opt.contents !== false;
+ // exit early for unlike primitive values
+ if (a === a &&
+ !(a && objectTypes[type]) &&
+ !(b && objectTypes[otherType])) {
+ return false;
+ }
+ // exit early for `null` and `undefined` avoiding ES3's Function#call behavior
+ // http://es5.github.io/#x15.3.4.4
+ if (a == null || b == null) {
+ return a === b;
}
+ // compare [[Class]] names
+ var className = toString.call(a),
+ otherClass = toString.call(b);
- // clone our file contents
- var contents;
- if (this.isStream()) {
- contents = this.contents.pipe(new Stream.PassThrough());
- this.contents = this.contents.pipe(new Stream.PassThrough());
- } else if (this.isBuffer()) {
- contents = opt.contents ? cloneBuffer(this.contents) : this.contents;
+ if (className == argsClass) {
+ className = objectClass;
+ }
+ if (otherClass == argsClass) {
+ otherClass = objectClass;
+ }
+ if (className != otherClass) {
+ return false;
}
+ switch (className) {
+ case boolClass:
+ case dateClass:
+ // coerce dates and booleans to numbers, dates to milliseconds and booleans
+ // to `1` or `0` treating invalid dates coerced to `NaN` as not equal
+ return +a == +b;
- var file = new File({
- cwd: this.cwd,
- base: this.base,
- stat: (this.stat ? cloneStats(this.stat) : null),
- history: this.history.slice(),
- contents: contents
- });
+ case numberClass:
+ // treat `NaN` vs. `NaN` as equal
+ return (a != +a)
+ ? b != +b
+ // but treat `+0` vs. `-0` as not equal
+ : (a == 0 ? (1 / a == 1 / b) : a == +b);
- // clone our custom properties
- Object.keys(this).forEach(function(key) {
- // ignore built-in fields
- if (key === '_contents' || key === 'stat' ||
- key === 'history' || key === 'path' ||
- key === 'base' || key === 'cwd') {
- return;
- }
- file[key] = opt.deep ? clone(this[key], true) : this[key];
- }, this);
- return file;
-};
+ case regexpClass:
+ case stringClass:
+ // coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
+ // treat string primitives and their corresponding object instances as equal
+ return a == String(b);
+ }
+ var isArr = className == arrayClass;
+ if (!isArr) {
+ // unwrap any `lodash` wrapped values
+ var aWrapped = hasOwnProperty.call(a, '__wrapped__'),
+ bWrapped = hasOwnProperty.call(b, '__wrapped__');
-File.prototype.pipe = function(stream, opt) {
- if (!opt) opt = {};
- if (typeof opt.end === 'undefined') opt.end = true;
+ if (aWrapped || bWrapped) {
+ return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB);
+ }
+ // exit for functions and DOM nodes
+ if (className != objectClass) {
+ return false;
+ }
+ // in older versions of Opera, `arguments` objects have `Array` constructors
+ var ctorA = a.constructor,
+ ctorB = b.constructor;
- if (this.isStream()) {
- return this.contents.pipe(stream, opt);
+ // non `Object` object instances with different constructors are not equal
+ if (ctorA != ctorB &&
+ !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
+ ('constructor' in a && 'constructor' in b)
+ ) {
+ return false;
+ }
}
- if (this.isBuffer()) {
- if (opt.end) {
- stream.end(this.contents);
- } else {
- stream.write(this.contents);
+ // assume cyclic structures are equal
+ // the algorithm for detecting cyclic structures is adapted from ES 5.1
+ // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
+ var initedStack = !stackA;
+ stackA || (stackA = getArray());
+ stackB || (stackB = getArray());
+
+ var length = stackA.length;
+ while (length--) {
+ if (stackA[length] == a) {
+ return stackB[length] == b;
}
- return stream;
}
+ var size = 0;
+ result = true;
- // isNull
- if (opt.end) stream.end();
- return stream;
-};
+ // add `a` and `b` to the stack of traversed objects
+ stackA.push(a);
+ stackB.push(b);
-File.prototype.inspect = function() {
- var inspect = [];
+ // recursively compare objects and arrays (susceptible to call stack limits)
+ if (isArr) {
+ // compare lengths to determine if a deep comparison is necessary
+ length = a.length;
+ size = b.length;
+ result = size == length;
- // use relative path if possible
- var filePath = (this.base && this.path) ? this.relative : this.path;
+ if (result || isWhere) {
+ // deep compare the contents, ignoring non-numeric properties
+ while (size--) {
+ var index = length,
+ value = b[size];
- if (filePath) {
- inspect.push('"'+filePath+'"');
+ if (isWhere) {
+ while (index--) {
+ if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
+ break;
+ }
+ }
+ } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
+ break;
+ }
+ }
+ }
}
+ else {
+ // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
+ // which, in this case, is more costly
+ forIn(b, function(value, key, b) {
+ if (hasOwnProperty.call(b, key)) {
+ // count the number of properties.
+ size++;
+ // deep compare each property value.
+ return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
+ }
+ });
- if (this.isBuffer()) {
- inspect.push(this.contents.inspect());
+ if (result && !isWhere) {
+ // ensure both objects have the same number of properties
+ forIn(a, function(value, key, a) {
+ if (hasOwnProperty.call(a, key)) {
+ // `size` will be `-1` if `a` has more properties than `b`
+ return (result = --size > -1);
+ }
+ });
+ }
}
+ stackA.pop();
+ stackB.pop();
- if (this.isStream()) {
- inspect.push(inspectStream(this.contents));
+ if (initedStack) {
+ releaseArray(stackA);
+ releaseArray(stackB);
}
+ return result;
+}
- return '';
-};
+module.exports = baseIsEqual;
-File.isVinyl = function(file) {
- return file && file._isVinyl === true;
-};
+},{"lodash._getarray":62,"lodash._objecttypes":65,"lodash._releasearray":66,"lodash.forin":73,"lodash.isfunction":76}],61:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var baseBind = require('lodash._basebind'),
+ baseCreateWrapper = require('lodash._basecreatewrapper'),
+ isFunction = require('lodash.isfunction'),
+ slice = require('lodash._slice');
-// virtual attributes
-// or stuff with extra logic
-Object.defineProperty(File.prototype, 'contents', {
- get: function() {
- return this._contents;
- },
- set: function(val) {
- if (!isBuffer(val) && !isStream(val) && !isNull(val)) {
- throw new Error('File.contents can only be a Buffer, a Stream, or null.');
- }
- this._contents = val;
- }
-});
+/**
+ * Used for `Array` method references.
+ *
+ * Normally `Array.prototype` would suffice, however, using an array literal
+ * avoids issues in Narwhal.
+ */
+var arrayRef = [];
-// TODO: should this be moved to vinyl-fs?
-Object.defineProperty(File.prototype, 'relative', {
- get: function() {
- if (!this.base) throw new Error('No base specified! Can not get relative.');
- if (!this.path) throw new Error('No path specified! Can not get relative.');
- return path.relative(this.base, this.path);
- },
- set: function() {
- throw new Error('File.relative is generated from the base and path attributes. Do not modify it.');
- }
-});
+/** Native method shortcuts */
+var push = arrayRef.push,
+ unshift = arrayRef.unshift;
-Object.defineProperty(File.prototype, 'dirname', {
- get: function() {
- if (!this.path) throw new Error('No path specified! Can not get dirname.');
- return path.dirname(this.path);
- },
- set: function(dirname) {
- if (!this.path) throw new Error('No path specified! Can not set dirname.');
- this.path = path.join(dirname, path.basename(this.path));
- }
-});
+/**
+ * Creates a function that, when called, either curries or invokes `func`
+ * with an optional `this` binding and partially applied arguments.
+ *
+ * @private
+ * @param {Function|string} func The function or method name to reference.
+ * @param {number} bitmask The bitmask of method flags to compose.
+ * The bitmask may be composed of the following flags:
+ * 1 - `_.bind`
+ * 2 - `_.bindKey`
+ * 4 - `_.curry`
+ * 8 - `_.curry` (bound)
+ * 16 - `_.partial`
+ * 32 - `_.partialRight`
+ * @param {Array} [partialArgs] An array of arguments to prepend to those
+ * provided to the new function.
+ * @param {Array} [partialRightArgs] An array of arguments to append to those
+ * provided to the new function.
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @param {number} [arity] The arity of `func`.
+ * @returns {Function} Returns the new function.
+ */
+function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
+ var isBind = bitmask & 1,
+ isBindKey = bitmask & 2,
+ isCurry = bitmask & 4,
+ isCurryBound = bitmask & 8,
+ isPartial = bitmask & 16,
+ isPartialRight = bitmask & 32;
-Object.defineProperty(File.prototype, 'basename', {
- get: function() {
- if (!this.path) throw new Error('No path specified! Can not get basename.');
- return path.basename(this.path);
- },
- set: function(basename) {
- if (!this.path) throw new Error('No path specified! Can not set basename.');
- this.path = path.join(path.dirname(this.path), basename);
+ if (!isBindKey && !isFunction(func)) {
+ throw new TypeError;
+ }
+ if (isPartial && !partialArgs.length) {
+ bitmask &= ~16;
+ isPartial = partialArgs = false;
}
-});
-
-Object.defineProperty(File.prototype, 'extname', {
- get: function() {
- if (!this.path) throw new Error('No path specified! Can not get extname.');
- return path.extname(this.path);
- },
- set: function(extname) {
- if (!this.path) throw new Error('No path specified! Can not set extname.');
- this.path = replaceExt(this.path, extname);
+ if (isPartialRight && !partialRightArgs.length) {
+ bitmask &= ~32;
+ isPartialRight = partialRightArgs = false;
}
-});
-
-Object.defineProperty(File.prototype, 'path', {
- get: function() {
- return this.history[this.history.length - 1];
- },
- set: function(path) {
- if (typeof path !== 'string') throw new Error('path should be string');
-
- // record history only when path changed
- if (path && path !== this.path) {
- this.history.push(path);
+ var bindData = func && func.__bindData__;
+ if (bindData && bindData !== true) {
+ // clone `bindData`
+ bindData = slice(bindData);
+ if (bindData[2]) {
+ bindData[2] = slice(bindData[2]);
+ }
+ if (bindData[3]) {
+ bindData[3] = slice(bindData[3]);
+ }
+ // set `thisBinding` is not previously bound
+ if (isBind && !(bindData[1] & 1)) {
+ bindData[4] = thisArg;
+ }
+ // set if previously bound but not currently (subsequent curried functions)
+ if (!isBind && bindData[1] & 1) {
+ bitmask |= 8;
+ }
+ // set curried arity if not yet set
+ if (isCurry && !(bindData[1] & 4)) {
+ bindData[5] = arity;
}
+ // append partial left arguments
+ if (isPartial) {
+ push.apply(bindData[2] || (bindData[2] = []), partialArgs);
+ }
+ // append partial right arguments
+ if (isPartialRight) {
+ unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
+ }
+ // merge flags
+ bindData[1] |= bitmask;
+ return createWrapper.apply(null, bindData);
}
-});
+ // fast path for `_.bind`
+ var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper;
+ return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]);
+}
-module.exports = File;
+module.exports = createWrapper;
-}).call(this,require('_process'))
-},{"./lib/cloneBuffer":97,"./lib/inspectStream":98,"./lib/isBuffer":99,"./lib/isNull":100,"./lib/isStream":101,"_process":64,"clone":9,"clone-stats":8,"path":62,"replace-ext":79,"stream":81}],97:[function(require,module,exports){
-var Buffer = require('buffer').Buffer;
+},{"lodash._basebind":56,"lodash._basecreatewrapper":59,"lodash._slice":69,"lodash.isfunction":76}],62:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var arrayPool = require('lodash._arraypool');
-module.exports = function(buf) {
- var out = new Buffer(buf.length);
- buf.copy(out);
- return out;
-};
+/**
+ * Gets an array from the array pool or creates a new one if the pool is empty.
+ *
+ * @private
+ * @returns {Array} The array from the pool.
+ */
+function getArray() {
+ return arrayPool.pop() || [];
+}
-},{"buffer":6}],98:[function(require,module,exports){
-var isStream = require('./isStream');
+module.exports = getArray;
-module.exports = function(stream) {
- if (!isStream(stream)) return;
+},{"lodash._arraypool":55}],63:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
- var streamType = stream.constructor.name;
- // avoid StreamStream
- if (streamType === 'Stream') streamType = '';
+/** Used for native method references */
+var objectProto = Object.prototype;
- return '<'+streamType+'Stream>';
-};
+/** Used to resolve the internal [[Class]] of values */
+var toString = objectProto.toString;
-},{"./isStream":101}],99:[function(require,module,exports){
-module.exports = require('buffer').Buffer.isBuffer;
+/** Used to detect if a method is native */
+var reNative = RegExp('^' +
+ String(toString)
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ .replace(/toString| for [^\]]+/g, '.*?') + '$'
+);
-},{"buffer":6}],100:[function(require,module,exports){
-module.exports = function(v) {
- return v === null;
-};
+/**
+ * Checks if `value` is a native function.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if the `value` is a native function, else `false`.
+ */
+function isNative(value) {
+ return typeof value == 'function' && reNative.test(value);
+}
-},{}],101:[function(require,module,exports){
-var Stream = require('stream').Stream;
+module.exports = isNative;
-module.exports = function(o) {
- return !!o && o instanceof Stream;
-};
-},{"stream":81}],102:[function(require,module,exports){
-var indexOf = require('indexof');
+},{}],64:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
-var Object_keys = function (obj) {
- if (Object.keys) return Object.keys(obj)
- else {
- var res = [];
- for (var key in obj) res.push(key)
- return res;
- }
-};
+/** Used as the max size of the `arrayPool` and `objectPool` */
+var maxPoolSize = 40;
-var forEach = function (xs, fn) {
- if (xs.forEach) return xs.forEach(fn)
- else for (var i = 0; i < xs.length; i++) {
- fn(xs[i], i, xs);
- }
-};
+module.exports = maxPoolSize;
-var defineProp = (function() {
- try {
- Object.defineProperty({}, '_', {});
- return function(obj, name, value) {
- Object.defineProperty(obj, name, {
- writable: true,
- enumerable: false,
- configurable: true,
- value: value
- })
- };
- } catch(e) {
- return function(obj, name, value) {
- obj[name] = value;
- };
- }
-}());
+},{}],65:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
-var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
-'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
-'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
-'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
-'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
+/** Used to determine if values are of the language type Object */
+var objectTypes = {
+ 'boolean': false,
+ 'function': true,
+ 'object': true,
+ 'number': false,
+ 'string': false,
+ 'undefined': false
+};
-function Context() {}
-Context.prototype = {};
+module.exports = objectTypes;
-var Script = exports.Script = function NodeScript (code) {
- if (!(this instanceof Script)) return new Script(code);
- this.code = code;
-};
+},{}],66:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var arrayPool = require('lodash._arraypool'),
+ maxPoolSize = require('lodash._maxpoolsize');
-Script.prototype.runInContext = function (context) {
- if (!(context instanceof Context)) {
- throw new TypeError("needs a 'context' argument.");
- }
-
- var iframe = document.createElement('iframe');
- if (!iframe.style) iframe.style = {};
- iframe.style.display = 'none';
-
- document.body.appendChild(iframe);
-
- var win = iframe.contentWindow;
- var wEval = win.eval, wExecScript = win.execScript;
+/**
+ * Releases the given array back to the array pool.
+ *
+ * @private
+ * @param {Array} [array] The array to release.
+ */
+function releaseArray(array) {
+ array.length = 0;
+ if (arrayPool.length < maxPoolSize) {
+ arrayPool.push(array);
+ }
+}
- if (!wEval && wExecScript) {
- // win.eval() magically appears when this is called in IE:
- wExecScript.call(win, 'null');
- wEval = win.eval;
- }
-
- forEach(Object_keys(context), function (key) {
- win[key] = context[key];
- });
- forEach(globals, function (key) {
- if (context[key]) {
- win[key] = context[key];
- }
- });
-
- var winKeys = Object_keys(win);
+module.exports = releaseArray;
- var res = wEval.call(win, this.code);
-
- forEach(Object_keys(win), function (key) {
- // Avoid copying circular objects like `top` and `window` by only
- // updating existing context properties or new properties in the `win`
- // that was only introduced after the eval.
- if (key in context || indexOf(winKeys, key) === -1) {
- context[key] = win[key];
- }
- });
+},{"lodash._arraypool":55,"lodash._maxpoolsize":64}],67:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var isNative = require('lodash._isnative'),
+ noop = require('lodash.noop');
- forEach(globals, function (key) {
- if (!(key in context)) {
- defineProp(context, key, win[key]);
- }
- });
-
- document.body.removeChild(iframe);
-
- return res;
+/** Used as the property descriptor for `__bindData__` */
+var descriptor = {
+ 'configurable': false,
+ 'enumerable': false,
+ 'value': null,
+ 'writable': false
};
-Script.prototype.runInThisContext = function () {
- return eval(this.code); // maybe...
-};
+/** Used to set meta data on functions */
+var defineProperty = (function() {
+ // IE 8 only accepts DOM elements
+ try {
+ var o = {},
+ func = isNative(func = Object.defineProperty) && func,
+ result = func(o, o, o) && func;
+ } catch(e) { }
+ return result;
+}());
-Script.prototype.runInNewContext = function (context) {
- var ctx = Script.createContext(context);
- var res = this.runInContext(ctx);
+/**
+ * Sets `this` binding data on a given function.
+ *
+ * @private
+ * @param {Function} func The function to set data on.
+ * @param {Array} value The data array to set.
+ */
+var setBindData = !defineProperty ? noop : function(func, value) {
+ descriptor.value = value;
+ defineProperty(func, '__bindData__', descriptor);
+};
- forEach(Object_keys(ctx), function (key) {
- context[key] = ctx[key];
- });
+module.exports = setBindData;
- return res;
-};
+},{"lodash._isnative":63,"lodash.noop":80}],68:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var objectTypes = require('lodash._objecttypes');
-forEach(Object_keys(Script.prototype), function (name) {
- exports[name] = Script[name] = function (code) {
- var s = Script(code);
- return s[name].apply(s, [].slice.call(arguments, 1));
- };
-});
+/** Used for native method references */
+var objectProto = Object.prototype;
-exports.createScript = function (code) {
- return exports.Script(code);
-};
+/** Native method shortcuts */
+var hasOwnProperty = objectProto.hasOwnProperty;
-exports.createContext = Script.createContext = function (context) {
- var copy = new Context();
- if(typeof context === 'object') {
- forEach(Object_keys(context), function (key) {
- copy[key] = context[key];
- });
+/**
+ * A fallback implementation of `Object.keys` which produces an array of the
+ * given object's own enumerable property names.
+ *
+ * @private
+ * @type Function
+ * @param {Object} object The object to inspect.
+ * @returns {Array} Returns an array of property names.
+ */
+var shimKeys = function(object) {
+ var index, iterable = object, result = [];
+ if (!iterable) return result;
+ if (!(objectTypes[typeof object])) return result;
+ for (index in iterable) {
+ if (hasOwnProperty.call(iterable, index)) {
+ result.push(index);
+ }
}
- return copy;
+ return result
};
-},{"indexof":17}],103:[function(require,module,exports){
-// Returns a wrapper function that returns a wrapped callback
-// The wrapper function should do some stuff, and return a
-// presumably different callback function.
-// This makes sure that own properties are retained, so that
-// decorations and such are not lost along the way.
-module.exports = wrappy
-function wrappy (fn, cb) {
- if (fn && cb) return wrappy(fn)(cb)
-
- if (typeof fn !== 'function')
- throw new TypeError('need wrapper function')
+module.exports = shimKeys;
- Object.keys(fn).forEach(function (k) {
- wrapper[k] = fn[k]
- })
+},{"lodash._objecttypes":65}],69:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
- return wrapper
+/**
+ * Slices the `collection` from the `start` index up to, but not including,
+ * the `end` index.
+ *
+ * Note: This function is used instead of `Array#slice` to support node lists
+ * in IE < 9 and to ensure dense arrays are returned.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to slice.
+ * @param {number} start The start index.
+ * @param {number} end The end index.
+ * @returns {Array} Returns the new array.
+ */
+function slice(array, start, end) {
+ start || (start = 0);
+ if (typeof end == 'undefined') {
+ end = array ? array.length : 0;
+ }
+ var index = -1,
+ length = end - start || 0,
+ result = Array(length < 0 ? 0 : length);
- function wrapper() {
- var args = new Array(arguments.length)
- for (var i = 0; i < args.length; i++) {
- args[i] = arguments[i]
- }
- var ret = fn.apply(this, args)
- var cb = args[args.length-1]
- if (typeof ret === 'function' && ret !== cb) {
- Object.keys(cb).forEach(function (k) {
- ret[k] = cb[k]
- })
- }
- return ret
+ while (++index < length) {
+ result[index] = array[start + index];
}
+ return result;
}
-},{}],104:[function(require,module,exports){
-arguments[4][55][0].apply(exports,arguments)
-},{"dup":55}],105:[function(require,module,exports){
-module.exports={
- "name": "ipfs-api",
- "version": "2.3.3",
- "description": "A client library for the IPFS API",
- "main": "src/index.js",
- "dependencies": {
- "brfs": "^1.4.0",
- "merge-stream": "^1.0.0",
- "multiaddr": "^1.0.0",
- "multipart-stream": "^2.0.0",
- "vinyl": "^0.5.1",
- "vinyl-fs-browser": "^2.1.1-1",
- "vinyl-multipart-stream": "^1.2.5"
- },
- "browserify": {
- "transform": [
- "brfs"
- ]
- },
- "engines": {
- "node": "^4.0.0"
- },
- "repository": {
- "type": "git",
- "url": "https://github.com/ipfs/node-ipfs-api"
- },
- "devDependencies": {
- "browserify": "^11.0.0",
- "ipfsd-ctl": "^0.5.1",
- "mocha": "^2.2.5",
- "pre-commit": "^1.0.6",
- "standard": "^5.2.2",
- "uglify-js": "^2.4.24"
- },
- "scripts": {
- "test": "./node_modules/.bin/mocha",
- "lint": "./node_modules/.bin/standard",
- "build": "./node_modules/.bin/browserify -t brfs -s ipfsAPI -e ./src/index.js | tee dist/ipfsapi.js | ./node_modules/.bin/uglifyjs -m > dist/ipfsapi.min.js"
- },
- "standard": {
- "ignore": [
- "dist/*"
- ]
- },
- "pre-commit": [
- "lint"
- ],
- "keywords": [
- "ipfs"
- ],
- "author": "Matt Bell ",
- "contributors": [
- "Travis Person ",
- "Jeromy Jonson "
- ],
- "license": "MIT",
- "bugs": {
- "url": "https://github.com/ipfs/node-ipfs-api/issues"
- },
- "homepage": "https://github.com/ipfs/node-ipfs-api"
-}
+module.exports = slice;
-},{}],106:[function(require,module,exports){
-var pkg = require('../package.json')
+},{}],70:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var createWrapper = require('lodash._createwrapper'),
+ slice = require('lodash._slice');
-exports = module.exports = {
- 'api-path': '/api/v0/',
- 'user-agent': '/node-' + pkg.name + '/' + pkg.version + '/',
- 'host': 'localhost',
- 'port': '5001'
+/**
+ * Creates a function that, when called, invokes `func` with the `this`
+ * binding of `thisArg` and prepends any additional `bind` arguments to those
+ * provided to the bound function.
+ *
+ * @static
+ * @memberOf _
+ * @category Functions
+ * @param {Function} func The function to bind.
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @param {...*} [arg] Arguments to be partially applied.
+ * @returns {Function} Returns the new bound function.
+ * @example
+ *
+ * var func = function(greeting) {
+ * return greeting + ' ' + this.name;
+ * };
+ *
+ * func = _.bind(func, { 'name': 'fred' }, 'hi');
+ * func();
+ * // => 'hi fred'
+ */
+function bind(func, thisArg) {
+ return arguments.length > 2
+ ? createWrapper(func, 17, slice(arguments, 2), null, thisArg)
+ : createWrapper(func, 1, null, null, thisArg);
}
-},{"../package.json":105}],107:[function(require,module,exports){
-(function (Buffer){
-var File = require('vinyl')
-var vinylfs = require('vinyl-fs-browser')
-var vmps = require('vinyl-multipart-stream')
-var stream = require('stream')
-var Merge = require('merge-stream')
+module.exports = bind;
-exports = module.exports = getFilesStream
+},{"lodash._createwrapper":61,"lodash._slice":69}],71:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.3 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var baseCreateCallback = require('lodash._basecreatecallback'),
+ baseIsEqual = require('lodash._baseisequal'),
+ isObject = require('lodash.isobject'),
+ keys = require('lodash.keys'),
+ property = require('lodash.property');
+
+/**
+ * Produces a callback bound to an optional `thisArg`. If `func` is a property
+ * name the created callback will return the property value for a given element.
+ * If `func` is an object the created callback will return `true` for elements
+ * that contain the equivalent object properties, otherwise it will return `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Utilities
+ * @param {*} [func=identity] The value to convert to a callback.
+ * @param {*} [thisArg] The `this` binding of the created callback.
+ * @param {number} [argCount] The number of arguments the callback accepts.
+ * @returns {Function} Returns a callback function.
+ * @example
+ *
+ * var characters = [
+ * { 'name': 'barney', 'age': 36 },
+ * { 'name': 'fred', 'age': 40 }
+ * ];
+ *
+ * // wrap to create custom callback shorthands
+ * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
+ * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
+ * return !match ? func(callback, thisArg) : function(object) {
+ * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
+ * };
+ * });
+ *
+ * _.filter(characters, 'age__gt38');
+ * // => [{ 'name': 'fred', 'age': 40 }]
+ */
+function createCallback(func, thisArg, argCount) {
+ var type = typeof func;
+ if (func == null || type == 'function') {
+ return baseCreateCallback(func, thisArg, argCount);
+ }
+ // handle "_.pluck" style callback shorthands
+ if (type != 'object') {
+ return property(func);
+ }
+ var props = keys(func),
+ key = props[0],
+ a = func[key];
-function getFilesStream (files, opts) {
- if (!files) return null
- if (!Array.isArray(files)) files = [files]
+ // handle "_.where" style callback shorthands
+ if (props.length == 1 && a === a && !isObject(a)) {
+ // fast path the common case of providing an object with a single
+ // property containing a primitive value
+ return function(object) {
+ var b = object[key];
+ return a === b && (a !== 0 || (1 / a == 1 / b));
+ };
+ }
+ return function(object) {
+ var length = props.length,
+ result = false;
- // merge all inputs into one stream
- var adder = new Merge()
+ while (length--) {
+ if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
+ break;
+ }
+ }
+ return result;
+ };
+}
- // single stream for pushing directly
- var single = new stream.PassThrough({objectMode: true})
- adder.add(single)
+module.exports = createCallback;
- for (var i = 0; i < files.length; i++) {
- var file = files[i]
+},{"lodash._basecreatecallback":58,"lodash._baseisequal":60,"lodash.isobject":77,"lodash.keys":78,"lodash.property":81}],72:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var createCallback = require('lodash.createcallback'),
+ forOwn = require('lodash.forown');
- if (typeof (file) === 'string') {
- var srcOpts = {
- buffer: false,
- stripBOM: false,
- followSymlinks: opts.followSymlinks != null ? opts.followSymlinks : true
- }
+/**
+ * Iterates over elements of a collection, returning an array of all elements
+ * the callback returns truey for. The callback is bound to `thisArg` and
+ * invoked with three arguments; (value, index|key, collection).
+ *
+ * If a property name is provided for `callback` the created "_.pluck" style
+ * callback will return the property value of the given element.
+ *
+ * If an object is provided for `callback` the created "_.where" style callback
+ * will return `true` for elements that have the properties of the given object,
+ * else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @alias select
+ * @category Collections
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [callback=identity] The function called
+ * per iteration. If a property name or object is provided it will be used
+ * to create a "_.pluck" or "_.where" style callback, respectively.
+ * @param {*} [thisArg] The `this` binding of `callback`.
+ * @returns {Array} Returns a new array of elements that passed the callback check.
+ * @example
+ *
+ * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
+ * // => [2, 4, 6]
+ *
+ * var characters = [
+ * { 'name': 'barney', 'age': 36, 'blocked': false },
+ * { 'name': 'fred', 'age': 40, 'blocked': true }
+ * ];
+ *
+ * // using "_.pluck" callback shorthand
+ * _.filter(characters, 'blocked');
+ * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
+ *
+ * // using "_.where" callback shorthand
+ * _.filter(characters, { 'age': 36 });
+ * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
+ */
+function filter(collection, callback, thisArg) {
+ var result = [];
+ callback = createCallback(callback, thisArg, 3);
- // add the file or dir itself
- adder.add(vinylfs.src(file, srcOpts))
+ var index = -1,
+ length = collection ? collection.length : 0;
- // if recursive, glob the contents
- if (opts.r || opts.recursive) {
- adder.add(vinylfs.src(file + '/**/*', srcOpts))
+ if (typeof length == 'number') {
+ while (++index < length) {
+ var value = collection[index];
+ if (callback(value, index, collection)) {
+ result.push(value);
}
- } else {
- // try to create a single vinyl file, and push it.
- // throws if cannot use the file.
- single.push(vinylFile(file))
}
+ } else {
+ forOwn(collection, function(value, index, collection) {
+ if (callback(value, index, collection)) {
+ result.push(value);
+ }
+ });
}
-
- single.end()
- return adder.pipe(vmps())
+ return result;
}
-// vinylFile tries to cast a file object to a vinyl file.
-// it's agressive. If it _cannot_ be converted to a file,
-// it returns null.
-function vinylFile (file) {
- if (file instanceof File) {
- return file // it's a vinyl file.
- }
-
- // let's try to make a vinyl file?
- var f = {cwd: '/', base: '/', path: ''}
- if (file.contents && file.path) {
- // set the cwd + base, if there.
- f.path = file.path
- f.cwd = file.cwd || f.cwd
- f.base = file.base || f.base
- f.contents = file.contents
- } else {
- // ok maybe we just have contents?
- f.contents = file
- }
+module.exports = filter;
- // ensure the contents are safe to pass.
- // throws if vinyl cannot use the contents
- f.contents = vinylContentsSafe(f.contents)
- return new File(f)
-}
+},{"lodash.createcallback":71,"lodash.forown":74}],73:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var baseCreateCallback = require('lodash._basecreatecallback'),
+ objectTypes = require('lodash._objecttypes');
-function vinylContentsSafe (c) {
- if (Buffer.isBuffer(c)) return c
- if (typeof (c) === 'string') return c
- if (c instanceof stream.Stream) return c
- if (typeof (c.pipe) === 'function') {
- // hey, looks like a stream. but vinyl won't detect it.
- // pipe it to a PassThrough, and use that
- var s = new stream.PassThrough()
- return c.pipe(s)
- }
+/**
+ * Iterates over own and inherited enumerable properties of an object,
+ * executing the callback for each property. The callback is bound to `thisArg`
+ * and invoked with three arguments; (value, key, object). Callbacks may exit
+ * iteration early by explicitly returning `false`.
+ *
+ * @static
+ * @memberOf _
+ * @type Function
+ * @category Objects
+ * @param {Object} object The object to iterate over.
+ * @param {Function} [callback=identity] The function called per iteration.
+ * @param {*} [thisArg] The `this` binding of `callback`.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * function Shape() {
+ * this.x = 0;
+ * this.y = 0;
+ * }
+ *
+ * Shape.prototype.move = function(x, y) {
+ * this.x += x;
+ * this.y += y;
+ * };
+ *
+ * _.forIn(new Shape, function(value, key) {
+ * console.log(key);
+ * });
+ * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
+ */
+var forIn = function(collection, callback, thisArg) {
+ var index, iterable = collection, result = iterable;
+ if (!iterable) return result;
+ if (!objectTypes[typeof iterable]) return result;
+ callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
+ for (index in iterable) {
+ if (callback(iterable[index], index, collection) === false) return result;
+ }
+ return result
+};
- throw new Error('vinyl will not accept: ' + c)
-}
+module.exports = forIn;
-}).call(this,{"isBuffer":require("/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js")})
-},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21,"merge-stream":51,"stream":81,"vinyl":96,"vinyl-fs-browser":110,"vinyl-multipart-stream":93}],108:[function(require,module,exports){
-(function (Buffer){
-var multiaddr = require('multiaddr')
-var config = require('./config')
-var requestAPI = require('./request-api')
+},{"lodash._basecreatecallback":58,"lodash._objecttypes":65}],74:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var baseCreateCallback = require('lodash._basecreatecallback'),
+ keys = require('lodash.keys'),
+ objectTypes = require('lodash._objecttypes');
-exports = module.exports = IpfsAPI
+/**
+ * Iterates over own enumerable properties of an object, executing the callback
+ * for each property. The callback is bound to `thisArg` and invoked with three
+ * arguments; (value, key, object). Callbacks may exit iteration early by
+ * explicitly returning `false`.
+ *
+ * @static
+ * @memberOf _
+ * @type Function
+ * @category Objects
+ * @param {Object} object The object to iterate over.
+ * @param {Function} [callback=identity] The function called per iteration.
+ * @param {*} [thisArg] The `this` binding of `callback`.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
+ * console.log(key);
+ * });
+ * // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
+ */
+var forOwn = function(collection, callback, thisArg) {
+ var index, iterable = collection, result = iterable;
+ if (!iterable) return result;
+ if (!objectTypes[typeof iterable]) return result;
+ callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
+ var ownIndex = -1,
+ ownProps = objectTypes[typeof iterable] && keys(iterable),
+ length = ownProps ? ownProps.length : 0;
-function IpfsAPI (host_or_multiaddr, port) {
- var self = this
+ while (++ownIndex < length) {
+ index = ownProps[ownIndex];
+ if (callback(iterable[index], index, collection) === false) return result;
+ }
+ return result
+};
- if (!(self instanceof IpfsAPI)) {
- return new IpfsAPI(host_or_multiaddr, port)
- }
+module.exports = forOwn;
- try {
- var maddr = multiaddr(host_or_multiaddr).nodeAddress()
- config.host = maddr.address
- config.port = maddr.port
- } catch (e) {
- config.host = host_or_multiaddr
- config.port = port || config.port
- }
+},{"lodash._basecreatecallback":58,"lodash._objecttypes":65,"lodash.keys":78}],75:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
- // autoconfigure in browser
- if (!config.host &&
- typeof window !== 'undefined') {
- var split = window.location.host.split(':')
- config.host = split[0]
- config.port = split[1]
- }
+/**
+ * This method returns the first argument provided to it.
+ *
+ * @static
+ * @memberOf _
+ * @category Utilities
+ * @param {*} value Any value.
+ * @returns {*} Returns `value`.
+ * @example
+ *
+ * var object = { 'name': 'fred' };
+ * _.identity(object) === object;
+ * // => true
+ */
+function identity(value) {
+ return value;
+}
- // -- Internal
+module.exports = identity;
- function command (name) {
- return function (opts, cb) {
- if (typeof (opts) === 'function') {
- cb = opts
- opts = {}
- }
- return requestAPI(name, null, opts, null, cb)
- }
- }
+},{}],76:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
- function argCommand (name) {
- return function (arg, opts, cb) {
- if (typeof (opts) === 'function') {
- cb = opts
- opts = {}
- }
- return requestAPI(name, arg, opts, null, cb)
- }
- }
+/**
+ * Checks if `value` is a function.
+ *
+ * @static
+ * @memberOf _
+ * @category Objects
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if the `value` is a function, else `false`.
+ * @example
+ *
+ * _.isFunction(_);
+ * // => true
+ */
+function isFunction(value) {
+ return typeof value == 'function';
+}
- // -- Interface
+module.exports = isFunction;
- self.send = requestAPI
+},{}],77:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var objectTypes = require('lodash._objecttypes');
- self.add = function (files, opts, cb) {
- if (typeof (opts) === 'function' && cb === undefined) {
- cb = opts
- opts = {}
- }
+/**
+ * Checks if `value` is the language type of Object.
+ * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
+ *
+ * @static
+ * @memberOf _
+ * @category Objects
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if the `value` is an object, else `false`.
+ * @example
+ *
+ * _.isObject({});
+ * // => true
+ *
+ * _.isObject([1, 2, 3]);
+ * // => true
+ *
+ * _.isObject(1);
+ * // => false
+ */
+function isObject(value) {
+ // check if the value is the ECMAScript language type of Object
+ // http://es5.github.io/#x8
+ // and avoid a V8 bug
+ // http://code.google.com/p/v8/issues/detail?id=2291
+ return !!(value && objectTypes[typeof value]);
+}
- return requestAPI('add', null, opts, files, cb)
- }
+module.exports = isObject;
- self.cat = argCommand('cat')
- self.ls = argCommand('ls')
+},{"lodash._objecttypes":65}],78:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var isNative = require('lodash._isnative'),
+ isObject = require('lodash.isobject'),
+ shimKeys = require('lodash._shimkeys');
- self.config = {
- get: argCommand('config'),
- set: function (key, value, opts, cb) {
- if (typeof (opts) === 'function') {
- cb = opts
- opts = {}
- }
- return requestAPI('config', [key, value], opts, null, cb)
- },
- show: function (cb) {
- return requestAPI('config/show', null, null, null, true, cb)
- },
- replace: function (file, cb) {
- return requestAPI('config/replace', null, null, file, cb)
- }
- }
+/* Native method shortcuts for methods with the same name as other `lodash` methods */
+var nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys;
- self.update = {
- apply: command('update'),
- check: command('update/check'),
- log: command('update/log')
+/**
+ * Creates an array composed of the own enumerable property names of an object.
+ *
+ * @static
+ * @memberOf _
+ * @category Objects
+ * @param {Object} object The object to inspect.
+ * @returns {Array} Returns an array of property names.
+ * @example
+ *
+ * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
+ * // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
+ */
+var keys = !nativeKeys ? shimKeys : function(object) {
+ if (!isObject(object)) {
+ return [];
}
+ return nativeKeys(object);
+};
- self.version = command('version')
- self.commands = command('commands')
+module.exports = keys;
- self.mount = function (ipfs, ipns, cb) {
- if (typeof ipfs === 'function') {
- cb = ipfs
- ipfs = null
- } else if (typeof ipns === 'function') {
- cb = ipns
- ipns = null
- }
- var opts = {}
- if (ipfs) opts.f = ipfs
- if (ipns) opts.n = ipns
- return requestAPI('mount', null, opts, null, cb)
- }
+},{"lodash._isnative":63,"lodash._shimkeys":68,"lodash.isobject":77}],79:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var createCallback = require('lodash.createcallback'),
+ forOwn = require('lodash.forown');
- self.diag = {
- net: command('diag/net')
- }
+/**
+ * Creates an array of values by running each element in the collection
+ * through the callback. The callback is bound to `thisArg` and invoked with
+ * three arguments; (value, index|key, collection).
+ *
+ * If a property name is provided for `callback` the created "_.pluck" style
+ * callback will return the property value of the given element.
+ *
+ * If an object is provided for `callback` the created "_.where" style callback
+ * will return `true` for elements that have the properties of the given object,
+ * else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @alias collect
+ * @category Collections
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [callback=identity] The function called
+ * per iteration. If a property name or object is provided it will be used
+ * to create a "_.pluck" or "_.where" style callback, respectively.
+ * @param {*} [thisArg] The `this` binding of `callback`.
+ * @returns {Array} Returns a new array of the results of each `callback` execution.
+ * @example
+ *
+ * _.map([1, 2, 3], function(num) { return num * 3; });
+ * // => [3, 6, 9]
+ *
+ * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
+ * // => [3, 6, 9] (property order is not guaranteed across environments)
+ *
+ * var characters = [
+ * { 'name': 'barney', 'age': 36 },
+ * { 'name': 'fred', 'age': 40 }
+ * ];
+ *
+ * // using "_.pluck" callback shorthand
+ * _.map(characters, 'name');
+ * // => ['barney', 'fred']
+ */
+function map(collection, callback, thisArg) {
+ var index = -1,
+ length = collection ? collection.length : 0;
- self.block = {
- get: argCommand('block/get'),
- put: function (file, cb) {
- if (Array.isArray(file)) {
- return cb(null, new Error('block.put() only accepts 1 file'))
- }
- return requestAPI('block/put', null, null, file, cb)
+ callback = createCallback(callback, thisArg, 3);
+ if (typeof length == 'number') {
+ var result = Array(length);
+ while (++index < length) {
+ result[index] = callback(collection[index], index, collection);
}
+ } else {
+ result = [];
+ forOwn(collection, function(value, key, collection) {
+ result[++index] = callback(value, key, collection);
+ });
}
+ return result;
+}
- self.object = {
- get: argCommand('object/get'),
- put: function (file, encoding, cb) {
- if (typeof encoding === 'function') {
- return cb(null, new Error("Must specify an object encoding ('json' or 'protobuf')"))
- }
- return requestAPI('object/put', encoding, null, file, cb)
- },
- data: argCommand('object/data'),
- stat: argCommand('object/stat'),
- links: argCommand('object/links')
- }
-
- self.swarm = {
- peers: command('swarm/peers'),
- connect: argCommand('swarm/peers')
- }
-
- self.ping = function (id, cb) {
- return requestAPI('ping', id, { n: 1 }, null, function (err, res) {
- if (err) return cb(err, null)
- cb(null, res[1])
- })
- }
-
- self.id = function (id, cb) {
- if (typeof id === 'function') {
- cb = id
- id = null
- }
- return requestAPI('id', id, null, null, cb)
- }
+module.exports = map;
- self.pin = {
- add: function (hash, opts, cb) {
- if (typeof opts === 'function') {
- cb = opts
- opts = null
- }
+},{"lodash.createcallback":71,"lodash.forown":74}],80:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
- requestAPI('pin/add', hash, opts, null, cb)
- },
- remove: function (hash, opts, cb) {
- if (typeof opts === 'function') {
- cb = opts
- opts = null
- }
+/**
+ * A no-operation function.
+ *
+ * @static
+ * @memberOf _
+ * @category Utilities
+ * @example
+ *
+ * var object = { 'name': 'fred' };
+ * _.noop(object) === undefined;
+ * // => true
+ */
+function noop() {
+ // no operation performed
+}
- requestAPI('pin/rm', hash, opts, null, cb)
- },
- list: function (type, cb) {
- if (typeof type === 'function') {
- cb = type
- type = null
- }
- var opts = null
- if (type) opts = { type: type }
- return requestAPI('pin/ls', null, opts, null, cb)
- }
- }
+module.exports = noop;
- self.gateway = {
- enable: command('gateway/enable'),
- disable: command('gateway/disable')
- }
+},{}],81:[function(require,module,exports){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
- self.log = {
- tail: function (cb) {
- return requestAPI('log/tail', null, {enc: 'text'}, null, true, cb)
- }
- }
+/**
+ * Creates a "_.pluck" style function, which returns the `key` value of a
+ * given object.
+ *
+ * @static
+ * @memberOf _
+ * @category Utilities
+ * @param {string} key The name of the property to retrieve.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var characters = [
+ * { 'name': 'fred', 'age': 40 },
+ * { 'name': 'barney', 'age': 36 }
+ * ];
+ *
+ * var getName = _.property('name');
+ *
+ * _.map(characters, getName);
+ * // => ['barney', 'fred']
+ *
+ * _.sortBy(characters, getName);
+ * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]
+ */
+function property(key) {
+ return function(object) {
+ return object[key];
+ };
+}
- self.name = {
- publish: argCommand('name/publish'),
- resolve: argCommand('name/resolve')
- }
+module.exports = property;
- self.Buffer = Buffer
+},{}],82:[function(require,module,exports){
+(function (global){
+/**
+ * Lo-Dash 2.4.1 (Custom Build)
+ * Build: `lodash modularize modern exports="npm" -o ./npm/`
+ * Copyright 2012-2013 The Dojo Foundation
+ * Based on Underscore.js 1.5.2
+ * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license
+ */
+var isNative = require('lodash._isnative');
- self.refs = argCommand('refs')
- self.refs.local = command('refs/local')
+/** Used to detect functions containing a `this` reference */
+var reThis = /\bthis\b/;
- self.dht = {
- findprovs: argCommand('dht/findprovs'),
+/**
+ * An object used to flag environments features.
+ *
+ * @static
+ * @memberOf _
+ * @type Object
+ */
+var support = {};
- get: function (key, opts, cb) {
- if (typeof (opts) === 'function' && !cb) {
- cb = opts
- opts = null
- }
+/**
+ * Detect if functions can be decompiled by `Function#toString`
+ * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
+ *
+ * @memberOf _.support
+ * @type boolean
+ */
+support.funcDecomp = !isNative(global.WinRTError) && reThis.test(function() { return this; });
- return requestAPI('dht/get', key, opts, null, function (err, res) {
- if (err) return cb(err)
- if (!res) return cb(new Error('empty response'))
- if (res.length === 0) return cb(new Error('no value returned for key'))
+/**
+ * Detect if `Function#name` is supported (all but IE).
+ *
+ * @memberOf _.support
+ * @type boolean
+ */
+support.funcNames = typeof Function.name == 'string';
- if (res[0].Type === 5) {
- cb(null, res[0].Extra)
- } else {
- cb(res)
- }
- })
- },
+module.exports = support;
- put: function (key, value, opts, cb) {
- if (typeof (opts) === 'function' && !cb) {
- cb = opts
- opts = null
- }
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"lodash._isnative":63}],83:[function(require,module,exports){
+'use strict';
- return requestAPI('dht/put', [key, value], opts, null, cb)
- }
- }
-}
+var PassThrough = require('readable-stream/passthrough')
-}).call(this,require("buffer").Buffer)
-},{"./config":106,"./request-api":109,"buffer":6,"multiaddr":54}],109:[function(require,module,exports){
-var http = require('http')
-var qs = require('querystring')
-var getFilesStream = require('./get-files-stream')
-var config = require('./config')
+module.exports = function (/*streams...*/) {
+ var sources = []
+ var output = new PassThrough({objectMode: true})
-exports = module.exports = requestAPI
+ output.setMaxListeners(0)
-function requestAPI (path, args, opts, files, buffer, cb) {
- var query, stream, contentType
- contentType = 'application/json'
+ output.add = add
+ output.isEmpty = isEmpty
- if (Array.isArray(path)) path = path.join('/')
+ output.on('unpipe', remove)
- opts = opts || {}
+ Array.prototype.slice.call(arguments).forEach(add)
- if (args && !Array.isArray(args)) args = [args]
- if (args) opts.arg = args
+ return output
- if (files) {
- stream = getFilesStream(files, opts)
- if (!stream.boundary) {
- throw new Error('no boundary in multipart stream')
+ function add (source) {
+ if (Array.isArray(source)) {
+ source.forEach(add)
+ return this
}
- contentType = 'multipart/form-data; boundary=' + stream.boundary
- }
- if (typeof buffer === 'function') {
- cb = buffer
- buffer = false
+ sources.push(source);
+ source.once('end', remove.bind(null, source))
+ source.pipe(output, {end: false})
+ return this
}
- // this option is only used internally, not passed to daemon
- delete opts.followSymlinks
-
- opts['stream-channels'] = true
- query = qs.stringify(opts)
+ function isEmpty () {
+ return sources.length == 0;
+ }
- var reqo = {
- method: files ? 'POST' : 'GET',
- host: config.host,
- port: config.port,
- path: config['api-path'] + path + '?' + query,
- headers: {
- 'User-Agent': config['user-agent'],
- 'Content-Type': contentType
- },
- withCredentials: false
+ function remove (source) {
+ sources = sources.filter(function (it) { return it !== source })
+ if (!sources.length && output.readable) { output.end() }
}
+}
- var req = http.request(reqo, function (res) {
- var data = ''
- var objects = []
- var stream = !!res.headers && !!res.headers['x-stream-output']
- var chunkedObjects = !!res.headers && !!res.headers['x-chunked-output']
+},{"readable-stream/passthrough":118}],84:[function(require,module,exports){
+module.exports = minimatch
+minimatch.Minimatch = Minimatch
- if (stream && !buffer) return cb(null, res)
- if (chunkedObjects && buffer) return cb(null, res)
+var path = { sep: '/' }
+try {
+ path = require('path')
+} catch (er) {}
- res.on('data', function (chunk) {
- if (!chunkedObjects) {
- data += chunk
- return data
- }
+var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
+var expand = require('brace-expansion')
- try {
- var obj = JSON.parse(chunk.toString())
- objects.push(obj)
- } catch (e) {
- chunkedObjects = false
- data += chunk
- }
- })
- res.on('end', function () {
- var parsed
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+var qmark = '[^/]'
- if (!chunkedObjects) {
- try {
- parsed = JSON.parse(data)
- data = parsed
- } catch (e) {}
- } else {
- data = objects
- }
+// * => any number of characters
+var star = qmark + '*?'
- if (res.statusCode >= 400 || !res.statusCode) {
- if (!data) data = new Error()
- return cb(data, null)
- }
- return cb(null, data)
- })
- res.on('error', function (err) {
- return cb(err, null)
- })
- })
+// ** when dots are allowed. Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
- req.on('error', function (err) {
- return cb(err, null)
- })
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
- if (stream) {
- stream.pipe(req)
- } else {
- req.end()
- }
+// characters that need to be escaped in RegExp.
+var reSpecials = charSet('().*{}+?[]^$\\!')
- return req
+// "abc" -> { a:true, b:true, c:true }
+function charSet (s) {
+ return s.split('').reduce(function (set, c) {
+ set[c] = true
+ return set
+ }, {})
}
-},{"./config":106,"./get-files-stream":107,"http":82,"querystring":68}],110:[function(require,module,exports){
-'use strict';
+// normalizes slashes.
+var slashSplit = /\/+/
-module.exports = {
- src: require('./lib/src'),
- dest: require('./lib/dest'),
- symlink: require('./lib/symlink')
-};
+minimatch.filter = filter
+function filter (pattern, options) {
+ options = options || {}
+ return function (p, i, list) {
+ return minimatch(p, pattern, options)
+ }
+}
-},{"./lib/dest":111,"./lib/src":124,"./lib/symlink":126}],111:[function(require,module,exports){
-(function (process){
-'use strict';
+function ext (a, b) {
+ a = a || {}
+ b = b || {}
+ var t = {}
+ Object.keys(b).forEach(function (k) {
+ t[k] = b[k]
+ })
+ Object.keys(a).forEach(function (k) {
+ t[k] = a[k]
+ })
+ return t
+}
-var through2 = require('through2');
-var sourcemaps = process.browser ? null : require('gulp-sourcemaps');
-var duplexify = require('duplexify');
-var prepareWrite = require('../prepareWrite');
-var writeContents = require('./writeContents');
+minimatch.defaults = function (def) {
+ if (!def || !Object.keys(def).length) return minimatch
-function dest(outFolder, opt) {
- if (!opt) {
- opt = {};
- }
+ var orig = minimatch
- function saveFile(file, enc, cb) {
- prepareWrite(outFolder, file, opt, function(err, writePath) {
- if (err) {
- return cb(err);
- }
- writeContents(writePath, file, cb);
- });
+ var m = function minimatch (p, pattern, options) {
+ return orig.minimatch(p, pattern, ext(def, options))
}
- var saveStream = through2.obj(saveFile);
- if (!opt.sourcemaps) {
- return saveStream;
+ m.Minimatch = function Minimatch (pattern, options) {
+ return new orig.Minimatch(pattern, ext(def, options))
}
- var mapStream = sourcemaps.write(opt.sourcemaps.path, opt.sourcemaps);
- var outputStream = duplexify.obj(mapStream, saveStream);
- mapStream.pipe(saveStream);
-
- return outputStream;
+ return m
}
-module.exports = dest;
-
-}).call(this,require('_process'))
-},{"../prepareWrite":118,"./writeContents":112,"_process":64,"duplexify":127,"gulp-sourcemaps":188,"through2":248}],112:[function(require,module,exports){
-'use strict';
-
-
-var writeDir = require('./writeDir');
-var writeStream = require('./writeStream');
-var writeBuffer = require('./writeBuffer');
-var writeSymbolicLink = require('./writeSymbolicLink');
+Minimatch.defaults = function (def) {
+ if (!def || !Object.keys(def).length) return Minimatch
+ return minimatch.defaults(def).Minimatch
+}
-function writeContents(writePath, file, cb) {
- // if directory then mkdirp it
- if (file.isDirectory()) {
- return writeDir(writePath, file, written);
+function minimatch (p, pattern, options) {
+ if (typeof pattern !== 'string') {
+ throw new TypeError('glob pattern string required')
}
- // stream it to disk yo
- if (file.isStream()) {
- return writeStream(writePath, file, written);
- }
+ if (!options) options = {}
- // write it as a symlink
- if (file.symlink) {
- return writeSymbolicLink(writePath, file, written);
+ // shortcut: comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ return false
}
- // write it like normal
- if (file.isBuffer()) {
- return writeBuffer(writePath, file, written);
- }
+ // "" only matches ""
+ if (pattern.trim() === '') return p === ''
- // if no contents then do nothing
- if (file.isNull()) {
- return complete();
- }
+ return new Minimatch(pattern, options).match(p)
+}
- function complete(err) {
- cb(err, file);
+function Minimatch (pattern, options) {
+ if (!(this instanceof Minimatch)) {
+ return new Minimatch(pattern, options)
}
- function written(err) {
-
- if (isErrorFatal(err)) {
- return complete(err);
- }
+ if (typeof pattern !== 'string') {
+ throw new TypeError('glob pattern string required')
+ }
- if (!file.stat || typeof file.stat.mode !== 'number' || file.symlink) {
- return complete();
- }
+ if (!options) options = {}
+ pattern = pattern.trim()
- fs.stat(writePath, function(err, st) {
- if (err) {
- return complete(err);
- }
- var currentMode = (st.mode & parseInt('0777', 8));
- var expectedMode = (file.stat.mode & parseInt('0777', 8));
- if (currentMode === expectedMode) {
- return complete();
- }
- fs.chmod(writePath, expectedMode, complete);
- });
+ // windows support: need to use /, not \
+ if (path.sep !== '/') {
+ pattern = pattern.split(path.sep).join('/')
}
- function isErrorFatal(err) {
- if (!err) {
- return false;
- }
-
- // Handle scenario for file overwrite failures.
- else if (err.code === 'EEXIST' && file.flag === 'wx') {
- return false; // "These aren't the droids you're looking for"
- }
+ this.options = options
+ this.set = []
+ this.pattern = pattern
+ this.regexp = null
+ this.negate = false
+ this.comment = false
+ this.empty = false
- // Otherwise, this is a fatal error
- return true;
- }
+ // make the set of regexps etc.
+ this.make()
}
-module.exports = writeContents;
+Minimatch.prototype.debug = function () {}
-},{"./writeBuffer":113,"./writeDir":114,"./writeStream":115,"./writeSymbolicLink":116}],113:[function(require,module,exports){
-(function (process){
-'use strict';
+Minimatch.prototype.make = make
+function make () {
+ // don't do it more than once.
+ if (this._made) return
-var fs = process.browser ? require('fs') : require('graceful-fs');
+ var pattern = this.pattern
+ var options = this.options
-function writeBuffer(writePath, file, cb) {
- var opt = {
- mode: file.stat.mode,
- flag: file.flag
- };
+ // empty patterns and comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ this.comment = true
+ return
+ }
+ if (!pattern) {
+ this.empty = true
+ return
+ }
- fs.writeFile(writePath, file.contents, opt, cb);
-}
+ // step 1: figure out negation, etc.
+ this.parseNegate()
-module.exports = writeBuffer;
+ // step 2: expand braces
+ var set = this.globSet = this.braceExpand()
-}).call(this,require('_process'))
-},{"_process":64,"fs":4,"graceful-fs":185}],114:[function(require,module,exports){
-'use strict';
+ if (options.debug) this.debug = console.error
-var mkdirp = require('mkdirp');
+ this.debug(this.pattern, set)
-function writeDir(writePath, file, cb) {
- mkdirp(writePath, file.stat.mode, cb);
-}
+ // step 3: now we have a set, so turn each one into a series of path-portion
+ // matching patterns.
+ // These will be regexps, except in the case of "**", which is
+ // set to the GLOBSTAR object for globstar behavior,
+ // and will not contain any / characters
+ set = this.globParts = set.map(function (s) {
+ return s.split(slashSplit)
+ })
-module.exports = writeDir;
+ this.debug(this.pattern, set)
+
+ // glob --> regexps
+ set = set.map(function (s, si, set) {
+ return s.map(this.parse, this)
+ }, this)
-},{"mkdirp":230}],115:[function(require,module,exports){
-(function (process){
-'use strict';
+ this.debug(this.pattern, set)
-var streamFile = require('../../src/getContents/streamFile');
-var fs = process.browser ? require('fs') : require('graceful-fs');
+ // filter out everything that didn't compile properly.
+ set = set.filter(function (s) {
+ return s.indexOf(false) === -1
+ })
-function writeStream(writePath, file, cb) {
- var opt = {
- mode: file.stat.mode,
- flag: file.flag
- };
+ this.debug(this.pattern, set)
- var outStream = fs.createWriteStream(writePath, opt);
+ this.set = set
+}
- file.contents.once('error', complete);
- outStream.once('error', complete);
- outStream.once('finish', success);
+Minimatch.prototype.parseNegate = parseNegate
+function parseNegate () {
+ var pattern = this.pattern
+ var negate = false
+ var options = this.options
+ var negateOffset = 0
- file.contents.pipe(outStream);
+ if (options.nonegate) return
- function success() {
- streamFile(file, {}, complete);
+ for (var i = 0, l = pattern.length
+ ; i < l && pattern.charAt(i) === '!'
+ ; i++) {
+ negate = !negate
+ negateOffset++
}
- // cleanup
- function complete(err) {
- file.contents.removeListener('error', cb);
- outStream.removeListener('error', cb);
- outStream.removeListener('finish', success);
- cb(err);
- }
+ if (negateOffset) this.pattern = pattern.substr(negateOffset)
+ this.negate = negate
}
-module.exports = writeStream;
-
-}).call(this,require('_process'))
-},{"../../src/getContents/streamFile":123,"_process":64,"fs":4,"graceful-fs":185}],116:[function(require,module,exports){
-(function (process){
-'use strict';
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+minimatch.braceExpand = function (pattern, options) {
+ return braceExpand(pattern, options)
+}
-var fs = process.browser ? require('fs') : require('graceful-fs');
+Minimatch.prototype.braceExpand = braceExpand
-function writeSymbolicLink(writePath, file, cb) {
- fs.symlink(file.symlink, writePath, function (err) {
- if (err && err.code !== 'EEXIST') {
- return cb(err);
+function braceExpand (pattern, options) {
+ if (!options) {
+ if (this instanceof Minimatch) {
+ options = this.options
+ } else {
+ options = {}
}
+ }
- cb(null, file);
- });
-}
+ pattern = typeof pattern === 'undefined'
+ ? this.pattern : pattern
-module.exports = writeSymbolicLink;
+ if (typeof pattern === 'undefined') {
+ throw new Error('undefined pattern')
+ }
-}).call(this,require('_process'))
-},{"_process":64,"fs":4,"graceful-fs":185}],117:[function(require,module,exports){
-'use strict';
+ if (options.nobrace ||
+ !pattern.match(/\{.*\}/)) {
+ // shortcut. no need to expand.
+ return [pattern]
+ }
-var filter = require('through2-filter');
+ return expand(pattern)
+}
-module.exports = function(d) {
- var isValid = typeof d === 'number' ||
- d instanceof Number ||
- d instanceof Date;
+// parse a component of the expanded set.
+// At this point, no pattern may contain "/" in it
+// so we're going to return a 2d array, where each entry is the full
+// pattern, split on '/', and then turned into a regular expression.
+// A regexp is made at the end which joins each array with an
+// escaped /, and another full one which joins each regexp with |.
+//
+// Following the lead of Bash 4.1, note that "**" only has special meaning
+// when it is the *only* thing in a path portion. Otherwise, any series
+// of * is equivalent to a single *. Globstar behavior is enabled by
+// default, and can be disabled by setting options.noglobstar.
+Minimatch.prototype.parse = parse
+var SUBPARSE = {}
+function parse (pattern, isSub) {
+ var options = this.options
- if (!isValid) {
- throw new Error('expected since option to be a date or a number');
- }
- return filter.obj(function(file){
- return file.stat && file.stat.mtime > d;
- });
-};
-},{"through2-filter":234}],118:[function(require,module,exports){
-(function (process){
-'use strict';
+ // shortcuts
+ if (!options.noglobstar && pattern === '**') return GLOBSTAR
+ if (pattern === '') return ''
-var assign = require('object-assign');
-var path = require('path');
-var mkdirp = require('mkdirp');
-var fs = process.browser ? require('fs') : require('graceful-fs');
+ var re = ''
+ var hasMagic = !!options.nocase
+ var escaping = false
+ // ? => one single character
+ var patternListStack = []
+ var negativeLists = []
+ var plType
+ var stateChar
+ var inClass = false
+ var reClassStart = -1
+ var classStart = -1
+ // . and .. never match anything that doesn't start with .,
+ // even when options.dot is set.
+ var patternStart = pattern.charAt(0) === '.' ? '' // anything
+ // not (start or / followed by . or .. followed by / or end)
+ : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
+ : '(?!\\.)'
+ var self = this
-function booleanOrFunc(v, file) {
- if (typeof v !== 'boolean' && typeof v !== 'function') {
- return null;
+ function clearStateChar () {
+ if (stateChar) {
+ // we had some state-tracking character
+ // that wasn't consumed by this pass.
+ switch (stateChar) {
+ case '*':
+ re += star
+ hasMagic = true
+ break
+ case '?':
+ re += qmark
+ hasMagic = true
+ break
+ default:
+ re += '\\' + stateChar
+ break
+ }
+ self.debug('clearStateChar %j %j', stateChar, re)
+ stateChar = false
+ }
}
- return typeof v === 'boolean' ? v : v(file);
-}
+ for (var i = 0, len = pattern.length, c
+ ; (i < len) && (c = pattern.charAt(i))
+ ; i++) {
+ this.debug('%s\t%s %s %j', pattern, i, re, c)
-function stringOrFunc(v, file) {
- if (typeof v !== 'string' && typeof v !== 'function') {
- return null;
- }
+ // skip over any that are escaped.
+ if (escaping && reSpecials[c]) {
+ re += '\\' + c
+ escaping = false
+ continue
+ }
- return typeof v === 'string' ? v : v(file);
-}
+ switch (c) {
+ case '/':
+ // completely not allowed, even escaped.
+ // Should already be path-split by now.
+ return false
-function prepareWrite(outFolder, file, opt, cb) {
- var options = assign({
- cwd: process.cwd(),
- mode: (file.stat ? file.stat.mode : null),
- dirMode: null,
- overwrite: true
- }, opt);
- var overwrite = booleanOrFunc(options.overwrite, file);
- options.flag = (overwrite ? 'w' : 'wx');
+ case '\\':
+ clearStateChar()
+ escaping = true
+ continue
- var cwd = path.resolve(options.cwd);
- var outFolderPath = stringOrFunc(outFolder, file);
- if (!outFolderPath) {
- throw new Error('Invalid output folder');
- }
- var basePath = options.base ?
- stringOrFunc(options.base, file) : path.resolve(cwd, outFolderPath);
- if (!basePath) {
- throw new Error('Invalid base option');
- }
+ // the various stateChar values
+ // for the "extglob" stuff.
+ case '?':
+ case '*':
+ case '+':
+ case '@':
+ case '!':
+ this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
- var writePath = path.resolve(basePath, file.relative);
- var writeFolder = path.dirname(writePath);
+ // all of those are literals inside a class, except that
+ // the glob [!a] means [^a] in regexp
+ if (inClass) {
+ this.debug(' in class')
+ if (c === '!' && i === classStart + 1) c = '^'
+ re += c
+ continue
+ }
+
+ // if we already have a stateChar, then it means
+ // that there was something like ** or +? in there.
+ // Handle the stateChar, then proceed with this one.
+ self.debug('call clearStateChar %j', stateChar)
+ clearStateChar()
+ stateChar = c
+ // if extglob is disabled, then +(asdf|foo) isn't a thing.
+ // just clear the statechar *now*, rather than even diving into
+ // the patternList stuff.
+ if (options.noext) clearStateChar()
+ continue
+
+ case '(':
+ if (inClass) {
+ re += '('
+ continue
+ }
- // wire up new properties
- file.stat = (file.stat || new fs.Stats());
- file.stat.mode = options.mode;
- file.flag = options.flag;
- file.cwd = cwd;
- file.base = basePath;
- file.path = writePath;
+ if (!stateChar) {
+ re += '\\('
+ continue
+ }
- // mkdirp the folder the file is going in
- mkdirp(writeFolder, options.dirMode, function(err){
- if (err) {
- return cb(err);
- }
- cb(null, writePath);
- });
-}
+ plType = stateChar
+ patternListStack.push({
+ type: plType,
+ start: i - 1,
+ reStart: re.length
+ })
+ // negation is (?:(?!js)[^/]*)
+ re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
+ this.debug('plType %j %j', stateChar, re)
+ stateChar = false
+ continue
-module.exports = prepareWrite;
+ case ')':
+ if (inClass || !patternListStack.length) {
+ re += '\\)'
+ continue
+ }
-}).call(this,require('_process'))
-},{"_process":64,"fs":4,"graceful-fs":185,"mkdirp":230,"object-assign":231,"path":62}],119:[function(require,module,exports){
-(function (process){
-'use strict';
+ clearStateChar()
+ hasMagic = true
+ re += ')'
+ var pl = patternListStack.pop()
+ plType = pl.type
+ // negation is (?:(?!js)[^/]*)
+ // The others are (?:)
+ switch (plType) {
+ case '!':
+ negativeLists.push(pl)
+ re += ')[^/]*?)'
+ pl.reEnd = re.length
+ break
+ case '?':
+ case '+':
+ case '*':
+ re += plType
+ break
+ case '@': break // the default anyway
+ }
+ continue
-var fs = process.browser ? require('fs') : require('graceful-fs');
-var stripBom = require('strip-bom');
+ case '|':
+ if (inClass || !patternListStack.length || escaping) {
+ re += '\\|'
+ escaping = false
+ continue
+ }
-function bufferFile(file, opt, cb) {
- fs.readFile(file.path, function(err, data) {
- if (err) {
- return cb(err);
- }
+ clearStateChar()
+ re += '|'
+ continue
- if (opt.stripBOM){
- file.contents = stripBom(data);
- } else {
- file.contents = data;
- }
+ // these are mostly the same in regexp and glob
+ case '[':
+ // swallow any state-tracking char before the [
+ clearStateChar()
- cb(null, file);
- });
-}
+ if (inClass) {
+ re += '\\' + c
+ continue
+ }
-module.exports = bufferFile;
+ inClass = true
+ classStart = i
+ reClassStart = re.length
+ re += c
+ continue
-}).call(this,require('_process'))
-},{"_process":64,"fs":4,"graceful-fs":185,"strip-bom":233}],120:[function(require,module,exports){
-'use strict';
+ case ']':
+ // a right bracket shall lose its special
+ // meaning and represent itself in
+ // a bracket expression if it occurs
+ // first in the list. -- POSIX.2 2.8.3.2
+ if (i === classStart + 1 || !inClass) {
+ re += '\\' + c
+ escaping = false
+ continue
+ }
-var through2 = require('through2');
-var readDir = require('./readDir');
-var readSymbolicLink = require('./readSymbolicLink');
-var bufferFile = require('./bufferFile');
-var streamFile = require('./streamFile');
+ // handle the case where we left a class open.
+ // "[z-a]" is valid, equivalent to "\[z-a\]"
+ if (inClass) {
+ // split where the last [ was, make sure we don't have
+ // an invalid re. if so, re-walk the contents of the
+ // would-be class to re-translate any characters that
+ // were passed through as-is
+ // TODO: It would probably be faster to determine this
+ // without a try/catch and a new RegExp, but it's tricky
+ // to do safely. For now, this is safe and works.
+ var cs = pattern.substring(classStart + 1, i)
+ try {
+ RegExp('[' + cs + ']')
+ } catch (er) {
+ // not a valid class!
+ var sp = this.parse(cs, SUBPARSE)
+ re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
+ hasMagic = hasMagic || sp[1]
+ inClass = false
+ continue
+ }
+ }
-function getContents(opt) {
- return through2.obj(function(file, enc, cb) {
- // don't fail to read a directory
- if (file.isDirectory()) {
- return readDir(file, opt, cb);
- }
+ // finish up the class.
+ hasMagic = true
+ inClass = false
+ re += c
+ continue
- // process symbolic links included with `followSymlinks` option
- if (file.stat && file.stat.isSymbolicLink()) {
- return readSymbolicLink(file, opt, cb);
- }
+ default:
+ // swallow any state char that wasn't consumed
+ clearStateChar()
- // read and pass full contents
- if (opt.buffer !== false) {
- return bufferFile(file, opt, cb);
- }
+ if (escaping) {
+ // no need
+ escaping = false
+ } else if (reSpecials[c]
+ && !(c === '^' && inClass)) {
+ re += '\\'
+ }
- // dont buffer anything - just pass streams
- return streamFile(file, opt, cb);
- });
-}
+ re += c
-module.exports = getContents;
+ } // switch
+ } // for
-},{"./bufferFile":119,"./readDir":121,"./readSymbolicLink":122,"./streamFile":123,"through2":248}],121:[function(require,module,exports){
-'use strict';
+ // handle the case where we left a class open.
+ // "[abc" is valid, equivalent to "\[abc"
+ if (inClass) {
+ // split where the last [ was, and escape it
+ // this is a huge pita. We now have to re-walk
+ // the contents of the would-be class to re-translate
+ // any characters that were passed through as-is
+ cs = pattern.substr(classStart + 1)
+ sp = this.parse(cs, SUBPARSE)
+ re = re.substr(0, reClassStart) + '\\[' + sp[0]
+ hasMagic = hasMagic || sp[1]
+ }
-function readDir(file, opt, cb) {
- // do nothing for now
- cb(null, file);
-}
+ // handle the case where we had a +( thing at the *end*
+ // of the pattern.
+ // each pattern list stack adds 3 chars, and we need to go through
+ // and escape any | chars that were passed through as-is for the regexp.
+ // Go through and escape them, taking care not to double-escape any
+ // | chars that were already escaped.
+ for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
+ var tail = re.slice(pl.reStart + 3)
+ // maybe some even number of \, then maybe 1 \, followed by a |
+ tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
+ if (!$2) {
+ // the | isn't already escaped, so escape it.
+ $2 = '\\'
+ }
-module.exports = readDir;
+ // need to escape all those slashes *again*, without escaping the
+ // one that we need for escaping the | character. As it works out,
+ // escaping an even number of slashes can be done by simply repeating
+ // it exactly after itself. That's why this trick works.
+ //
+ // I am sorry that you have to see this.
+ return $1 + $1 + $2 + '|'
+ })
-},{}],122:[function(require,module,exports){
-(function (process){
-'use strict';
+ this.debug('tail=%j\n %s', tail, tail)
+ var t = pl.type === '*' ? star
+ : pl.type === '?' ? qmark
+ : '\\' + pl.type
-var fs = process.browser ? require('fs') : require('graceful-fs');
+ hasMagic = true
+ re = re.slice(0, pl.reStart) + t + '\\(' + tail
+ }
-function readLink(file, opt, cb) {
- fs.readlink(file.path, function (err, target) {
- if (err) {
- return cb(err);
- }
+ // handle trailing things that only matter at the very end.
+ clearStateChar()
+ if (escaping) {
+ // trailing \\
+ re += '\\\\'
+ }
- // store the link target path
- file.symlink = target;
+ // only need to apply the nodot start if the re starts with
+ // something that could conceivably capture a dot
+ var addPatternStart = false
+ switch (re.charAt(0)) {
+ case '.':
+ case '[':
+ case '(': addPatternStart = true
+ }
- return cb(null, file);
- });
-}
+ // Hack to work around lack of negative lookbehind in JS
+ // A pattern like: *.!(x).!(y|z) needs to ensure that a name
+ // like 'a.xyz.yz' doesn't match. So, the first negative
+ // lookahead, has to look ALL the way ahead, to the end of
+ // the pattern.
+ for (var n = negativeLists.length - 1; n > -1; n--) {
+ var nl = negativeLists[n]
+
+ var nlBefore = re.slice(0, nl.reStart)
+ var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
+ var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
+ var nlAfter = re.slice(nl.reEnd)
-module.exports = readLink;
+ nlLast += nlAfter
-}).call(this,require('_process'))
-},{"_process":64,"fs":4,"graceful-fs":185}],123:[function(require,module,exports){
-(function (process){
-'use strict';
+ // Handle nested stuff like *(*.js|!(*.json)), where open parens
+ // mean that we should *not* include the ) in the bit that is considered
+ // "after" the negated section.
+ var openParensBefore = nlBefore.split('(').length - 1
+ var cleanAfter = nlAfter
+ for (i = 0; i < openParensBefore; i++) {
+ cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
+ }
+ nlAfter = cleanAfter
-var fs = process.browser ? require('fs') : require('graceful-fs');
-var stripBom = require('strip-bom-stream');
+ var dollar = ''
+ if (nlAfter === '' && isSub !== SUBPARSE) {
+ dollar = '$'
+ }
+ var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
+ re = newRe
+ }
-function streamFile(file, opt, cb) {
- file.contents = fs.createReadStream(file.path);
+ // if the re is not "" at this point, then we need to make sure
+ // it doesn't match against an empty path part.
+ // Otherwise a/* will match a/, which it should not.
+ if (re !== '' && hasMagic) {
+ re = '(?=.)' + re
+ }
- if (opt.stripBOM) {
- file.contents = file.contents.pipe(stripBom());
+ if (addPatternStart) {
+ re = patternStart + re
}
- cb(null, file);
-}
+ // parsing just a piece of a larger pattern.
+ if (isSub === SUBPARSE) {
+ return [re, hasMagic]
+ }
-module.exports = streamFile;
+ // skip the regexp for non-magical patterns
+ // unescape anything in it, though, so that it'll be
+ // an exact match against a file etc.
+ if (!hasMagic) {
+ return globUnescape(pattern)
+ }
-}).call(this,require('_process'))
-},{"_process":64,"fs":4,"graceful-fs":185,"strip-bom-stream":232}],124:[function(require,module,exports){
-(function (process){
-'use strict';
+ var flags = options.nocase ? 'i' : ''
+ var regExp = new RegExp('^' + re + '$', flags)
-var assign = require('object-assign');
-var through = require('through2');
-var gs = require('glob-stream');
-var File = require('vinyl');
-var duplexify = require('duplexify');
-var merge = require('merge-stream');
-var sourcemaps = process.browser ? null : require('gulp-sourcemaps');
-var filterSince = require('../filterSince');
-var isValidGlob = require('is-valid-glob');
+ regExp._glob = pattern
+ regExp._src = re
-var getContents = require('./getContents');
-var resolveSymlinks = require('./resolveSymlinks');
+ return regExp
+}
-function createFile(globFile, enc, cb) {
- cb(null, new File(globFile));
+minimatch.makeRe = function (pattern, options) {
+ return new Minimatch(pattern, options || {}).makeRe()
}
-function src(glob, opt) {
- var options = assign({
- read: true,
- buffer: true,
- stripBOM: true,
- sourcemaps: false,
- passthrough: false,
- followSymlinks: true
- }, opt);
+Minimatch.prototype.makeRe = makeRe
+function makeRe () {
+ if (this.regexp || this.regexp === false) return this.regexp
- var inputPass;
+ // at this point, this.set is a 2d array of partial
+ // pattern strings, or "**".
+ //
+ // It's better to use .match(). This function shouldn't
+ // be used, really, but it's pretty convenient sometimes,
+ // when you just want to work with a regex.
+ var set = this.set
- if (!isValidGlob(glob)) {
- throw new Error('Invalid glob argument: ' + glob);
+ if (!set.length) {
+ this.regexp = false
+ return this.regexp
}
+ var options = this.options
- var globStream = gs.create(glob, options);
+ var twoStar = options.noglobstar ? star
+ : options.dot ? twoStarDot
+ : twoStarNoDot
+ var flags = options.nocase ? 'i' : ''
- var outputStream = globStream
- .pipe(resolveSymlinks(options))
- .pipe(through.obj(createFile));
+ var re = set.map(function (pattern) {
+ return pattern.map(function (p) {
+ return (p === GLOBSTAR) ? twoStar
+ : (typeof p === 'string') ? regExpEscape(p)
+ : p._src
+ }).join('\\\/')
+ }).join('|')
- if (options.since != null) {
- outputStream = outputStream
- .pipe(filterSince(options.since));
- }
+ // must match entire pattern
+ // ending in a * or ** will make it less strict.
+ re = '^(?:' + re + ')$'
- if (options.read !== false) {
- outputStream = outputStream
- .pipe(getContents(options));
- }
+ // can match anything, as long as it's not this.
+ if (this.negate) re = '^(?!' + re + ').*$'
- if (options.passthrough === true) {
- inputPass = through.obj();
- outputStream = duplexify.obj(inputPass, merge(outputStream, inputPass));
- }
- if (options.sourcemaps === true) {
- outputStream = outputStream
- .pipe(sourcemaps.init({loadMaps: true}));
+ try {
+ this.regexp = new RegExp(re, flags)
+ } catch (ex) {
+ this.regexp = false
}
- globStream.on('error', outputStream.emit.bind(outputStream, 'error'));
- return outputStream;
+ return this.regexp
}
-module.exports = src;
-
-}).call(this,require('_process'))
-},{"../filterSince":117,"./getContents":120,"./resolveSymlinks":125,"_process":64,"duplexify":127,"glob-stream":144,"gulp-sourcemaps":188,"is-valid-glob":216,"merge-stream":217,"object-assign":231,"through2":248,"vinyl":249}],125:[function(require,module,exports){
-(function (process){
-'use strict';
-
-var through2 = require('through2');
-var fs = process.browser ? require('fs') : require('graceful-fs');
-var path = require('path');
-
-function resolveSymlinks(options) {
-
- // a stat property is exposed on file objects as a (wanted) side effect
- function resolveFile(globFile, enc, cb) {
- fs.lstat(globFile.path, function (err, stat) {
- if (err) {
- return cb(err);
- }
-
- globFile.stat = stat;
+minimatch.match = function (list, pattern, options) {
+ options = options || {}
+ var mm = new Minimatch(pattern, options)
+ list = list.filter(function (f) {
+ return mm.match(f)
+ })
+ if (mm.options.nonull && !list.length) {
+ list.push(pattern)
+ }
+ return list
+}
- if (!stat.isSymbolicLink() || !options.followSymlinks) {
- return cb(null, globFile);
- }
+Minimatch.prototype.match = match
+function match (f, partial) {
+ this.debug('match', f, this.pattern)
+ // short-circuit in the case of busted things.
+ // comments, etc.
+ if (this.comment) return false
+ if (this.empty) return f === ''
- fs.realpath(globFile.path, function (err, filePath) {
- if (err) {
- return cb(err);
- }
+ if (f === '/' && partial) return true
- globFile.base = path.dirname(filePath);
- globFile.path = filePath;
+ var options = this.options
- // recurse to get real file stat
- resolveFile(globFile, enc, cb);
- });
- });
+ // windows: need to use /, not \
+ if (path.sep !== '/') {
+ f = f.split(path.sep).join('/')
}
- return through2.obj(resolveFile);
-}
+ // treat the test path as a set of pathparts.
+ f = f.split(slashSplit)
+ this.debug(this.pattern, 'split', f)
-module.exports = resolveSymlinks;
+ // just ONE of the pattern sets in this.set needs to match
+ // in order for it to be valid. If negating, then just one
+ // match means that we have failed.
+ // Either way, return on the first hit.
-}).call(this,require('_process'))
-},{"_process":64,"fs":4,"graceful-fs":185,"path":62,"through2":248}],126:[function(require,module,exports){
-(function (process){
-'use strict';
+ var set = this.set
+ this.debug(this.pattern, 'set', set)
-var through2 = require('through2');
-var fs = process.browser ? require('fs') : require('graceful-fs');
-var prepareWrite = require('../prepareWrite');
+ // Find the basename of the path by looking for the last non-empty segment
+ var filename
+ var i
+ for (i = f.length - 1; i >= 0; i--) {
+ filename = f[i]
+ if (filename) break
+ }
-function symlink(outFolder, opt) {
- function linkFile(file, enc, cb) {
- var srcPath = file.path;
- var symType = (file.isDirectory() ? 'dir' : 'file');
- prepareWrite(outFolder, file, opt, function(err, writePath) {
- if (err) {
- return cb(err);
- }
- fs.symlink(srcPath, writePath, symType, function(err) {
- if (err && err.code !== 'EEXIST') {
- return cb(err);
- }
- cb(null, file);
- });
- });
+ for (i = 0; i < set.length; i++) {
+ var pattern = set[i]
+ var file = f
+ if (options.matchBase && pattern.length === 1) {
+ file = [filename]
+ }
+ var hit = this.matchOne(file, pattern, partial)
+ if (hit) {
+ if (options.flipNegate) return true
+ return !this.negate
+ }
}
- var stream = through2.obj(linkFile);
- // TODO: option for either backpressure or lossy
- stream.resume();
- return stream;
+ // didn't get any hits. this is success if it's a negative
+ // pattern, failure otherwise.
+ if (options.flipNegate) return false
+ return this.negate
}
-module.exports = symlink;
-
-}).call(this,require('_process'))
-},{"../prepareWrite":118,"_process":64,"fs":4,"graceful-fs":185,"through2":248}],127:[function(require,module,exports){
-arguments[4][12][0].apply(exports,arguments)
-},{"_process":64,"buffer":6,"dup":12,"end-of-stream":128,"readable-stream":142,"util":90}],128:[function(require,module,exports){
-arguments[4][13][0].apply(exports,arguments)
-},{"dup":13,"once":130}],129:[function(require,module,exports){
-arguments[4][103][0].apply(exports,arguments)
-},{"dup":103}],130:[function(require,module,exports){
-arguments[4][60][0].apply(exports,arguments)
-},{"dup":60,"wrappy":129}],131:[function(require,module,exports){
-arguments[4][70][0].apply(exports,arguments)
-},{"./_stream_readable":133,"./_stream_writable":135,"core-util-is":136,"dup":70,"inherits":137,"process-nextick-args":139}],132:[function(require,module,exports){
-arguments[4][71][0].apply(exports,arguments)
-},{"./_stream_transform":134,"core-util-is":136,"dup":71,"inherits":137}],133:[function(require,module,exports){
-arguments[4][72][0].apply(exports,arguments)
-},{"./_stream_duplex":131,"_process":64,"buffer":6,"core-util-is":136,"dup":72,"events":14,"inherits":137,"isarray":138,"process-nextick-args":139,"string_decoder/":140,"util":3}],134:[function(require,module,exports){
-arguments[4][73][0].apply(exports,arguments)
-},{"./_stream_duplex":131,"core-util-is":136,"dup":73,"inherits":137}],135:[function(require,module,exports){
-arguments[4][74][0].apply(exports,arguments)
-},{"./_stream_duplex":131,"buffer":6,"core-util-is":136,"dup":74,"events":14,"inherits":137,"process-nextick-args":139,"util-deprecate":141}],136:[function(require,module,exports){
-arguments[4][11][0].apply(exports,arguments)
-},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21,"dup":11}],137:[function(require,module,exports){
-arguments[4][18][0].apply(exports,arguments)
-},{"dup":18}],138:[function(require,module,exports){
-arguments[4][22][0].apply(exports,arguments)
-},{"dup":22}],139:[function(require,module,exports){
-arguments[4][63][0].apply(exports,arguments)
-},{"_process":64,"dup":63}],140:[function(require,module,exports){
-arguments[4][86][0].apply(exports,arguments)
-},{"buffer":6,"dup":86}],141:[function(require,module,exports){
-arguments[4][88][0].apply(exports,arguments)
-},{"dup":88}],142:[function(require,module,exports){
-arguments[4][76][0].apply(exports,arguments)
-},{"./lib/_stream_duplex.js":131,"./lib/_stream_passthrough.js":132,"./lib/_stream_readable.js":133,"./lib/_stream_transform.js":134,"./lib/_stream_writable.js":135,"dup":76}],143:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-var util = require('util');
-var Transform = require('stream').Transform;
+// set partial to true to test if, for example,
+// "/a/b" matches the start of "/*/b/*/d"
+// Partial means, if you run out of file before you run
+// out of pattern, then that's fine, as long as all
+// the parts match.
+Minimatch.prototype.matchOne = function (file, pattern, partial) {
+ var options = this.options
-function ctor(options, transform) {
- util.inherits(FirstChunk, Transform);
+ this.debug('matchOne',
+ { 'this': this, file: file, pattern: pattern })
- if (typeof options === 'function') {
- transform = options;
- options = {};
- }
+ this.debug('matchOne', file.length, pattern.length)
- if (typeof transform !== 'function') {
- throw new Error('transform function required');
- }
+ for (var fi = 0,
+ pi = 0,
+ fl = file.length,
+ pl = pattern.length
+ ; (fi < fl) && (pi < pl)
+ ; fi++, pi++) {
+ this.debug('matchOne loop')
+ var p = pattern[pi]
+ var f = file[fi]
- function FirstChunk(options2) {
- if (!(this instanceof FirstChunk)) {
- return new FirstChunk(options2);
- }
+ this.debug(pattern, p, f)
- Transform.call(this, options2);
+ // should be impossible.
+ // some invalid regexp stuff in the set.
+ if (p === false) return false
- this._firstChunk = true;
- this._transformCalled = false;
- this._minSize = options.minSize;
- }
+ if (p === GLOBSTAR) {
+ this.debug('GLOBSTAR', [pattern, p, f])
- FirstChunk.prototype._transform = function (chunk, enc, cb) {
- this._enc = enc;
+ // "**"
+ // a/**/b/**/c would match the following:
+ // a/b/x/y/z/c
+ // a/x/y/z/b/c
+ // a/b/x/b/x/c
+ // a/b/c
+ // To do this, take the rest of the pattern after
+ // the **, and see if it would match the file remainder.
+ // If so, return success.
+ // If not, the ** "swallows" a segment, and try again.
+ // This is recursively awful.
+ //
+ // a/**/b/**/c matching a/b/x/y/z/c
+ // - a matches a
+ // - doublestar
+ // - matchOne(b/x/y/z/c, b/**/c)
+ // - b matches b
+ // - doublestar
+ // - matchOne(x/y/z/c, c) -> no
+ // - matchOne(y/z/c, c) -> no
+ // - matchOne(z/c, c) -> no
+ // - matchOne(c, c) yes, hit
+ var fr = fi
+ var pr = pi + 1
+ if (pr === pl) {
+ this.debug('** at the end')
+ // a ** at the end will just swallow the rest.
+ // We have found a match.
+ // however, it will not swallow /.x, unless
+ // options.dot is set.
+ // . and .. are *never* matched by **, for explosively
+ // exponential reasons.
+ for (; fi < fl; fi++) {
+ if (file[fi] === '.' || file[fi] === '..' ||
+ (!options.dot && file[fi].charAt(0) === '.')) return false
+ }
+ return true
+ }
- if (this._firstChunk) {
- this._firstChunk = false;
+ // ok, let's see if we can swallow whatever we can.
+ while (fr < fl) {
+ var swallowee = file[fr]
- if (this._minSize == null) {
- transform.call(this, chunk, enc, cb);
- this._transformCalled = true;
- return;
- }
+ this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
- this._buffer = chunk;
- cb();
- return;
- }
+ // XXX remove this slice. Just pass the start index.
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+ this.debug('globstar found match!', fr, fl, swallowee)
+ // found a match.
+ return true
+ } else {
+ // can't swallow "." or ".." ever.
+ // can only swallow ".foo" when explicitly asked.
+ if (swallowee === '.' || swallowee === '..' ||
+ (!options.dot && swallowee.charAt(0) === '.')) {
+ this.debug('dot detected!', file, fr, pattern, pr)
+ break
+ }
- if (this._minSize == null) {
- this.push(chunk);
- cb();
- return;
- }
+ // ** swallows a segment, and continue.
+ this.debug('globstar swallow a segment, and continue')
+ fr++
+ }
+ }
- if (this._buffer.length < this._minSize) {
- this._buffer = Buffer.concat([this._buffer, chunk]);
- cb();
- return;
- }
+ // no match was found.
+ // However, in partial mode, we can't say this is necessarily over.
+ // If there's more *pattern* left, then
+ if (partial) {
+ // ran out of file
+ this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
+ if (fr === fl) return true
+ }
+ return false
+ }
- if (this._buffer.length >= this._minSize) {
- transform.call(this, this._buffer.slice(), enc, function () {
- this.push(chunk);
- cb();
- }.bind(this));
- this._transformCalled = true;
- this._buffer = false;
- return;
- }
+ // something other than **
+ // non-magic patterns just have to match exactly
+ // patterns with magic have been turned into regexps.
+ var hit
+ if (typeof p === 'string') {
+ if (options.nocase) {
+ hit = f.toLowerCase() === p.toLowerCase()
+ } else {
+ hit = f === p
+ }
+ this.debug('string match', p, f, hit)
+ } else {
+ hit = f.match(p)
+ this.debug('pattern match', p, f, hit)
+ }
- this.push(chunk);
- cb();
- };
+ if (!hit) return false
+ }
- FirstChunk.prototype._flush = function (cb) {
- if (!this._buffer) {
- cb();
- return;
- }
+ // Note: ending in / means that we'll get a final ""
+ // at the end of the pattern. This can only match a
+ // corresponding "" at the end of the file.
+ // If the file ends in /, then it can only match a
+ // a pattern that ends in /, unless the pattern just
+ // doesn't have any more for it. But, a/b/ should *not*
+ // match "a/b/*", even though "" matches against the
+ // [^/]*? pattern, except in partial mode, where it might
+ // simply not be reached yet.
+ // However, a/b/ should still satisfy a/*
- if (this._transformCalled) {
- this.push(this._buffer);
- cb();
- } else {
- transform.call(this, this._buffer.slice(), this._enc, cb);
- }
- };
+ // now either we fell off the end of the pattern, or we're done.
+ if (fi === fl && pi === pl) {
+ // ran out of pattern and filename at the same time.
+ // an exact hit!
+ return true
+ } else if (fi === fl) {
+ // ran out of file, but still had pattern left.
+ // this is ok if we're doing the match as part of
+ // a glob fs traversal.
+ return partial
+ } else if (pi === pl) {
+ // ran out of pattern, still have file left.
+ // this is only acceptable if we're on the very last
+ // empty segment of a file with a trailing slash.
+ // a/* should match a/b/
+ var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')
+ return emptyFileEnd
+ }
- return FirstChunk;
+ // should be unreachable.
+ throw new Error('wtf?')
}
-module.exports = function () {
- return ctor.apply(ctor, arguments)();
-};
+// replace stuff like \* with *
+function globUnescape (s) {
+ return s.replace(/\\(.)/g, '$1')
+}
-module.exports.ctor = ctor;
+function regExpEscape (s) {
+ return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
+}
-}).call(this,require("buffer").Buffer)
-},{"buffer":6,"stream":81,"util":90}],144:[function(require,module,exports){
+},{"brace-expansion":4,"path":104}],85:[function(require,module,exports){
(function (process){
-/*jslint node: true */
-
-'use strict';
+var path = require('path');
+var fs = require('fs');
+var _0777 = parseInt('0777', 8);
-var through2 = require('through2');
-var Combine = require('ordered-read-streams');
-var unique = require('unique-stream');
+module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
-var glob = require('glob');
-var Minimatch = require('minimatch').Minimatch;
-var glob2base = require('glob2base');
-var path = require('path');
+function mkdirP (p, opts, f, made) {
+ if (typeof opts === 'function') {
+ f = opts;
+ opts = {};
+ }
+ else if (!opts || typeof opts !== 'object') {
+ opts = { mode: opts };
+ }
+
+ var mode = opts.mode;
+ var xfs = opts.fs || fs;
+
+ if (mode === undefined) {
+ mode = _0777 & (~process.umask());
+ }
+ if (!made) made = null;
+
+ var cb = f || function () {};
+ p = path.resolve(p);
+
+ xfs.mkdir(p, mode, function (er) {
+ if (!er) {
+ made = made || p;
+ return cb(null, made);
+ }
+ switch (er.code) {
+ case 'ENOENT':
+ mkdirP(path.dirname(p), opts, function (er, made) {
+ if (er) cb(er, made);
+ else mkdirP(p, opts, cb, made);
+ });
+ break;
-var gs = {
- // creates a stream for a single glob or filter
- createStream: function(ourGlob, negatives, opt) {
- // remove path relativity to make globs make sense
- ourGlob = unrelative(opt.cwd, ourGlob);
+ // In the case of any other error, just see if there's a dir
+ // there already. If so, then hooray! If not, then something
+ // is borked.
+ default:
+ xfs.stat(p, function (er2, stat) {
+ // if the stat fails, then that's super weird.
+ // let the original error be the failure reason.
+ if (er2 || !stat.isDirectory()) cb(er, made)
+ else cb(null, made);
+ });
+ break;
+ }
+ });
+}
- // create globbing stuff
- var globber = new glob.Glob(ourGlob, opt);
+mkdirP.sync = function sync (p, opts, made) {
+ if (!opts || typeof opts !== 'object') {
+ opts = { mode: opts };
+ }
+
+ var mode = opts.mode;
+ var xfs = opts.fs || fs;
+
+ if (mode === undefined) {
+ mode = _0777 & (~process.umask());
+ }
+ if (!made) made = null;
- // extract base path from glob
- var basePath = opt.base || glob2base(globber);
+ p = path.resolve(p);
- // create stream and map events from globber to it
- var stream = through2.obj(negatives.length ? filterNegatives : undefined);
+ try {
+ xfs.mkdirSync(p, mode);
+ made = made || p;
+ }
+ catch (err0) {
+ switch (err0.code) {
+ case 'ENOENT' :
+ made = sync(path.dirname(p), opts, made);
+ sync(p, opts, made);
+ break;
- var found = false;
+ // In the case of any other error, just see if there's a dir
+ // there already. If so, then hooray! If not, then something
+ // is borked.
+ default:
+ var stat;
+ try {
+ stat = xfs.statSync(p);
+ }
+ catch (err1) {
+ throw err0;
+ }
+ if (!stat.isDirectory()) throw err0;
+ break;
+ }
+ }
- globber.on('error', stream.emit.bind(stream, 'error'));
- globber.on('end', function(){
- if (opt.allowEmpty !== true && !found && globIsSingular(globber)) {
- stream.emit('error', new Error('File not found with singular glob'));
- }
+ return made;
+};
- stream.end();
- });
- globber.on('match', function(filename) {
- found = true;
+}).call(this,require('_process'))
+},{"_process":107,"fs":6,"path":104}],86:[function(require,module,exports){
+(function (Buffer){
+var map = require('lodash.map')
+var filter = require('lodash.filter')
+var log = console.log
+var convert = require('./convert')
+var protocols = require('./protocols')
- stream.write({
- cwd: opt.cwd,
- base: basePath,
- path: path.resolve(opt.cwd, filename)
- });
- });
+// export codec
+var codec = module.exports = {
+ stringToStringTuples: stringToStringTuples,
+ stringTuplesToString: stringTuplesToString,
- return stream;
+ tuplesToStringTuples: tuplesToStringTuples,
+ stringTuplesToTuples: stringTuplesToTuples,
- function filterNegatives(filename, enc, cb) {
- var matcha = isMatch.bind(null, filename);
- if (negatives.every(matcha)) {
- cb(null, filename); // pass
- } else {
- cb(); // ignore
- }
- }
- },
+ bufferToTuples: bufferToTuples,
+ tuplesToBuffer: tuplesToBuffer,
- // creates a stream for multiple globs or filters
- create: function(globs, opt) {
- if (!opt) opt = {};
- if (typeof opt.cwd !== 'string') opt.cwd = process.cwd();
- if (typeof opt.dot !== 'boolean') opt.dot = false;
- if (typeof opt.silent !== 'boolean') opt.silent = true;
- if (typeof opt.nonull !== 'boolean') opt.nonull = false;
- if (typeof opt.cwdbase !== 'boolean') opt.cwdbase = false;
- if (opt.cwdbase) opt.base = opt.cwd;
+ bufferToString: bufferToString,
+ stringToBuffer: stringToBuffer,
- // only one glob no need to aggregate
- if (!Array.isArray(globs)) globs = [globs];
+ fromString: fromString,
+ fromBuffer: fromBuffer,
+ validateBuffer: validateBuffer,
+ isValidBuffer: isValidBuffer,
+ cleanPath: cleanPath,
- var positives = [];
- var negatives = [];
+ ParseError: ParseError,
+ protoFromTuple: protoFromTuple,
+}
- globs.forEach(function(glob, index) {
- if (typeof glob !== 'string' && !(glob instanceof RegExp)) {
- throw new Error('Invalid glob at index ' + index);
- }
+// string -> [[str name, str addr]... ]
+function stringToStringTuples(str) {
+ var tuples = []
+ var parts = str.split('/').slice(1) // skip first empty elem
+ if (parts.length == 1 && parts[0] == '')
+ return []
- var globArray = isNegative(glob) ? negatives : positives;
+ for (var p = 0; p < parts.length; p++) {
+ var part = parts[p]
+ var proto = protocols(part)
+ if (proto.size == 0)
+ return [part]
- // create Minimatch instances for negative glob patterns
- if (globArray === negatives && typeof glob === 'string') {
- glob = new Minimatch(unrelative(opt.cwd, glob), opt);
- }
+ p++ // advance addr part
+ if (p >= parts.length)
+ throw ParseError("invalid address: " + str)
- globArray.push({
- index: index,
- glob: glob
- });
- });
+ tuples.push([part, parts[p]])
+ }
+ return tuples
+}
- if (positives.length === 0) throw new Error('Missing positive glob');
+// [[str name, str addr]... ] -> string
+function stringTuplesToString(tuples) {
+ var parts = []
+ map(tuples, function(tup) {
+ var proto = protoFromTuple(tup)
+ parts.push(proto.name)
+ if (tup.length > 1)
+ parts.push(tup[1])
+ })
+ return "/" + parts.join("/")
+}
- // only one positive glob no need to aggregate
- if (positives.length === 1) return streamFromPositive(positives[0]);
- // create all individual streams
- var streams = positives.map(streamFromPositive);
+// [[str name, str addr]... ] -> [[int code, Buffer]... ]
+function stringTuplesToTuples(tuples) {
+ return map(tuples, function(tup) {
+ var proto = protoFromTuple(tup)
+ if (tup.length > 1)
+ return [proto.code, convert.toBuffer(proto.code, tup[1])]
+ return [proto.code]
+ })
+}
- // then just pipe them to a single unique stream and return it
- var aggregate = new Combine(streams);
- var uniqueStream = unique('path');
- var returnStream = aggregate.pipe(uniqueStream);
+// [[int code, Buffer]... ] -> [[str name, str addr]... ]
+function tuplesToStringTuples(tuples) {
+ return map(tuples, function(tup) {
+ var proto = protoFromTuple(tup)
+ if (tup.length > 1)
+ return [proto.code, convert.toString(proto.code, tup[1])]
+ return [proto.code]
+ })
+}
- aggregate.on('error', function (err) {
- returnStream.emit('error', err);
- });
+// [[int code, Buffer ]... ] -> Buffer
+function tuplesToBuffer(tuples) {
+ return fromBuffer(Buffer.concat(map(tuples, function(tup) {
+ var proto = protoFromTuple(tup)
+ var buf = new Buffer([proto.code])
+ if (tup.length > 1)
+ buf = Buffer.concat([buf, tup[1]]) // add address buffer
+ return buf
+ })))
+}
- return returnStream;
+// Buffer -> [[int code, Buffer ]... ]
+function bufferToTuples(buf) {
+ var tuples = []
+ for (var i = 0; i < buf.length; ) {
+ var code = buf[i]
+ var proto = protocols(code)
+ if (!proto)
+ throw ParseError("Invalid protocol code: " + code)
- function streamFromPositive(positive) {
- var negativeGlobs = negatives.filter(indexGreaterThan(positive.index)).map(toGlob);
- return gs.createStream(positive.glob, negativeGlobs, opt);
- }
- }
-};
+ var size = (proto.size / 8)
+ var code = 0 + buf[i]
+ var addr = buf.slice(i + 1, i + 1 + size)
+ i += 1 + size
+ if (i > buf.length) // did not end _exactly_ at buffer.length
+ throw ParseError("Invalid address buffer: " + buf.toString('hex'))
-function isMatch(file, matcher) {
- if (matcher instanceof Minimatch) return matcher.match(file.path);
- if (matcher instanceof RegExp) return matcher.test(file.path);
+ // ok, tuple seems good.
+ tuples.push([code, addr])
+ }
+ return tuples
}
-function isNegative(pattern) {
- if (typeof pattern === 'string') return pattern[0] === '!';
- if (pattern instanceof RegExp) return true;
+// Buffer -> String
+function bufferToString(buf) {
+ var a = bufferToTuples(buf)
+ var b = tuplesToStringTuples(a)
+ return stringTuplesToString(b)
}
-function unrelative(cwd, glob) {
- var mod = '';
- if (glob[0] === '!') {
- mod = glob[0];
- glob = glob.slice(1);
- }
- return mod+path.resolve(cwd, glob);
+// String -> Buffer
+function stringToBuffer(str) {
+ str = cleanPath(str)
+ var a = stringToStringTuples(str)
+ var b = stringTuplesToTuples(a)
+ return tuplesToBuffer(b)
}
-function indexGreaterThan(index) {
- return function(obj) {
- return obj.index > index;
- };
+// String -> Buffer
+function fromString(str) {
+ return stringToBuffer(str)
}
-function toGlob(obj) {
- return obj.glob;
+// Buffer -> Buffer
+function fromBuffer(buf) {
+ var err = validateBuffer(buf)
+ if (err) throw err
+ return new Buffer(buf) // copy
}
-function globIsSingular(glob) {
- var globSet = glob.minimatch.set;
+function validateBuffer(buf) {
+ bufferToTuples(buf) // try to parse. will throw if breaks
+}
- if (globSet.length !== 1) {
- return false;
+function isValidBuffer(buf) {
+ try {
+ validateBuffer(buf) // try to parse. will throw if breaks
+ return true
+ } catch(e) {
+ return false
}
-
- return globSet[0].every(function isString(value) {
- return typeof value === 'string';
- });
}
-module.exports = gs;
-
-}).call(this,require('_process'))
-},{"_process":64,"glob":146,"glob2base":154,"minimatch":156,"ordered-read-streams":160,"path":62,"through2":182,"unique-stream":183}],145:[function(require,module,exports){
-(function (process){
-exports.alphasort = alphasort
-exports.alphasorti = alphasorti
-exports.setopts = setopts
-exports.ownProp = ownProp
-exports.makeAbs = makeAbs
-exports.finish = finish
-exports.mark = mark
-exports.isIgnored = isIgnored
-exports.childrenIgnored = childrenIgnored
-
-function ownProp (obj, field) {
- return Object.prototype.hasOwnProperty.call(obj, field)
+function cleanPath(str) {
+ return '/' + filter(str.trim().split('/')).join('/')
}
-var path = require("path")
-var minimatch = require("minimatch")
-var isAbsolute = require("path-is-absolute")
-var Minimatch = minimatch.Minimatch
-
-function alphasorti (a, b) {
- return a.toLowerCase().localeCompare(b.toLowerCase())
+function ParseError(str) {
+ return new Error("Error parsing address: " + str)
}
-function alphasort (a, b) {
- return a.localeCompare(b)
+function protoFromTuple(tup) {
+ var proto = protocols(tup[0])
+ if (tup.length > 1 && proto.size == 0)
+ throw ParseError("tuple has address but protocol size is 0")
+ return proto
}
-function setupIgnores (self, options) {
- self.ignore = options.ignore || []
+}).call(this,require("buffer").Buffer)
+},{"./convert":87,"./protocols":90,"buffer":8,"lodash.filter":72,"lodash.map":79}],87:[function(require,module,exports){
+(function (Buffer){
+var ip = require('ip')
+var protocols = require('./protocols')
- if (!Array.isArray(self.ignore))
- self.ignore = [self.ignore]
+module.exports = Convert
- if (self.ignore.length) {
- self.ignore = self.ignore.map(ignoreMap)
- }
+// converts (serializes) addresses
+function Convert(proto, a) {
+ if (a instanceof Buffer)
+ return Convert.toString(proto, a)
+ else
+ return Convert.toBuffer(proto, a)
}
-function ignoreMap (pattern) {
- var gmatcher = null
- if (pattern.slice(-3) === '/**') {
- var gpattern = pattern.replace(/(\/\*\*)+$/, '')
- gmatcher = new Minimatch(gpattern)
- }
+Convert.toString = function convertToString(proto, buf) {
+ proto = protocols(proto)
+ switch (proto.code) {
+ case 4: // ipv4
+ case 41: // ipv6
+ return ip.toString(buf)
- return {
- matcher: new Minimatch(pattern),
- gmatcher: gmatcher
+ case 6: // tcp
+ case 17: // udp
+ case 33: // dccp
+ case 132: // sctp
+ return buf2port(buf)
}
+ return buf.toString('hex') // no clue. convert to hex
}
-function setopts (self, pattern, options) {
- if (!options)
- options = {}
-
- // base-matching: just use globstar for that.
- if (options.matchBase && -1 === pattern.indexOf("/")) {
- if (options.noglobstar) {
- throw new Error("base matching requires globstar")
- }
- pattern = "**/" + pattern
- }
-
- self.silent = !!options.silent
- self.pattern = pattern
- self.strict = options.strict !== false
- self.realpath = !!options.realpath
- self.realpathCache = options.realpathCache || Object.create(null)
- self.follow = !!options.follow
- self.dot = !!options.dot
- self.mark = !!options.mark
- self.nodir = !!options.nodir
- if (self.nodir)
- self.mark = true
- self.sync = !!options.sync
- self.nounique = !!options.nounique
- self.nonull = !!options.nonull
- self.nosort = !!options.nosort
- self.nocase = !!options.nocase
- self.stat = !!options.stat
- self.noprocess = !!options.noprocess
-
- self.maxLength = options.maxLength || Infinity
- self.cache = options.cache || Object.create(null)
- self.statCache = options.statCache || Object.create(null)
- self.symlinks = options.symlinks || Object.create(null)
-
- setupIgnores(self, options)
+Convert.toBuffer = function convertToBuffer(proto, str) {
+ proto = protocols(proto)
+ switch (proto.code) {
+ case 4: // ipv4
+ case 41: // ipv6
+ return ip.toBuffer(str)
- self.changedCwd = false
- var cwd = process.cwd()
- if (!ownProp(options, "cwd"))
- self.cwd = cwd
- else {
- self.cwd = options.cwd
- self.changedCwd = path.resolve(options.cwd) !== cwd
+ case 6: // tcp
+ case 17: // udp
+ case 33: // dccp
+ case 132: // sctp
+ return port2buf(parseInt(str, 10))
}
-
- self.root = options.root || path.resolve(self.cwd, "/")
- self.root = path.resolve(self.root)
- if (process.platform === "win32")
- self.root = self.root.replace(/\\/g, "/")
-
- self.nomount = !!options.nomount
-
- // disable comments and negation unless the user explicitly
- // passes in false as the option.
- options.nonegate = options.nonegate === false ? false : true
- options.nocomment = options.nocomment === false ? false : true
- deprecationWarning(options)
-
- self.minimatch = new Minimatch(pattern, options)
- self.options = self.minimatch.options
+ return new Buffer(str, 'hex') // no clue. convert from hex
}
-// TODO(isaacs): remove entirely in v6
-// exported to reset in tests
-exports.deprecationWarned
-function deprecationWarning(options) {
- if (!options.nonegate || !options.nocomment) {
- if (process.noDeprecation !== true && !exports.deprecationWarned) {
- var msg = 'glob WARNING: comments and negation will be disabled in v6'
- if (process.throwDeprecation)
- throw new Error(msg)
- else if (process.traceDeprecation)
- console.trace(msg)
- else
- console.error(msg)
-
- exports.deprecationWarned = true
- }
- }
+function port2buf(port) {
+ var buf = new Buffer(2)
+ buf.writeUInt16BE(port, 0);
+ return buf
}
-function finish (self) {
- var nou = self.nounique
- var all = nou ? [] : Object.create(null)
+function buf2port(buf) {
+ return buf.readUInt16BE(0)
+}
- for (var i = 0, l = self.matches.length; i < l; i ++) {
- var matches = self.matches[i]
- if (!matches || Object.keys(matches).length === 0) {
- if (self.nonull) {
- // do like the shell, and spit out the literal glob
- var literal = self.minimatch.globSet[i]
- if (nou)
- all.push(literal)
- else
- all[literal] = true
- }
- } else {
- // had matches
- var m = Object.keys(matches)
- if (nou)
- all.push.apply(all, m)
- else
- m.forEach(function (m) {
- all[m] = true
- })
- }
- }
+}).call(this,require("buffer").Buffer)
+},{"./protocols":90,"buffer":8,"ip":48}],88:[function(require,module,exports){
+(function (Buffer){
+var map = require('lodash.map')
+var extend = require('xtend')
+var codec = require('./codec')
+var bufeq = require('buffer-equal')
+var protocols = require('./protocols')
+var NotImplemented = new Error("Sorry, Not Implemented Yet.")
- if (!nou)
- all = Object.keys(all)
+module.exports = Multiaddr
- if (!self.nosort)
- all = all.sort(self.nocase ? alphasorti : alphasort)
+function Multiaddr(addr) {
+ if (!(this instanceof Multiaddr))
+ return new Multiaddr(addr)
- // at *some* point we statted all of these
- if (self.mark) {
- for (var i = 0; i < all.length; i++) {
- all[i] = self._mark(all[i])
- }
- if (self.nodir) {
- all = all.filter(function (e) {
- return !(/\/$/.test(e))
- })
- }
- }
+ // defaults
+ if (!addr)
+ addr = ''
- if (self.ignore.length)
- all = all.filter(function(m) {
- return !isIgnored(self, m)
- })
+ if (addr instanceof Buffer)
+ this.buffer = codec.fromBuffer(addr)
+ else if (typeof(addr) == 'string' || addr instanceof String)
+ this.buffer = codec.fromString(addr)
+ else if (addr.buffer && addr.protos && addr.protoCodes) // Multiaddr
+ this.buffer = codec.fromBuffer(addr.buffer) // validate + copy buffer
+ else
+ throw new Error('addr must be a string, Buffer, or Multiaddr')
+}
- self.found = all
+// get the multiaddr protocols
+Multiaddr.prototype.toString = function toString() {
+ return codec.bufferToString(this.buffer)
}
-function mark (self, p) {
- var abs = makeAbs(self, p)
- var c = self.cache[abs]
- var m = p
- if (c) {
- var isDir = c === 'DIR' || Array.isArray(c)
- var slash = p.slice(-1) === '/'
+// get the multiaddr as a convinent options object to be dropped in net.createConnection
+Multiaddr.prototype.toOptions = function toOptions() {
+ var opts = {}
+ var parsed = this.toString().split('/')
+ opts.family = parsed[1] === 'ip4' ? 'ipv4' : 'ipv6'
+ opts.host = parsed[2]
+ opts.port = parsed[4]
+ return opts
+}
- if (isDir && !slash)
- m += '/'
- else if (!isDir && slash)
- m = m.slice(0, -1)
+// get the multiaddr protocols
+Multiaddr.prototype.inspect = function inspect() {
+ return ""
+}
- if (m !== p) {
- var mabs = makeAbs(self, m)
- self.statCache[mabs] = self.statCache[abs]
- self.cache[mabs] = self.cache[abs]
- }
- }
+// get the multiaddr protocols
+Multiaddr.prototype.protos = function protos() {
+ return map(this.protoCodes(), function(code) {
+ return extend(protocols(code))
+ // copy to prevent users from modifying the internal objs.
+ });
+}
- return m
+// get the multiaddr protocols
+Multiaddr.prototype.protos = function protos() {
+ return map(this.protoCodes(), function(code) {
+ return extend(protocols(code))
+ // copy to prevent users from modifying the internal objs.
+ });
}
-// lotta situps...
-function makeAbs (self, f) {
- var abs = f
- if (f.charAt(0) === '/') {
- abs = path.join(self.root, f)
- } else if (isAbsolute(f) || f === '') {
- abs = f
- } else if (self.changedCwd) {
- abs = path.resolve(self.cwd, f)
- } else {
- abs = path.resolve(f)
+// get the multiaddr protocol codes
+Multiaddr.prototype.protoCodes = function protoCodes() {
+ var codes = []
+ for (var i = 0; i < this.buffer.length; i++) {
+ var code = 0 + this.buffer[i]
+ var size = protocols(code).size / 8
+ i += size // skip over proto data
+ codes.push(code)
}
- return abs
+ return codes
}
-
-// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
-// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
-function isIgnored (self, path) {
- if (!self.ignore.length)
- return false
-
- return self.ignore.some(function(item) {
- return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
+// get the multiaddr protocol string names
+Multiaddr.prototype.protoNames = function protoNames() {
+ return map(this.protos(), function(proto) {
+ return proto.name
})
}
-function childrenIgnored (self, path) {
- if (!self.ignore.length)
- return false
+// Returns a tuple of parts:
+Multiaddr.prototype.tuples = function tuples() {
+ return codec.bufferToTuples(this.buffer)
+}
- return self.ignore.some(function(item) {
- return !!(item.gmatcher && item.gmatcher.match(path))
- })
+// Returns a tuple of string parts:
+Multiaddr.prototype.stringTuples = function stringTuples() {
+ var t = codec.bufferToTuples(this.buffer)
+ return codec.tuplesToStringTuples(t)
}
-}).call(this,require('_process'))
-},{"_process":64,"minimatch":156,"path":62,"path-is-absolute":152}],146:[function(require,module,exports){
-(function (process){
-// Approach:
-//
-// 1. Get the minimatch set
-// 2. For each pattern in the set, PROCESS(pattern, false)
-// 3. Store matches per-set, then uniq them
-//
-// PROCESS(pattern, inGlobStar)
-// Get the first [n] items from pattern that are all strings
-// Join these together. This is PREFIX.
-// If there is no more remaining, then stat(PREFIX) and
-// add to matches if it succeeds. END.
-//
-// If inGlobStar and PREFIX is symlink and points to dir
-// set ENTRIES = []
-// else readdir(PREFIX) as ENTRIES
-// If fail, END
-//
-// with ENTRIES
-// If pattern[n] is GLOBSTAR
-// // handle the case where the globstar match is empty
-// // by pruning it out, and testing the resulting pattern
-// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
-// // handle other cases.
-// for ENTRY in ENTRIES (not dotfiles)
-// // attach globstar + tail onto the entry
-// // Mark that this entry is a globstar match
-// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
-//
-// else // not globstar
-// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
-// Test ENTRY against pattern[n]
-// If fails, continue
-// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
-//
-// Caveat:
-// Cache all stats and readdirs results to minimize syscall. Since all
-// we ever care about is existence and directory-ness, we can just keep
-// `true` for files, and [children,...] for directories, or `false` for
-// things that don't exist.
-module.exports = glob
+Multiaddr.prototype.encapsulate = function encapsulate(addr) {
+ addr = Multiaddr(addr)
+ return Multiaddr(this.toString() + addr.toString())
+}
-var fs = require('fs')
-var minimatch = require('minimatch')
-var Minimatch = minimatch.Minimatch
-var inherits = require('inherits')
-var EE = require('events').EventEmitter
-var path = require('path')
-var assert = require('assert')
-var isAbsolute = require('path-is-absolute')
-var globSync = require('./sync.js')
-var common = require('./common.js')
-var alphasort = common.alphasort
-var alphasorti = common.alphasorti
-var setopts = common.setopts
-var ownProp = common.ownProp
-var inflight = require('inflight')
-var util = require('util')
-var childrenIgnored = common.childrenIgnored
-var isIgnored = common.isIgnored
+Multiaddr.prototype.decapsulate = function decapsulate(addr) {
+ addr = addr.toString()
+ var s = this.toString()
+ var i = s.lastIndexOf(addr)
+ if (i < 0)
+ throw new Error("Address " +this+" does not contain subaddress: " +addr)
+ return Multiaddr(s.slice(0, i))
+}
-var once = require('once')
+Multiaddr.prototype.equals = function equals(addr) {
+ return bufeq(this.buffer, addr.buffer)
+}
-function glob (pattern, options, cb) {
- if (typeof options === 'function') cb = options, options = {}
- if (!options) options = {}
+// get a node friendly address object
+Multiaddr.prototype.nodeAddress = function nodeAddress() {
+ if (!this.isThinWaistAddress())
+ throw new Error('Multiaddr must be "thin waist" address for nodeAddress.')
- if (options.sync) {
- if (cb)
- throw new TypeError('callback provided to sync glob')
- return globSync(pattern, options)
+ var codes = this.protoCodes()
+ var parts = this.toString().split('/').slice(1)
+ return {
+ family: (codes[0] == 41) ? "IPv6" : "IPv4",
+ address: parts[1], // ip addr
+ port: parts[3], // tcp or udp port
}
-
- return new Glob(pattern, options, cb)
}
-glob.sync = globSync
-var GlobSync = glob.GlobSync = globSync.GlobSync
-
-// old api surface
-glob.glob = glob
-
-glob.hasMagic = function (pattern, options_) {
- var options = util._extend({}, options_)
- options.noprocess = true
-
- var g = new Glob(pattern, options)
- var set = g.minimatch.set
- if (set.length > 1)
- return true
+// from a node friendly address object
+Multiaddr.fromNodeAddress = function fromNodeAddress(addr, transport) {
+ if (!addr) throw new Error('requires node address object')
+ if (!transport) throw new Error('requires transport protocol')
+ var ip = (addr.family == "IPv6") ? 'ip6' : 'ip4'
+ return Multiaddr('/' + [ip, addr.address, transport, addr.port].join('/'))
+}
- for (var j = 0; j < set[0].length; j++) {
- if (typeof set[0][j] !== 'string')
- return true
- }
- return false
+// returns whether this address is a standard combination:
+// /{IPv4, IPv6}/{TCP, UDP}
+Multiaddr.prototype.isThinWaistAddress = function isThinWaistAddress(addr) {
+ var protos = (addr || this).protos()
+ if (protos.length != 2) return false
+ if (protos[0].code != 4 && protos[0].code != 41) return false
+ if (protos[1].code != 6 && protos[1].code != 17) return false
+ return true
}
-glob.Glob = Glob
-inherits(Glob, EE)
-function Glob (pattern, options, cb) {
- if (typeof options === 'function') {
- cb = options
- options = null
- }
- if (options && options.sync) {
- if (cb)
- throw new TypeError('callback provided to sync glob')
- return new GlobSync(pattern, options)
- }
+// parses the "stupid string" format:
+// ://[:]
+// udp4://1.2.3.4:5678
+Multiaddr.prototype.fromStupidString = function fromStupidString(str) {
+ throw NotImplemented
+}
- if (!(this instanceof Glob))
- return new Glob(pattern, options, cb)
+// patch this in
+Multiaddr.protocols = protocols
- setopts(this, pattern, options)
- this._didRealPath = false
+}).call(this,require("buffer").Buffer)
+},{"./codec":86,"./protocols":90,"buffer":8,"buffer-equal":7,"lodash.map":79,"xtend":89}],89:[function(require,module,exports){
+module.exports = extend
- // process each pattern in the minimatch set
- var n = this.minimatch.set.length
+function extend() {
+ var target = {}
- // The matches are stored as {: true,...} so that
- // duplicates are automagically pruned.
- // Later, we do an Object.keys() on these.
- // Keep them as a list so we can fill in when nonull is set.
- this.matches = new Array(n)
+ for (var i = 0; i < arguments.length; i++) {
+ var source = arguments[i]
- if (typeof cb === 'function') {
- cb = once(cb)
- this.on('error', cb)
- this.on('end', function (matches) {
- cb(null, matches)
- })
- }
+ for (var key in source) {
+ if (source.hasOwnProperty(key)) {
+ target[key] = source[key]
+ }
+ }
+ }
- var self = this
- var n = this.minimatch.set.length
- this._processing = 0
- this.matches = new Array(n)
+ return target
+}
- this._emitQueue = []
- this._processQueue = []
- this.paused = false
+},{}],90:[function(require,module,exports){
+var map = require('lodash.map')
- if (this.noprocess)
- return this
+module.exports = Protocols
- if (n === 0)
- return done()
+function Protocols(proto) {
+ if (typeof(proto) == 'number') {
+ if (Protocols.codes[proto])
+ return Protocols.codes[proto]
- for (var i = 0; i < n; i ++) {
- this._process(this.minimatch.set[i], i, false, done)
+ throw new Error("no protocol with code: " + proto)
}
+ else if (typeof(proto) == 'string' || proto instanceof String) {
+ if (Protocols.names[proto])
+ return Protocols.names[proto]
- function done () {
- --self._processing
- if (self._processing <= 0)
- self._finish()
+ throw new Error("no protocol with name: " + proto)
}
-}
-
-Glob.prototype._finish = function () {
- assert(this instanceof Glob)
- if (this.aborted)
- return
-
- if (this.realpath && !this._didRealpath)
- return this._realpath()
- common.finish(this)
- this.emit('end', this.found)
+ throw new Error("invalid protocol id type: " + proto)
}
-Glob.prototype._realpath = function () {
- if (this._didRealpath)
- return
+// replicating table here to:
+// 1. avoid parsing the csv
+// 2. ensuring errors in the csv don't screw up code.
+// 3. changing a number has to happen in two places.
- this._didRealpath = true
+Protocols.table = [
+ [4, 32, 'ip4'],
+ [6, 16, 'tcp'],
+ [17, 16, 'udp'],
+ [33, 16, 'dccp'],
+ [41, 128, 'ip6'],
+ // these require varint:
+ [132, 16, 'sctp'],
+ // [480, 0, 'http'],
+ // [443, 0, 'https'],
+]
- var n = this.matches.length
- if (n === 0)
- return this._finish()
+Protocols.names = {}
+Protocols.codes = {}
- var self = this
- for (var i = 0; i < this.matches.length; i++)
- this._realpathSet(i, next)
+// populate tables
+map(Protocols.table, function(e) {
+ var proto = p.apply(this, e)
+ Protocols.codes[proto.code] = proto
+ Protocols.names[proto.name] = proto
+})
- function next () {
- if (--n === 0)
- self._finish()
- }
+Protocols.object = p
+
+function p(code, size, name) {
+ return {code: code, size: size, name: name}
}
-Glob.prototype._realpathSet = function (index, cb) {
- var matchset = this.matches[index]
- if (!matchset)
- return cb()
+},{"lodash.map":79}],91:[function(require,module,exports){
+var Sandwich = require('sandwich-stream').SandwichStream
+var stream = require('stream')
+var inherits = require('inherits')
- var found = Object.keys(matchset)
- var self = this
- var n = found.length
+var CRNL = '\r\n'
- if (n === 0)
- return cb()
+module.exports = Multipart
- var set = this.matches[index] = Object.create(null)
- found.forEach(function (p, i) {
- // If there's a problem with the stat, then it means that
- // one or more of the links in the realpath couldn't be
- // resolved. just return the abs value in that case.
- p = self._makeAbs(p)
- fs.realpath(p, self.realpathCache, function (er, real) {
- if (!er)
- set[real] = true
- else if (er.syscall === 'stat')
- set[p] = true
- else
- self.emit('error', er) // srsly wtf right here
+/**
+ * Multipart request constructor.
+ * @constructor
+ * @param {object} [opts]
+ * @param {string} [opts.boundary] - The boundary to be used. If omitted one is generated.
+ * @returns {function} Returns the multipart stream.
+ */
+function Multipart(boundary) {
+ if(!this instanceof Multipart) {
+ return new Multipart(boundary)
+ }
- if (--n === 0) {
- self.matches[index] = set
- cb()
- }
- })
- })
-}
+ this.boundary = boundary || Math.random().toString(36).slice(2)
-Glob.prototype._mark = function (p) {
- return common.mark(this, p)
-}
+ Sandwich.call(this, {
+ head: '--' + this.boundary + CRNL,
+ tail: CRNL + '--' + this.boundary + '--',
+ separator: CRNL + '--' + this.boundary + CRNL
+ })
-Glob.prototype._makeAbs = function (f) {
- return common.makeAbs(this, f)
+ this._add = this.add
+ this.add = this.addPart
}
-Glob.prototype.abort = function () {
- this.aborted = true
- this.emit('abort')
-}
+inherits(Multipart, Sandwich)
-Glob.prototype.pause = function () {
- if (!this.paused) {
- this.paused = true
- this.emit('pause')
- }
-}
+/**
+ * Adds a new part to the request.
+ * @param {object} [part={}]
+ * @param {object} [part.headers={}]
+ * @param {string|buffer|stream} [part.body=\r\n]
+ * @returns {function} Returns the multipart stream.
+ */
+Multipart.prototype.addPart = function(part) {
+ part = part || {}
+ var partStream = new stream.PassThrough()
-Glob.prototype.resume = function () {
- if (this.paused) {
- this.emit('resume')
- this.paused = false
- if (this._emitQueue.length) {
- var eq = this._emitQueue.slice(0)
- this._emitQueue.length = 0
- for (var i = 0; i < eq.length; i ++) {
- var e = eq[i]
- this._emitMatch(e[0], e[1])
- }
- }
- if (this._processQueue.length) {
- var pq = this._processQueue.slice(0)
- this._processQueue.length = 0
- for (var i = 0; i < pq.length; i ++) {
- var p = pq[i]
- this._processing--
- this._process(p[0], p[1], p[2], p[3])
- }
- }
- }
-}
+ if(part.headers) {
+ for(var key in part.headers) {
+ var header = part.headers[key]
+ partStream.write(key + ': ' + header + CRNL)
+ }
+ }
-Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
- assert(this instanceof Glob)
- assert(typeof cb === 'function')
+ partStream.write(CRNL)
- if (this.aborted)
- return
+ if(part.body instanceof stream.Stream) {
+ part.body.pipe(partStream)
+ } else {
+ partStream.end(part.body)
+ }
- this._processing++
- if (this.paused) {
- this._processQueue.push([pattern, index, inGlobStar, cb])
- return
- }
+ this._add(partStream)
+}
+},{"inherits":47,"sandwich-stream":123,"stream":124}],92:[function(require,module,exports){
+/* eslint-disable no-unused-vars */
+'use strict';
+var hasOwnProperty = Object.prototype.hasOwnProperty;
+var propIsEnumerable = Object.prototype.propertyIsEnumerable;
- //console.error('PROCESS %d', this._processing, pattern)
+function toObject(val) {
+ if (val === null || val === undefined) {
+ throw new TypeError('Object.assign cannot be called with null or undefined');
+ }
- // Get the first [n] parts of pattern that are all strings.
- var n = 0
- while (typeof pattern[n] === 'string') {
- n ++
- }
- // now n is the index of the first one that is *not* a string.
+ return Object(val);
+}
- // see if there's anything else
- var prefix
- switch (n) {
- // if not, then this is rather simple
- case pattern.length:
- this._processSimple(pattern.join('/'), index, cb)
- return
+module.exports = Object.assign || function (target, source) {
+ var from;
+ var to = toObject(target);
+ var symbols;
- case 0:
- // pattern *starts* with some non-trivial item.
- // going to readdir(cwd), but not include the prefix in matches.
- prefix = null
- break
+ for (var s = 1; s < arguments.length; s++) {
+ from = Object(arguments[s]);
- default:
- // pattern has some string bits in the front.
- // whatever it starts with, whether that's 'absolute' like /foo/bar,
- // or 'relative' like '../baz'
- prefix = pattern.slice(0, n).join('/')
- break
- }
+ for (var key in from) {
+ if (hasOwnProperty.call(from, key)) {
+ to[key] = from[key];
+ }
+ }
- var remain = pattern.slice(n)
+ if (Object.getOwnPropertySymbols) {
+ symbols = Object.getOwnPropertySymbols(from);
+ for (var i = 0; i < symbols.length; i++) {
+ if (propIsEnumerable.call(from, symbols[i])) {
+ to[symbols[i]] = from[symbols[i]];
+ }
+ }
+ }
+ }
- // get the list of entries.
- var read
- if (prefix === null)
- read = '.'
- else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
- if (!prefix || !isAbsolute(prefix))
- prefix = '/' + prefix
- read = prefix
- } else
- read = prefix
+ return to;
+};
- var abs = this._makeAbs(read)
+},{}],93:[function(require,module,exports){
+'use strict';
- //if ignored, skip _processing
- if (childrenIgnored(this, read))
- return cb()
+// modified from https://github.com/es-shims/es5-shim
+var has = Object.prototype.hasOwnProperty;
+var toStr = Object.prototype.toString;
+var slice = Array.prototype.slice;
+var isArgs = require('./isArguments');
+var hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
+var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
+var dontEnums = [
+ 'toString',
+ 'toLocaleString',
+ 'valueOf',
+ 'hasOwnProperty',
+ 'isPrototypeOf',
+ 'propertyIsEnumerable',
+ 'constructor'
+];
+var equalsConstructorPrototype = function (o) {
+ var ctor = o.constructor;
+ return ctor && ctor.prototype === o;
+};
+var blacklistedKeys = {
+ $console: true,
+ $frame: true,
+ $frameElement: true,
+ $frames: true,
+ $parent: true,
+ $self: true,
+ $webkitIndexedDB: true,
+ $webkitStorageInfo: true,
+ $window: true
+};
+var hasAutomationEqualityBug = (function () {
+ /* global window */
+ if (typeof window === 'undefined') { return false; }
+ for (var k in window) {
+ try {
+ if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
+ try {
+ equalsConstructorPrototype(window[k]);
+ } catch (e) {
+ return true;
+ }
+ }
+ } catch (e) {
+ return true;
+ }
+ }
+ return false;
+}());
+var equalsConstructorPrototypeIfNotBuggy = function (o) {
+ /* global window */
+ if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
+ return equalsConstructorPrototype(o);
+ }
+ try {
+ return equalsConstructorPrototype(o);
+ } catch (e) {
+ return false;
+ }
+};
- var isGlobStar = remain[0] === minimatch.GLOBSTAR
- if (isGlobStar)
- this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
- else
- this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
-}
+var keysShim = function keys(object) {
+ var isObject = object !== null && typeof object === 'object';
+ var isFunction = toStr.call(object) === '[object Function]';
+ var isArguments = isArgs(object);
+ var isString = isObject && toStr.call(object) === '[object String]';
+ var theKeys = [];
-Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
- var self = this
- this._readdir(abs, inGlobStar, function (er, entries) {
- return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
- })
-}
+ if (!isObject && !isFunction && !isArguments) {
+ throw new TypeError('Object.keys called on a non-object');
+ }
-Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
+ var skipProto = hasProtoEnumBug && isFunction;
+ if (isString && object.length > 0 && !has.call(object, 0)) {
+ for (var i = 0; i < object.length; ++i) {
+ theKeys.push(String(i));
+ }
+ }
- // if the abs isn't a dir, then nothing can match!
- if (!entries)
- return cb()
+ if (isArguments && object.length > 0) {
+ for (var j = 0; j < object.length; ++j) {
+ theKeys.push(String(j));
+ }
+ } else {
+ for (var name in object) {
+ if (!(skipProto && name === 'prototype') && has.call(object, name)) {
+ theKeys.push(String(name));
+ }
+ }
+ }
- // It will only match dot entries if it starts with a dot, or if
- // dot is set. Stuff like @(.foo|.bar) isn't allowed.
- var pn = remain[0]
- var negate = !!this.minimatch.negate
- var rawGlob = pn._glob
- var dotOk = this.dot || rawGlob.charAt(0) === '.'
+ if (hasDontEnumBug) {
+ var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
- var matchedEntries = []
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i]
- if (e.charAt(0) !== '.' || dotOk) {
- var m
- if (negate && !prefix) {
- m = !e.match(pn)
- } else {
- m = e.match(pn)
- }
- if (m)
- matchedEntries.push(e)
- }
- }
+ for (var k = 0; k < dontEnums.length; ++k) {
+ if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
+ theKeys.push(dontEnums[k]);
+ }
+ }
+ }
+ return theKeys;
+};
- //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
+keysShim.shim = function shimObjectKeys() {
+ if (Object.keys) {
+ var keysWorksWithArguments = (function () {
+ // Safari 5.0 bug
+ return (Object.keys(arguments) || '').length === 2;
+ }(1, 2));
+ if (!keysWorksWithArguments) {
+ var originalKeys = Object.keys;
+ Object.keys = function keys(object) {
+ if (isArgs(object)) {
+ return originalKeys(slice.call(object));
+ } else {
+ return originalKeys(object);
+ }
+ };
+ }
+ } else {
+ Object.keys = keysShim;
+ }
+ return Object.keys || keysShim;
+};
- var len = matchedEntries.length
- // If there are no matched entries, then nothing matches.
- if (len === 0)
- return cb()
+module.exports = keysShim;
- // if this is the last remaining pattern bit, then no need for
- // an additional stat *unless* the user has specified mark or
- // stat explicitly. We know they exist, since readdir returned
- // them.
+},{"./isArguments":94}],94:[function(require,module,exports){
+'use strict';
- if (remain.length === 1 && !this.mark && !this.stat) {
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
+var toStr = Object.prototype.toString;
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- if (prefix) {
- if (prefix !== '/')
- e = prefix + '/' + e
- else
- e = prefix + e
- }
+module.exports = function isArguments(value) {
+ var str = toStr.call(value);
+ var isArgs = str === '[object Arguments]';
+ if (!isArgs) {
+ isArgs = str !== '[object Array]' &&
+ value !== null &&
+ typeof value === 'object' &&
+ typeof value.length === 'number' &&
+ value.length >= 0 &&
+ toStr.call(value.callee) === '[object Function]';
+ }
+ return isArgs;
+};
- if (e.charAt(0) === '/' && !this.nomount) {
- e = path.join(this.root, e)
- }
- this._emitMatch(index, e)
- }
- // This was the last one, and no stats were needed
- return cb()
- }
+},{}],95:[function(require,module,exports){
+var wrappy = require('wrappy')
+module.exports = wrappy(once)
- // now test all matched entries as stand-ins for that part
- // of the pattern.
- remain.shift()
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- var newPattern
- if (prefix) {
- if (prefix !== '/')
- e = prefix + '/' + e
- else
- e = prefix + e
- }
- this._process([e].concat(remain), index, inGlobStar, cb)
+once.proto = once(function () {
+ Object.defineProperty(Function.prototype, 'once', {
+ value: function () {
+ return once(this)
+ },
+ configurable: true
+ })
+})
+
+function once (fn) {
+ var f = function () {
+ if (f.called) return f.value
+ f.called = true
+ return f.value = fn.apply(this, arguments)
}
- cb()
+ f.called = false
+ return f
}
-Glob.prototype._emitMatch = function (index, e) {
- if (this.aborted)
- return
+},{"wrappy":173}],96:[function(require,module,exports){
+var Readable = require('readable-stream').Readable;
+var isReadable = require('isstream').isReadable;
+var util = require('util');
- if (this.matches[index][e])
- return
- if (isIgnored(this, e))
- return
+function addStream(streams, stream)
+{
+ if(!isReadable(stream)) throw new Error('All input streams must be readable');
- if (this.paused) {
- this._emitQueue.push([index, e])
- return
- }
+ var self = this;
- var abs = this._makeAbs(e)
+ stream._buffer = [];
- if (this.nodir) {
- var c = this.cache[abs]
- if (c === 'DIR' || Array.isArray(c))
- return
- }
+ stream.on('readable', function()
+ {
+ var chunk = stream.read();
+ if (chunk === null)
+ return;
- if (this.mark)
- e = this._mark(e)
+ if(this === streams[0])
+ self.push(chunk);
- this.matches[index][e] = true
+ else
+ this._buffer.push(chunk);
+ });
- var st = this.statCache[abs]
- if (st)
- this.emit('stat', e, st)
+ stream.on('end', function()
+ {
+ for(var stream = streams[0];
+ stream && stream._readableState.ended;
+ stream = streams[0])
+ {
+ while(stream._buffer.length)
+ self.push(stream._buffer.shift());
- this.emit('match', e)
-}
+ streams.shift();
+ }
-Glob.prototype._readdirInGlobStar = function (abs, cb) {
- if (this.aborted)
- return
+ if(!streams.length) self.push(null);
+ });
- // follow all symlinked directories forever
- // just proceed as if this is a non-globstar situation
- if (this.follow)
- return this._readdir(abs, false, cb)
+ stream.on('error', this.emit.bind(this, 'error'));
- var lstatkey = 'lstat\0' + abs
- var self = this
- var lstatcb = inflight(lstatkey, lstatcb_)
+ streams.push(stream);
+}
- if (lstatcb)
- fs.lstat(abs, lstatcb)
- function lstatcb_ (er, lstat) {
- if (er)
- return cb()
+function OrderedStreams(streams, options) {
+ if (!(this instanceof(OrderedStreams))) {
+ return new OrderedStreams(streams, options);
+ }
- var isSym = lstat.isSymbolicLink()
- self.symlinks[abs] = isSym
+ streams = streams || [];
+ options = options || {};
- // If it's not a symlink or a dir, then it's definitely a regular file.
- // don't bother doing a readdir in that case.
- if (!isSym && !lstat.isDirectory()) {
- self.cache[abs] = 'FILE'
- cb()
- } else
- self._readdir(abs, false, cb)
- }
-}
+ options.objectMode = true;
-Glob.prototype._readdir = function (abs, inGlobStar, cb) {
- if (this.aborted)
- return
+ Readable.call(this, options);
- cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
- if (!cb)
- return
- //console.error('RD %j %j', +inGlobStar, abs)
- if (inGlobStar && !ownProp(this.symlinks, abs))
- return this._readdirInGlobStar(abs, cb)
+ if(!Array.isArray(streams)) streams = [streams];
+ if(!streams.length) return this.push(null); // no streams, close
- if (ownProp(this.cache, abs)) {
- var c = this.cache[abs]
- if (!c || c === 'FILE')
- return cb()
- if (Array.isArray(c))
- return cb(null, c)
- }
+ var addStream_bind = addStream.bind(this, []);
- var self = this
- fs.readdir(abs, readdirCb(this, abs, cb))
-}
-function readdirCb (self, abs, cb) {
- return function (er, entries) {
- if (er)
- self._readdirError(abs, er, cb)
+ streams.forEach(function(item)
+ {
+ if(Array.isArray(item))
+ item.forEach(addStream_bind);
+
else
- self._readdirEntries(abs, entries, cb)
- }
+ addStream_bind(item);
+ });
}
+util.inherits(OrderedStreams, Readable);
-Glob.prototype._readdirEntries = function (abs, entries, cb) {
- if (this.aborted)
- return
+OrderedStreams.prototype._read = function () {};
- // if we haven't asked to stat everything, then just
- // assume that everything in there exists, so we can avoid
- // having to stat it a second time.
- if (!this.mark && !this.stat) {
- for (var i = 0; i < entries.length; i ++) {
- var e = entries[i]
- if (abs === '/')
- e = abs + e
- else
- e = abs + '/' + e
- this.cache[e] = true
- }
- }
- this.cache[abs] = entries
- return cb(null, entries)
-}
+module.exports = OrderedStreams;
-Glob.prototype._readdirError = function (f, er, cb) {
- if (this.aborted)
- return
+},{"isstream":54,"readable-stream":102,"util":138}],97:[function(require,module,exports){
+arguments[4][23][0].apply(exports,arguments)
+},{"./_stream_readable":99,"./_stream_writable":101,"_process":107,"core-util-is":15,"dup":23,"inherits":47}],98:[function(require,module,exports){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
- // handle errors, and cache the information
- switch (er.code) {
- case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
- case 'ENOTDIR': // totally normal. means it *does* exist.
- this.cache[this._makeAbs(f)] = 'FILE'
- break
+// a passthrough stream.
+// basically just the most minimal sort of Transform stream.
+// Every written chunk gets output as-is.
- case 'ENOENT': // not terribly unusual
- case 'ELOOP':
- case 'ENAMETOOLONG':
- case 'UNKNOWN':
- this.cache[this._makeAbs(f)] = false
- break
+module.exports = PassThrough;
- default: // some unusual error. Treat as failure.
- this.cache[this._makeAbs(f)] = false
- if (this.strict) {
- this.emit('error', er)
- // If the error is handled, then we abort
- // if not, we threw out of here
- this.abort()
- }
- if (!this.silent)
- console.error('glob error', er)
- break
- }
+var Transform = require('./_stream_transform');
+
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
+
+util.inherits(PassThrough, Transform);
+
+function PassThrough(options) {
+ if (!(this instanceof PassThrough))
+ return new PassThrough(options);
- return cb()
+ Transform.call(this, options);
}
-Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
- var self = this
- this._readdir(abs, inGlobStar, function (er, entries) {
- self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
- })
-}
+PassThrough.prototype._transform = function(chunk, encoding, cb) {
+ cb(null, chunk);
+};
+},{"./_stream_transform":100,"core-util-is":15,"inherits":47}],99:[function(require,module,exports){
+(function (process){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
-Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
- //console.error('pgs2', prefix, remain[0], entries)
+module.exports = Readable;
- // no entries means not a dir, so it can never have matches
- // foo.txt/** doesn't match foo.txt
- if (!entries)
- return cb()
+/**/
+var isArray = require('isarray');
+/**/
- // test without the globstar, and with every child both below
- // and replacing the globstar.
- var remainWithoutGlobStar = remain.slice(1)
- var gspref = prefix ? [ prefix ] : []
- var noGlobStar = gspref.concat(remainWithoutGlobStar)
- // the noGlobStar pattern exits the inGlobStar state
- this._process(noGlobStar, index, false, cb)
+/**/
+var Buffer = require('buffer').Buffer;
+/**/
- var isSym = this.symlinks[abs]
- var len = entries.length
+Readable.ReadableState = ReadableState;
- // If it's a symlink, and we're in a globstar, then stop
- if (isSym && inGlobStar)
- return cb()
+var EE = require('events').EventEmitter;
- for (var i = 0; i < len; i++) {
- var e = entries[i]
- if (e.charAt(0) === '.' && !this.dot)
- continue
+/**/
+if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
+ return emitter.listeners(type).length;
+};
+/**/
- // these two cases enter the inGlobStar state
- var instead = gspref.concat(entries[i], remainWithoutGlobStar)
- this._process(instead, index, true, cb)
+var Stream = require('stream');
- var below = gspref.concat(entries[i], remain)
- this._process(below, index, true, cb)
- }
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
- cb()
-}
+var StringDecoder;
-Glob.prototype._processSimple = function (prefix, index, cb) {
- // XXX review this. Shouldn't it be doing the mounting etc
- // before doing stat? kinda weird?
- var self = this
- this._stat(prefix, function (er, exists) {
- self._processSimple2(prefix, index, er, exists, cb)
- })
+
+/**/
+var debug = require('util');
+if (debug && debug.debuglog) {
+ debug = debug.debuglog('stream');
+} else {
+ debug = function () {};
}
-Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
+/**/
- //console.error('ps2', prefix, exists)
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
+util.inherits(Readable, Stream);
- // If it doesn't exist, then just mark the lack of results
- if (!exists)
- return cb()
+function ReadableState(options, stream) {
+ var Duplex = require('./_stream_duplex');
- if (prefix && isAbsolute(prefix) && !this.nomount) {
- var trail = /[\/\\]$/.test(prefix)
- if (prefix.charAt(0) === '/') {
- prefix = path.join(this.root, prefix)
- } else {
- prefix = path.resolve(this.root, prefix)
- if (trail)
- prefix += '/'
- }
- }
+ options = options || {};
- if (process.platform === 'win32')
- prefix = prefix.replace(/\\/g, '/')
+ // the point at which it stops calling _read() to fill the buffer
+ // Note: 0 is a valid value, means "don't call _read preemptively ever"
+ var hwm = options.highWaterMark;
+ var defaultHwm = options.objectMode ? 16 : 16 * 1024;
+ this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
- // Mark this as a match
- this._emitMatch(index, prefix)
- cb()
-}
+ // cast to ints.
+ this.highWaterMark = ~~this.highWaterMark;
-// Returns either 'DIR', 'FILE', or false
-Glob.prototype._stat = function (f, cb) {
- var abs = this._makeAbs(f)
- var needDir = f.slice(-1) === '/'
+ this.buffer = [];
+ this.length = 0;
+ this.pipes = null;
+ this.pipesCount = 0;
+ this.flowing = null;
+ this.ended = false;
+ this.endEmitted = false;
+ this.reading = false;
- if (f.length > this.maxLength)
- return cb()
+ // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, because any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+ this.sync = true;
- if (!this.stat && ownProp(this.cache, abs)) {
- var c = this.cache[abs]
+ // whenever we return null, then we set a flag to say
+ // that we're awaiting a 'readable' event emission.
+ this.needReadable = false;
+ this.emittedReadable = false;
+ this.readableListening = false;
- if (Array.isArray(c))
- c = 'DIR'
- // It exists, but maybe not how we need it
- if (!needDir || c === 'DIR')
- return cb(null, c)
+ // object stream flag. Used to make read(n) ignore n and to
+ // make all the buffer merging and length checks go away
+ this.objectMode = !!options.objectMode;
- if (needDir && c === 'FILE')
- return cb()
+ if (stream instanceof Duplex)
+ this.objectMode = this.objectMode || !!options.readableObjectMode;
- // otherwise we have to stat, because maybe c=true
- // if we know it exists, but not what it is.
- }
+ // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+ this.defaultEncoding = options.defaultEncoding || 'utf8';
- var exists
- var stat = this.statCache[abs]
- if (stat !== undefined) {
- if (stat === false)
- return cb(null, stat)
- else {
- var type = stat.isDirectory() ? 'DIR' : 'FILE'
- if (needDir && type === 'FILE')
- return cb()
- else
- return cb(null, type, stat)
- }
- }
+ // when piping, we only care about 'readable' events that happen
+ // after read()ing all the bytes and not getting any pushback.
+ this.ranOut = false;
- var self = this
- var statcb = inflight('stat\0' + abs, lstatcb_)
- if (statcb)
- fs.lstat(abs, statcb)
+ // the number of writers that are awaiting a drain event in .pipe()s
+ this.awaitDrain = 0;
- function lstatcb_ (er, lstat) {
- if (lstat && lstat.isSymbolicLink()) {
- // If it's a symlink, then treat it as the target, unless
- // the target does not exist, then treat it as a file.
- return fs.stat(abs, function (er, stat) {
- if (er)
- self._stat2(f, abs, null, lstat, cb)
- else
- self._stat2(f, abs, er, stat, cb)
- })
- } else {
- self._stat2(f, abs, er, lstat, cb)
- }
+ // if true, a maybeReadMore has been scheduled
+ this.readingMore = false;
+
+ this.decoder = null;
+ this.encoding = null;
+ if (options.encoding) {
+ if (!StringDecoder)
+ StringDecoder = require('string_decoder/').StringDecoder;
+ this.decoder = new StringDecoder(options.encoding);
+ this.encoding = options.encoding;
}
}
-Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
- if (er) {
- this.statCache[abs] = false
- return cb()
- }
+function Readable(options) {
+ var Duplex = require('./_stream_duplex');
- var needDir = f.slice(-1) === '/'
- this.statCache[abs] = stat
+ if (!(this instanceof Readable))
+ return new Readable(options);
- if (abs.slice(-1) === '/' && !stat.isDirectory())
- return cb(null, false, stat)
+ this._readableState = new ReadableState(options, this);
+
+ // legacy
+ this.readable = true;
+
+ Stream.call(this);
+}
+
+// Manually shove something into the read() buffer.
+// This returns true if the highWaterMark has not been hit yet,
+// similar to how Writable.write() returns true if you should
+// write() some more.
+Readable.prototype.push = function(chunk, encoding) {
+ var state = this._readableState;
+
+ if (util.isString(chunk) && !state.objectMode) {
+ encoding = encoding || state.defaultEncoding;
+ if (encoding !== state.encoding) {
+ chunk = new Buffer(chunk, encoding);
+ encoding = '';
+ }
+ }
- var c = stat.isDirectory() ? 'DIR' : 'FILE'
- this.cache[abs] = this.cache[abs] || c
+ return readableAddChunk(this, state, chunk, encoding, false);
+};
- if (needDir && c !== 'DIR')
- return cb()
+// Unshift should *always* be something directly out of read()
+Readable.prototype.unshift = function(chunk) {
+ var state = this._readableState;
+ return readableAddChunk(this, state, chunk, '', true);
+};
- return cb(null, c, stat)
-}
+function readableAddChunk(stream, state, chunk, encoding, addToFront) {
+ var er = chunkInvalid(state, chunk);
+ if (er) {
+ stream.emit('error', er);
+ } else if (util.isNullOrUndefined(chunk)) {
+ state.reading = false;
+ if (!state.ended)
+ onEofChunk(stream, state);
+ } else if (state.objectMode || chunk && chunk.length > 0) {
+ if (state.ended && !addToFront) {
+ var e = new Error('stream.push() after EOF');
+ stream.emit('error', e);
+ } else if (state.endEmitted && addToFront) {
+ var e = new Error('stream.unshift() after end event');
+ stream.emit('error', e);
+ } else {
+ if (state.decoder && !addToFront && !encoding)
+ chunk = state.decoder.write(chunk);
-}).call(this,require('_process'))
-},{"./common.js":145,"./sync.js":153,"_process":64,"assert":1,"events":14,"fs":4,"inflight":147,"inherits":149,"minimatch":156,"once":151,"path":62,"path-is-absolute":152,"util":90}],147:[function(require,module,exports){
-(function (process){
-var wrappy = require('wrappy')
-var reqs = Object.create(null)
-var once = require('once')
+ if (!addToFront)
+ state.reading = false;
-module.exports = wrappy(inflight)
+ // if we want the data now, just emit it.
+ if (state.flowing && state.length === 0 && !state.sync) {
+ stream.emit('data', chunk);
+ stream.read(0);
+ } else {
+ // update the buffer info.
+ state.length += state.objectMode ? 1 : chunk.length;
+ if (addToFront)
+ state.buffer.unshift(chunk);
+ else
+ state.buffer.push(chunk);
-function inflight (key, cb) {
- if (reqs[key]) {
- reqs[key].push(cb)
- return null
- } else {
- reqs[key] = [cb]
- return makeres(key)
- }
-}
+ if (state.needReadable)
+ emitReadable(stream);
+ }
-function makeres (key) {
- return once(function RES () {
- var cbs = reqs[key]
- var len = cbs.length
- var args = slice(arguments)
- for (var i = 0; i < len; i++) {
- cbs[i].apply(null, args)
- }
- if (cbs.length > len) {
- // added more in the interim.
- // de-zalgo, just in case, but don't call again.
- cbs.splice(0, len)
- process.nextTick(function () {
- RES.apply(null, args)
- })
- } else {
- delete reqs[key]
+ maybeReadMore(stream, state);
}
- })
-}
-
-function slice (args) {
- var length = args.length
- var array = []
+ } else if (!addToFront) {
+ state.reading = false;
+ }
- for (var i = 0; i < length; i++) array[i] = args[i]
- return array
+ return needMoreData(state);
}
-}).call(this,require('_process'))
-},{"_process":64,"once":151,"wrappy":148}],148:[function(require,module,exports){
-arguments[4][103][0].apply(exports,arguments)
-},{"dup":103}],149:[function(require,module,exports){
-arguments[4][18][0].apply(exports,arguments)
-},{"dup":18}],150:[function(require,module,exports){
-arguments[4][103][0].apply(exports,arguments)
-},{"dup":103}],151:[function(require,module,exports){
-arguments[4][60][0].apply(exports,arguments)
-},{"dup":60,"wrappy":150}],152:[function(require,module,exports){
-(function (process){
-'use strict';
-function posix(path) {
- return path.charAt(0) === '/';
-};
-function win32(path) {
- // https://github.com/joyent/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
- var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
- var result = splitDeviceRe.exec(path);
- var device = result[1] || '';
- var isUnc = !!device && device.charAt(1) !== ':';
+// if it's past the high water mark, we can push in some more.
+// Also, if we have no data yet, we can stand some
+// more bytes. This is to work around cases where hwm=0,
+// such as the repl. Also, if the push() triggered a
+// readable event, and the user called read(largeNumber) such that
+// needReadable was set, then we ought to push more, so that another
+// 'readable' event will be triggered.
+function needMoreData(state) {
+ return !state.ended &&
+ (state.needReadable ||
+ state.length < state.highWaterMark ||
+ state.length === 0);
+}
- // UNC paths are always absolute
- return !!result[2] || isUnc;
+// backwards compatibility.
+Readable.prototype.setEncoding = function(enc) {
+ if (!StringDecoder)
+ StringDecoder = require('string_decoder/').StringDecoder;
+ this._readableState.decoder = new StringDecoder(enc);
+ this._readableState.encoding = enc;
+ return this;
};
-module.exports = process.platform === 'win32' ? win32 : posix;
-module.exports.posix = posix;
-module.exports.win32 = win32;
+// Don't raise the hwm > 128MB
+var MAX_HWM = 0x800000;
+function roundUpToNextPowerOf2(n) {
+ if (n >= MAX_HWM) {
+ n = MAX_HWM;
+ } else {
+ // Get the next highest power of 2
+ n--;
+ for (var p = 1; p < 32; p <<= 1) n |= n >> p;
+ n++;
+ }
+ return n;
+}
-}).call(this,require('_process'))
-},{"_process":64}],153:[function(require,module,exports){
-(function (process){
-module.exports = globSync
-globSync.GlobSync = GlobSync
+function howMuchToRead(n, state) {
+ if (state.length === 0 && state.ended)
+ return 0;
-var fs = require('fs')
-var minimatch = require('minimatch')
-var Minimatch = minimatch.Minimatch
-var Glob = require('./glob.js').Glob
-var util = require('util')
-var path = require('path')
-var assert = require('assert')
-var isAbsolute = require('path-is-absolute')
-var common = require('./common.js')
-var alphasort = common.alphasort
-var alphasorti = common.alphasorti
-var setopts = common.setopts
-var ownProp = common.ownProp
-var childrenIgnored = common.childrenIgnored
+ if (state.objectMode)
+ return n === 0 ? 0 : 1;
-function globSync (pattern, options) {
- if (typeof options === 'function' || arguments.length === 3)
- throw new TypeError('callback provided to sync glob\n'+
- 'See: https://github.com/isaacs/node-glob/issues/167')
+ if (isNaN(n) || util.isNull(n)) {
+ // only flow one buffer at a time
+ if (state.flowing && state.buffer.length)
+ return state.buffer[0].length;
+ else
+ return state.length;
+ }
- return new GlobSync(pattern, options).found
-}
+ if (n <= 0)
+ return 0;
-function GlobSync (pattern, options) {
- if (!pattern)
- throw new Error('must provide pattern')
+ // If we're asking for more than the target buffer level,
+ // then raise the water mark. Bump up to the next highest
+ // power of 2, to prevent increasing it excessively in tiny
+ // amounts.
+ if (n > state.highWaterMark)
+ state.highWaterMark = roundUpToNextPowerOf2(n);
- if (typeof options === 'function' || arguments.length === 3)
- throw new TypeError('callback provided to sync glob\n'+
- 'See: https://github.com/isaacs/node-glob/issues/167')
+ // don't have that much. return null, unless we've ended.
+ if (n > state.length) {
+ if (!state.ended) {
+ state.needReadable = true;
+ return 0;
+ } else
+ return state.length;
+ }
- if (!(this instanceof GlobSync))
- return new GlobSync(pattern, options)
+ return n;
+}
- setopts(this, pattern, options)
+// you can override either this method, or the async _read(n) below.
+Readable.prototype.read = function(n) {
+ debug('read', n);
+ var state = this._readableState;
+ var nOrig = n;
- if (this.noprocess)
- return this
+ if (!util.isNumber(n) || n > 0)
+ state.emittedReadable = false;
- var n = this.minimatch.set.length
- this.matches = new Array(n)
- for (var i = 0; i < n; i ++) {
- this._process(this.minimatch.set[i], i, false)
+ // if we're doing read(0) to trigger a readable event, but we
+ // already have a bunch of data in the buffer, then just trigger
+ // the 'readable' event and move on.
+ if (n === 0 &&
+ state.needReadable &&
+ (state.length >= state.highWaterMark || state.ended)) {
+ debug('read: emitReadable', state.length, state.ended);
+ if (state.length === 0 && state.ended)
+ endReadable(this);
+ else
+ emitReadable(this);
+ return null;
}
- this._finish()
-}
-GlobSync.prototype._finish = function () {
- assert(this instanceof GlobSync)
- if (this.realpath) {
- var self = this
- this.matches.forEach(function (matchset, index) {
- var set = self.matches[index] = Object.create(null)
- for (var p in matchset) {
- try {
- p = self._makeAbs(p)
- var real = fs.realpathSync(p, self.realpathCache)
- set[real] = true
- } catch (er) {
- if (er.syscall === 'stat')
- set[self._makeAbs(p)] = true
- else
- throw er
- }
- }
- })
+ n = howMuchToRead(n, state);
+
+ // if we've ended, and we're now clear, then finish it up.
+ if (n === 0 && state.ended) {
+ if (state.length === 0)
+ endReadable(this);
+ return null;
}
- common.finish(this)
-}
+ // All the actual chunk generation logic needs to be
+ // *below* the call to _read. The reason is that in certain
+ // synthetic stream cases, such as passthrough streams, _read
+ // may be a completely synchronous operation which may change
+ // the state of the read buffer, providing enough data when
+ // before there was *not* enough.
+ //
+ // So, the steps are:
+ // 1. Figure out what the state of things will be after we do
+ // a read from the buffer.
+ //
+ // 2. If that resulting state will trigger a _read, then call _read.
+ // Note that this may be asynchronous, or synchronous. Yes, it is
+ // deeply ugly to write APIs this way, but that still doesn't mean
+ // that the Readable class should behave improperly, as streams are
+ // designed to be sync/async agnostic.
+ // Take note if the _read call is sync or async (ie, if the read call
+ // has returned yet), so that we know whether or not it's safe to emit
+ // 'readable' etc.
+ //
+ // 3. Actually pull the requested chunks out of the buffer and return.
-GlobSync.prototype._process = function (pattern, index, inGlobStar) {
- assert(this instanceof GlobSync)
+ // if we need a readable event, then we need to do some reading.
+ var doRead = state.needReadable;
+ debug('need readable', doRead);
- // Get the first [n] parts of pattern that are all strings.
- var n = 0
- while (typeof pattern[n] === 'string') {
- n ++
+ // if we currently have less than the highWaterMark, then also read some
+ if (state.length === 0 || state.length - n < state.highWaterMark) {
+ doRead = true;
+ debug('length less than watermark', doRead);
}
- // now n is the index of the first one that is *not* a string.
-
- // See if there's anything else
- var prefix
- switch (n) {
- // if not, then this is rather simple
- case pattern.length:
- this._processSimple(pattern.join('/'), index)
- return
- case 0:
- // pattern *starts* with some non-trivial item.
- // going to readdir(cwd), but not include the prefix in matches.
- prefix = null
- break
+ // however, if we've ended, then there's no point, and if we're already
+ // reading, then it's unnecessary.
+ if (state.ended || state.reading) {
+ doRead = false;
+ debug('reading or ended', doRead);
+ }
- default:
- // pattern has some string bits in the front.
- // whatever it starts with, whether that's 'absolute' like /foo/bar,
- // or 'relative' like '../baz'
- prefix = pattern.slice(0, n).join('/')
- break
+ if (doRead) {
+ debug('do read');
+ state.reading = true;
+ state.sync = true;
+ // if the length is currently zero, then we *need* a readable event.
+ if (state.length === 0)
+ state.needReadable = true;
+ // call internal read method
+ this._read(state.highWaterMark);
+ state.sync = false;
}
- var remain = pattern.slice(n)
+ // If _read pushed data synchronously, then `reading` will be false,
+ // and we need to re-evaluate how much data we can return to the user.
+ if (doRead && !state.reading)
+ n = howMuchToRead(nOrig, state);
- // get the list of entries.
- var read
- if (prefix === null)
- read = '.'
- else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
- if (!prefix || !isAbsolute(prefix))
- prefix = '/' + prefix
- read = prefix
- } else
- read = prefix
+ var ret;
+ if (n > 0)
+ ret = fromList(n, state);
+ else
+ ret = null;
- var abs = this._makeAbs(read)
+ if (util.isNull(ret)) {
+ state.needReadable = true;
+ n = 0;
+ }
- //if ignored, skip processing
- if (childrenIgnored(this, read))
- return
+ state.length -= n;
- var isGlobStar = remain[0] === minimatch.GLOBSTAR
- if (isGlobStar)
- this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
- else
- this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
-}
+ // If we have nothing in the buffer, then we want to know
+ // as soon as we *do* get something into the buffer.
+ if (state.length === 0 && !state.ended)
+ state.needReadable = true;
+ // If we tried to read() past the EOF, then emit end on the next tick.
+ if (nOrig !== n && state.ended && state.length === 0)
+ endReadable(this);
-GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
- var entries = this._readdir(abs, inGlobStar)
+ if (!util.isNull(ret))
+ this.emit('data', ret);
- // if the abs isn't a dir, then nothing can match!
- if (!entries)
- return
+ return ret;
+};
- // It will only match dot entries if it starts with a dot, or if
- // dot is set. Stuff like @(.foo|.bar) isn't allowed.
- var pn = remain[0]
- var negate = !!this.minimatch.negate
- var rawGlob = pn._glob
- var dotOk = this.dot || rawGlob.charAt(0) === '.'
+function chunkInvalid(state, chunk) {
+ var er = null;
+ if (!util.isBuffer(chunk) &&
+ !util.isString(chunk) &&
+ !util.isNullOrUndefined(chunk) &&
+ !state.objectMode) {
+ er = new TypeError('Invalid non-string/buffer chunk');
+ }
+ return er;
+}
- var matchedEntries = []
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i]
- if (e.charAt(0) !== '.' || dotOk) {
- var m
- if (negate && !prefix) {
- m = !e.match(pn)
- } else {
- m = e.match(pn)
- }
- if (m)
- matchedEntries.push(e)
+
+function onEofChunk(stream, state) {
+ if (state.decoder && !state.ended) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length) {
+ state.buffer.push(chunk);
+ state.length += state.objectMode ? 1 : chunk.length;
}
}
+ state.ended = true;
- var len = matchedEntries.length
- // If there are no matched entries, then nothing matches.
- if (len === 0)
- return
+ // emit 'readable' now to make sure it gets picked up.
+ emitReadable(stream);
+}
- // if this is the last remaining pattern bit, then no need for
- // an additional stat *unless* the user has specified mark or
- // stat explicitly. We know they exist, since readdir returned
- // them.
+// Don't emit readable right away in sync mode, because this can trigger
+// another read() call => stack overflow. This way, it might trigger
+// a nextTick recursion warning, but that's not so bad.
+function emitReadable(stream) {
+ var state = stream._readableState;
+ state.needReadable = false;
+ if (!state.emittedReadable) {
+ debug('emitReadable', state.flowing);
+ state.emittedReadable = true;
+ if (state.sync)
+ process.nextTick(function() {
+ emitReadable_(stream);
+ });
+ else
+ emitReadable_(stream);
+ }
+}
- if (remain.length === 1 && !this.mark && !this.stat) {
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
+function emitReadable_(stream) {
+ debug('emit readable');
+ stream.emit('readable');
+ flow(stream);
+}
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- if (prefix) {
- if (prefix.slice(-1) !== '/')
- e = prefix + '/' + e
- else
- e = prefix + e
- }
- if (e.charAt(0) === '/' && !this.nomount) {
- e = path.join(this.root, e)
- }
- this.matches[index][e] = true
- }
- // This was the last one, and no stats were needed
- return
+// at this point, the user has presumably seen the 'readable' event,
+// and called read() to consume some data. that may have triggered
+// in turn another _read(n) call, in which case reading = true if
+// it's in progress.
+// However, if we're not ended, or reading, and the length < hwm,
+// then go ahead and try to read some more preemptively.
+function maybeReadMore(stream, state) {
+ if (!state.readingMore) {
+ state.readingMore = true;
+ process.nextTick(function() {
+ maybeReadMore_(stream, state);
+ });
}
+}
- // now test all matched entries as stand-ins for that part
- // of the pattern.
- remain.shift()
- for (var i = 0; i < len; i ++) {
- var e = matchedEntries[i]
- var newPattern
- if (prefix)
- newPattern = [prefix, e]
+function maybeReadMore_(stream, state) {
+ var len = state.length;
+ while (!state.reading && !state.flowing && !state.ended &&
+ state.length < state.highWaterMark) {
+ debug('maybeReadMore read 0');
+ stream.read(0);
+ if (len === state.length)
+ // didn't get any data, stop spinning.
+ break;
else
- newPattern = [e]
- this._process(newPattern.concat(remain), index, inGlobStar)
+ len = state.length;
}
+ state.readingMore = false;
}
+// abstract method. to be overridden in specific implementation classes.
+// call cb(er, data) where data is <= n in length.
+// for virtual (non-string, non-buffer) streams, "length" is somewhat
+// arbitrary, and perhaps not very meaningful.
+Readable.prototype._read = function(n) {
+ this.emit('error', new Error('not implemented'));
+};
+
+Readable.prototype.pipe = function(dest, pipeOpts) {
+ var src = this;
+ var state = this._readableState;
-GlobSync.prototype._emitMatch = function (index, e) {
- var abs = this._makeAbs(e)
- if (this.mark)
- e = this._mark(e)
+ switch (state.pipesCount) {
+ case 0:
+ state.pipes = dest;
+ break;
+ case 1:
+ state.pipes = [state.pipes, dest];
+ break;
+ default:
+ state.pipes.push(dest);
+ break;
+ }
+ state.pipesCount += 1;
+ debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
- if (this.matches[index][e])
- return
+ var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
+ dest !== process.stdout &&
+ dest !== process.stderr;
- if (this.nodir) {
- var c = this.cache[this._makeAbs(e)]
- if (c === 'DIR' || Array.isArray(c))
- return
+ var endFn = doEnd ? onend : cleanup;
+ if (state.endEmitted)
+ process.nextTick(endFn);
+ else
+ src.once('end', endFn);
+
+ dest.on('unpipe', onunpipe);
+ function onunpipe(readable) {
+ debug('onunpipe');
+ if (readable === src) {
+ cleanup();
+ }
}
- this.matches[index][e] = true
- if (this.stat)
- this._stat(e)
-}
+ function onend() {
+ debug('onend');
+ dest.end();
+ }
+ // when the dest drains, it reduces the awaitDrain counter
+ // on the source. This would be more elegant with a .once()
+ // handler in flow(), but adding and removing repeatedly is
+ // too slow.
+ var ondrain = pipeOnDrain(src);
+ dest.on('drain', ondrain);
-GlobSync.prototype._readdirInGlobStar = function (abs) {
- // follow all symlinked directories forever
- // just proceed as if this is a non-globstar situation
- if (this.follow)
- return this._readdir(abs, false)
+ function cleanup() {
+ debug('cleanup');
+ // cleanup event handlers once the pipe is broken
+ dest.removeListener('close', onclose);
+ dest.removeListener('finish', onfinish);
+ dest.removeListener('drain', ondrain);
+ dest.removeListener('error', onerror);
+ dest.removeListener('unpipe', onunpipe);
+ src.removeListener('end', onend);
+ src.removeListener('end', cleanup);
+ src.removeListener('data', ondata);
- var entries
- var lstat
- var stat
- try {
- lstat = fs.lstatSync(abs)
- } catch (er) {
- // lstat failed, doesn't exist
- return null
+ // if the reader is waiting for a drain event from this
+ // specific writer, then it would cause it to never start
+ // flowing again.
+ // So, if this is awaiting a drain, then we just call it now.
+ // If we don't know, then assume that we are waiting for one.
+ if (state.awaitDrain &&
+ (!dest._writableState || dest._writableState.needDrain))
+ ondrain();
}
- var isSym = lstat.isSymbolicLink()
- this.symlinks[abs] = isSym
+ src.on('data', ondata);
+ function ondata(chunk) {
+ debug('ondata');
+ var ret = dest.write(chunk);
+ if (false === ret) {
+ debug('false write response, pause',
+ src._readableState.awaitDrain);
+ src._readableState.awaitDrain++;
+ src.pause();
+ }
+ }
- // If it's not a symlink or a dir, then it's definitely a regular file.
- // don't bother doing a readdir in that case.
- if (!isSym && !lstat.isDirectory())
- this.cache[abs] = 'FILE'
+ // if the dest has an error, then stop piping into it.
+ // however, don't suppress the throwing behavior for this.
+ function onerror(er) {
+ debug('onerror', er);
+ unpipe();
+ dest.removeListener('error', onerror);
+ if (EE.listenerCount(dest, 'error') === 0)
+ dest.emit('error', er);
+ }
+ // This is a brutally ugly hack to make sure that our error handler
+ // is attached before any userland ones. NEVER DO THIS.
+ if (!dest._events || !dest._events.error)
+ dest.on('error', onerror);
+ else if (isArray(dest._events.error))
+ dest._events.error.unshift(onerror);
else
- entries = this._readdir(abs, false)
-
- return entries
-}
-
-GlobSync.prototype._readdir = function (abs, inGlobStar) {
- var entries
+ dest._events.error = [onerror, dest._events.error];
- if (inGlobStar && !ownProp(this.symlinks, abs))
- return this._readdirInGlobStar(abs)
- if (ownProp(this.cache, abs)) {
- var c = this.cache[abs]
- if (!c || c === 'FILE')
- return null
- if (Array.isArray(c))
- return c
+ // Both close and finish should trigger unpipe, but only once.
+ function onclose() {
+ dest.removeListener('finish', onfinish);
+ unpipe();
+ }
+ dest.once('close', onclose);
+ function onfinish() {
+ debug('onfinish');
+ dest.removeListener('close', onclose);
+ unpipe();
}
+ dest.once('finish', onfinish);
- try {
- return this._readdirEntries(abs, fs.readdirSync(abs))
- } catch (er) {
- this._readdirError(abs, er)
- return null
+ function unpipe() {
+ debug('unpipe');
+ src.unpipe(dest);
}
-}
-GlobSync.prototype._readdirEntries = function (abs, entries) {
- // if we haven't asked to stat everything, then just
- // assume that everything in there exists, so we can avoid
- // having to stat it a second time.
- if (!this.mark && !this.stat) {
- for (var i = 0; i < entries.length; i ++) {
- var e = entries[i]
- if (abs === '/')
- e = abs + e
- else
- e = abs + '/' + e
- this.cache[e] = true
- }
+ // tell the dest that it's being piped to
+ dest.emit('pipe', src);
+
+ // start the flow if it hasn't been started already.
+ if (!state.flowing) {
+ debug('pipe resume');
+ src.resume();
}
- this.cache[abs] = entries
+ return dest;
+};
- // mark and cache dir-ness
- return entries
+function pipeOnDrain(src) {
+ return function() {
+ var state = src._readableState;
+ debug('pipeOnDrain', state.awaitDrain);
+ if (state.awaitDrain)
+ state.awaitDrain--;
+ if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
+ state.flowing = true;
+ flow(src);
+ }
+ };
}
-GlobSync.prototype._readdirError = function (f, er) {
- // handle errors, and cache the information
- switch (er.code) {
- case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
- case 'ENOTDIR': // totally normal. means it *does* exist.
- this.cache[this._makeAbs(f)] = 'FILE'
- break
- case 'ENOENT': // not terribly unusual
- case 'ELOOP':
- case 'ENAMETOOLONG':
- case 'UNKNOWN':
- this.cache[this._makeAbs(f)] = false
- break
+Readable.prototype.unpipe = function(dest) {
+ var state = this._readableState;
- default: // some unusual error. Treat as failure.
- this.cache[this._makeAbs(f)] = false
- if (this.strict)
- throw er
- if (!this.silent)
- console.error('glob error', er)
- break
- }
-}
+ // if we're not piping anywhere, then do nothing.
+ if (state.pipesCount === 0)
+ return this;
-GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
+ // just one destination. most common case.
+ if (state.pipesCount === 1) {
+ // passed in one, but it's not the right one.
+ if (dest && dest !== state.pipes)
+ return this;
- var entries = this._readdir(abs, inGlobStar)
+ if (!dest)
+ dest = state.pipes;
- // no entries means not a dir, so it can never have matches
- // foo.txt/** doesn't match foo.txt
- if (!entries)
- return
+ // got a match.
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+ if (dest)
+ dest.emit('unpipe', this);
+ return this;
+ }
- // test without the globstar, and with every child both below
- // and replacing the globstar.
- var remainWithoutGlobStar = remain.slice(1)
- var gspref = prefix ? [ prefix ] : []
- var noGlobStar = gspref.concat(remainWithoutGlobStar)
+ // slow case. multiple pipe destinations.
+
+ if (!dest) {
+ // remove all.
+ var dests = state.pipes;
+ var len = state.pipesCount;
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+
+ for (var i = 0; i < len; i++)
+ dests[i].emit('unpipe', this);
+ return this;
+ }
- // the noGlobStar pattern exits the inGlobStar state
- this._process(noGlobStar, index, false)
+ // try to find the right one.
+ var i = indexOf(state.pipes, dest);
+ if (i === -1)
+ return this;
- var len = entries.length
- var isSym = this.symlinks[abs]
+ state.pipes.splice(i, 1);
+ state.pipesCount -= 1;
+ if (state.pipesCount === 1)
+ state.pipes = state.pipes[0];
- // If it's a symlink, and we're in a globstar, then stop
- if (isSym && inGlobStar)
- return
+ dest.emit('unpipe', this);
- for (var i = 0; i < len; i++) {
- var e = entries[i]
- if (e.charAt(0) === '.' && !this.dot)
- continue
+ return this;
+};
- // these two cases enter the inGlobStar state
- var instead = gspref.concat(entries[i], remainWithoutGlobStar)
- this._process(instead, index, true)
+// set up data events if they are asked for
+// Ensure readable listeners eventually get something
+Readable.prototype.on = function(ev, fn) {
+ var res = Stream.prototype.on.call(this, ev, fn);
- var below = gspref.concat(entries[i], remain)
- this._process(below, index, true)
+ // If listening to data, and it has not explicitly been paused,
+ // then call resume to start the flow of data on the next tick.
+ if (ev === 'data' && false !== this._readableState.flowing) {
+ this.resume();
}
-}
-
-GlobSync.prototype._processSimple = function (prefix, index) {
- // XXX review this. Shouldn't it be doing the mounting etc
- // before doing stat? kinda weird?
- var exists = this._stat(prefix)
- if (!this.matches[index])
- this.matches[index] = Object.create(null)
+ if (ev === 'readable' && this.readable) {
+ var state = this._readableState;
+ if (!state.readableListening) {
+ state.readableListening = true;
+ state.emittedReadable = false;
+ state.needReadable = true;
+ if (!state.reading) {
+ var self = this;
+ process.nextTick(function() {
+ debug('readable nexttick read 0');
+ self.read(0);
+ });
+ } else if (state.length) {
+ emitReadable(this, state);
+ }
+ }
+ }
- // If it doesn't exist, then just mark the lack of results
- if (!exists)
- return
+ return res;
+};
+Readable.prototype.addListener = Readable.prototype.on;
- if (prefix && isAbsolute(prefix) && !this.nomount) {
- var trail = /[\/\\]$/.test(prefix)
- if (prefix.charAt(0) === '/') {
- prefix = path.join(this.root, prefix)
- } else {
- prefix = path.resolve(this.root, prefix)
- if (trail)
- prefix += '/'
+// pause() and resume() are remnants of the legacy readable stream API
+// If the user uses them, then switch into old mode.
+Readable.prototype.resume = function() {
+ var state = this._readableState;
+ if (!state.flowing) {
+ debug('resume');
+ state.flowing = true;
+ if (!state.reading) {
+ debug('resume read 0');
+ this.read(0);
}
+ resume(this, state);
}
+ return this;
+};
- if (process.platform === 'win32')
- prefix = prefix.replace(/\\/g, '/')
-
- // Mark this as a match
- this.matches[index][prefix] = true
+function resume(stream, state) {
+ if (!state.resumeScheduled) {
+ state.resumeScheduled = true;
+ process.nextTick(function() {
+ resume_(stream, state);
+ });
+ }
}
-// Returns either 'DIR', 'FILE', or false
-GlobSync.prototype._stat = function (f) {
- var abs = this._makeAbs(f)
- var needDir = f.slice(-1) === '/'
+function resume_(stream, state) {
+ state.resumeScheduled = false;
+ stream.emit('resume');
+ flow(stream);
+ if (state.flowing && !state.reading)
+ stream.read(0);
+}
- if (f.length > this.maxLength)
- return false
+Readable.prototype.pause = function() {
+ debug('call pause flowing=%j', this._readableState.flowing);
+ if (false !== this._readableState.flowing) {
+ debug('pause');
+ this._readableState.flowing = false;
+ this.emit('pause');
+ }
+ return this;
+};
- if (!this.stat && ownProp(this.cache, abs)) {
- var c = this.cache[abs]
+function flow(stream) {
+ var state = stream._readableState;
+ debug('flow', state.flowing);
+ if (state.flowing) {
+ do {
+ var chunk = stream.read();
+ } while (null !== chunk && state.flowing);
+ }
+}
- if (Array.isArray(c))
- c = 'DIR'
+// wrap an old-style stream as the async data source.
+// This is *not* part of the readable stream interface.
+// It is an ugly unfortunate mess of history.
+Readable.prototype.wrap = function(stream) {
+ var state = this._readableState;
+ var paused = false;
- // It exists, but maybe not how we need it
- if (!needDir || c === 'DIR')
- return c
+ var self = this;
+ stream.on('end', function() {
+ debug('wrapped end');
+ if (state.decoder && !state.ended) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length)
+ self.push(chunk);
+ }
- if (needDir && c === 'FILE')
- return false
+ self.push(null);
+ });
- // otherwise we have to stat, because maybe c=true
- // if we know it exists, but not what it is.
- }
+ stream.on('data', function(chunk) {
+ debug('wrapped data');
+ if (state.decoder)
+ chunk = state.decoder.write(chunk);
+ if (!chunk || !state.objectMode && !chunk.length)
+ return;
- var exists
- var stat = this.statCache[abs]
- if (!stat) {
- var lstat
- try {
- lstat = fs.lstatSync(abs)
- } catch (er) {
- return false
+ var ret = self.push(chunk);
+ if (!ret) {
+ paused = true;
+ stream.pause();
}
+ });
- if (lstat.isSymbolicLink()) {
- try {
- stat = fs.statSync(abs)
- } catch (er) {
- stat = lstat
- }
- } else {
- stat = lstat
+ // proxy all the other methods.
+ // important when wrapping filters and duplexes.
+ for (var i in stream) {
+ if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
+ this[i] = function(method) { return function() {
+ return stream[method].apply(stream, arguments);
+ }}(i);
}
}
- this.statCache[abs] = stat
+ // proxy certain important events.
+ var events = ['error', 'close', 'destroy', 'pause', 'resume'];
+ forEach(events, function(ev) {
+ stream.on(ev, self.emit.bind(self, ev));
+ });
- var c = stat.isDirectory() ? 'DIR' : 'FILE'
- this.cache[abs] = this.cache[abs] || c
+ // when we try to consume some more bytes, simply unpause the
+ // underlying stream.
+ self._read = function(n) {
+ debug('wrapped _read', n);
+ if (paused) {
+ paused = false;
+ stream.resume();
+ }
+ };
- if (needDir && c !== 'DIR')
- return false
+ return self;
+};
- return c
-}
-GlobSync.prototype._mark = function (p) {
- return common.mark(this, p)
-}
-GlobSync.prototype._makeAbs = function (f) {
- return common.makeAbs(this, f)
-}
+// exposed for testing purposes only.
+Readable._fromList = fromList;
+
+// Pluck off n bytes from an array of buffers.
+// Length is the combined lengths of all the buffers in the list.
+function fromList(n, state) {
+ var list = state.buffer;
+ var length = state.length;
+ var stringMode = !!state.decoder;
+ var objectMode = !!state.objectMode;
+ var ret;
+
+ // nothing in the list, definitely empty.
+ if (list.length === 0)
+ return null;
+
+ if (length === 0)
+ ret = null;
+ else if (objectMode)
+ ret = list.shift();
+ else if (!n || n >= length) {
+ // read it all, truncate the array.
+ if (stringMode)
+ ret = list.join('');
+ else
+ ret = Buffer.concat(list, length);
+ list.length = 0;
+ } else {
+ // read just some of it.
+ if (n < list[0].length) {
+ // just take a part of the first list item.
+ // slice is the same for buffers and strings.
+ var buf = list[0];
+ ret = buf.slice(0, n);
+ list[0] = buf.slice(n);
+ } else if (n === list[0].length) {
+ // first list is a perfect match
+ ret = list.shift();
+ } else {
+ // complex case.
+ // we have enough to cover it, but it spans past the first buffer.
+ if (stringMode)
+ ret = '';
+ else
+ ret = new Buffer(n);
+
+ var c = 0;
+ for (var i = 0, l = list.length; i < l && c < n; i++) {
+ var buf = list[0];
+ var cpy = Math.min(n - c, buf.length);
-}).call(this,require('_process'))
-},{"./common.js":145,"./glob.js":146,"_process":64,"assert":1,"fs":4,"minimatch":156,"path":62,"path-is-absolute":152,"util":90}],154:[function(require,module,exports){
-'use strict';
+ if (stringMode)
+ ret += buf.slice(0, cpy);
+ else
+ buf.copy(ret, c, 0, cpy);
-var path = require('path');
-var findIndex = require('find-index');
+ if (cpy < buf.length)
+ list[0] = buf.slice(cpy);
+ else
+ list.shift();
-var flattenGlob = function(arr){
- var out = [];
- var flat = true;
- for(var i = 0; i < arr.length; i++) {
- if (typeof arr[i] !== 'string') {
- flat = false;
- break;
+ c += cpy;
+ }
}
- out.push(arr[i]);
}
- // last one is a file or specific dir
- // so we pop it off
- if (flat) {
- out.pop();
- }
- return out;
-};
+ return ret;
+}
-var flattenExpansion = function(set) {
- var first = set[0];
- var toCompare = set.slice(1);
+function endReadable(stream) {
+ var state = stream._readableState;
- // find index where the diff is
- var idx = findIndex(first, function(v, idx){
- if (typeof v !== 'string') {
- return true;
- }
+ // If we get here before consuming all the bytes, then that is a
+ // bug in node. Should never happen.
+ if (state.length > 0)
+ throw new Error('endReadable called on non-empty stream');
- var matched = toCompare.every(function(arr){
- return v === arr[idx];
+ if (!state.endEmitted) {
+ state.ended = true;
+ process.nextTick(function() {
+ // Check that we didn't get one last unshift.
+ if (!state.endEmitted && state.length === 0) {
+ state.endEmitted = true;
+ stream.readable = false;
+ stream.emit('end');
+ }
});
-
- return !matched;
- });
-
- return first.slice(0, idx);
-};
-
-var setToBase = function(set) {
- // normal something/*.js
- if (set.length <= 1) {
- return flattenGlob(set[0]);
}
- // has expansion
- return flattenExpansion(set);
-};
-
-module.exports = function(glob) {
- var set = glob.minimatch.set;
- var baseParts = setToBase(set);
- var basePath = path.normalize(baseParts.join(path.sep))+path.sep;
- return basePath;
-};
+}
-},{"find-index":155,"path":62}],155:[function(require,module,exports){
-function findIndex(array, predicate, self) {
- var len = array.length;
- var i;
- if (len === 0) return -1;
- if (typeof predicate !== 'function') {
- throw new TypeError(predicate + ' must be a function');
+function forEach (xs, f) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ f(xs[i], i);
}
+}
- if (self) {
- for (i = 0; i < len; i++) {
- if (predicate.call(self, array[i], i, array)) {
- return i;
- }
- }
- } else {
- for (i = 0; i < len; i++) {
- if (predicate(array[i], i, array)) {
- return i;
- }
- }
+function indexOf (xs, x) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ if (xs[i] === x) return i;
}
-
return -1;
}
-module.exports = findIndex
+}).call(this,require('_process'))
+},{"./_stream_duplex":97,"_process":107,"buffer":8,"core-util-is":15,"events":18,"inherits":47,"isarray":53,"stream":124,"string_decoder/":129,"util":5}],100:[function(require,module,exports){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
-},{}],156:[function(require,module,exports){
-module.exports = minimatch
-minimatch.Minimatch = Minimatch
-var path = { sep: '/' }
-try {
- path = require('path')
-} catch (er) {}
+// a transform stream is a readable/writable stream where you do
+// something with the data. Sometimes it's called a "filter",
+// but that's not a great name for it, since that implies a thing where
+// some bits pass through, and others are simply ignored. (That would
+// be a valid example of a transform, of course.)
+//
+// While the output is causally related to the input, it's not a
+// necessarily symmetric or synchronous transformation. For example,
+// a zlib stream might take multiple plain-text writes(), and then
+// emit a single compressed chunk some time in the future.
+//
+// Here's how this works:
+//
+// The Transform stream has all the aspects of the readable and writable
+// stream classes. When you write(chunk), that calls _write(chunk,cb)
+// internally, and returns false if there's a lot of pending writes
+// buffered up. When you call read(), that calls _read(n) until
+// there's enough pending readable data buffered up.
+//
+// In a transform stream, the written data is placed in a buffer. When
+// _read(n) is called, it transforms the queued up data, calling the
+// buffered _write cb's as it consumes chunks. If consuming a single
+// written chunk would result in multiple output chunks, then the first
+// outputted bit calls the readcb, and subsequent chunks just go into
+// the read buffer, and will cause it to emit 'readable' if necessary.
+//
+// This way, back-pressure is actually determined by the reading side,
+// since _read has to be called to start processing a new chunk. However,
+// a pathological inflate type of transform can cause excessive buffering
+// here. For example, imagine a stream where every byte of input is
+// interpreted as an integer from 0-255, and then results in that many
+// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
+// 1kb of data being output. In this case, you could write a very small
+// amount of input, and end up with a very large amount of output. In
+// such a pathological inflating mechanism, there'd be no way to tell
+// the system to stop doing the transform. A single 4MB write could
+// cause the system to run out of memory.
+//
+// However, even in such a pathological case, only a single written chunk
+// would be consumed, and then the rest would wait (un-transformed) until
+// the results of the previous transformed chunk were consumed.
-var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
-var expand = require('brace-expansion')
+module.exports = Transform;
-// any single thing other than /
-// don't need to escape / when using new RegExp()
-var qmark = '[^/]'
+var Duplex = require('./_stream_duplex');
-// * => any number of characters
-var star = qmark + '*?'
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
-// ** when dots are allowed. Anything goes, except .. and .
-// not (^ or / followed by one or two dots followed by $ or /),
-// followed by anything, any number of times.
-var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
+util.inherits(Transform, Duplex);
-// not a ^ or / followed by a dot,
-// followed by anything, any number of times.
-var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
-// characters that need to be escaped in RegExp.
-var reSpecials = charSet('().*{}+?[]^$\\!')
+function TransformState(options, stream) {
+ this.afterTransform = function(er, data) {
+ return afterTransform(stream, er, data);
+ };
-// "abc" -> { a:true, b:true, c:true }
-function charSet (s) {
- return s.split('').reduce(function (set, c) {
- set[c] = true
- return set
- }, {})
+ this.needTransform = false;
+ this.transforming = false;
+ this.writecb = null;
+ this.writechunk = null;
}
-// normalizes slashes.
-var slashSplit = /\/+/
+function afterTransform(stream, er, data) {
+ var ts = stream._transformState;
+ ts.transforming = false;
-minimatch.filter = filter
-function filter (pattern, options) {
- options = options || {}
- return function (p, i, list) {
- return minimatch(p, pattern, options)
- }
-}
+ var cb = ts.writecb;
-function ext (a, b) {
- a = a || {}
- b = b || {}
- var t = {}
- Object.keys(b).forEach(function (k) {
- t[k] = b[k]
- })
- Object.keys(a).forEach(function (k) {
- t[k] = a[k]
- })
- return t
-}
+ if (!cb)
+ return stream.emit('error', new Error('no writecb in Transform class'));
+
+ ts.writechunk = null;
+ ts.writecb = null;
-minimatch.defaults = function (def) {
- if (!def || !Object.keys(def).length) return minimatch
+ if (!util.isNullOrUndefined(data))
+ stream.push(data);
- var orig = minimatch
+ if (cb)
+ cb(er);
- var m = function minimatch (p, pattern, options) {
- return orig.minimatch(p, pattern, ext(def, options))
+ var rs = stream._readableState;
+ rs.reading = false;
+ if (rs.needReadable || rs.length < rs.highWaterMark) {
+ stream._read(rs.highWaterMark);
}
+}
- m.Minimatch = function Minimatch (pattern, options) {
- return new orig.Minimatch(pattern, ext(def, options))
- }
- return m
-}
+function Transform(options) {
+ if (!(this instanceof Transform))
+ return new Transform(options);
-Minimatch.defaults = function (def) {
- if (!def || !Object.keys(def).length) return Minimatch
- return minimatch.defaults(def).Minimatch
-}
+ Duplex.call(this, options);
-function minimatch (p, pattern, options) {
- if (typeof pattern !== 'string') {
- throw new TypeError('glob pattern string required')
- }
+ this._transformState = new TransformState(options, this);
- if (!options) options = {}
+ // when the writable side finishes, then flush out anything remaining.
+ var stream = this;
- // shortcut: comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- return false
- }
+ // start out asking for a readable event once data is transformed.
+ this._readableState.needReadable = true;
- // "" only matches ""
- if (pattern.trim() === '') return p === ''
+ // we have implemented the _read method, and done the other things
+ // that Readable wants before the first _read call, so unset the
+ // sync guard flag.
+ this._readableState.sync = false;
- return new Minimatch(pattern, options).match(p)
+ this.once('prefinish', function() {
+ if (util.isFunction(this._flush))
+ this._flush(function(er) {
+ done(stream, er);
+ });
+ else
+ done(stream);
+ });
}
-function Minimatch (pattern, options) {
- if (!(this instanceof Minimatch)) {
- return new Minimatch(pattern, options)
- }
+Transform.prototype.push = function(chunk, encoding) {
+ this._transformState.needTransform = false;
+ return Duplex.prototype.push.call(this, chunk, encoding);
+};
- if (typeof pattern !== 'string') {
- throw new TypeError('glob pattern string required')
+// This is the part where you do stuff!
+// override this function in implementation classes.
+// 'chunk' is an input chunk.
+//
+// Call `push(newChunk)` to pass along transformed output
+// to the readable side. You may call 'push' zero or more times.
+//
+// Call `cb(err)` when you are done with this chunk. If you pass
+// an error, then that'll put the hurt on the whole operation. If you
+// never call cb(), then you'll never get another chunk.
+Transform.prototype._transform = function(chunk, encoding, cb) {
+ throw new Error('not implemented');
+};
+
+Transform.prototype._write = function(chunk, encoding, cb) {
+ var ts = this._transformState;
+ ts.writecb = cb;
+ ts.writechunk = chunk;
+ ts.writeencoding = encoding;
+ if (!ts.transforming) {
+ var rs = this._readableState;
+ if (ts.needTransform ||
+ rs.needReadable ||
+ rs.length < rs.highWaterMark)
+ this._read(rs.highWaterMark);
}
+};
- if (!options) options = {}
- pattern = pattern.trim()
+// Doesn't matter what the args are here.
+// _transform does all the work.
+// That we got here means that the readable side wants more data.
+Transform.prototype._read = function(n) {
+ var ts = this._transformState;
- // windows support: need to use /, not \
- if (path.sep !== '/') {
- pattern = pattern.split(path.sep).join('/')
+ if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
+ ts.transforming = true;
+ this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
+ } else {
+ // mark that we need a transform, so that any data that comes in
+ // will get processed, now that we've asked for it.
+ ts.needTransform = true;
}
+};
- this.options = options
- this.set = []
- this.pattern = pattern
- this.regexp = null
- this.negate = false
- this.comment = false
- this.empty = false
-
- // make the set of regexps etc.
- this.make()
-}
-Minimatch.prototype.debug = function () {}
+function done(stream, er) {
+ if (er)
+ return stream.emit('error', er);
-Minimatch.prototype.make = make
-function make () {
- // don't do it more than once.
- if (this._made) return
+ // if there's nothing in the write buffer, then that means
+ // that nothing more will ever be provided
+ var ws = stream._writableState;
+ var ts = stream._transformState;
- var pattern = this.pattern
- var options = this.options
+ if (ws.length)
+ throw new Error('calling transform done when ws.length != 0');
- // empty patterns and comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- this.comment = true
- return
- }
- if (!pattern) {
- this.empty = true
- return
- }
+ if (ts.transforming)
+ throw new Error('calling transform done when still transforming');
- // step 1: figure out negation, etc.
- this.parseNegate()
+ return stream.push(null);
+}
- // step 2: expand braces
- var set = this.globSet = this.braceExpand()
+},{"./_stream_duplex":97,"core-util-is":15,"inherits":47}],101:[function(require,module,exports){
+(function (process){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
- if (options.debug) this.debug = console.error
+// A bit simpler than readable streams.
+// Implement an async ._write(chunk, cb), and it'll handle all
+// the drain event emission and buffering.
- this.debug(this.pattern, set)
+module.exports = Writable;
- // step 3: now we have a set, so turn each one into a series of path-portion
- // matching patterns.
- // These will be regexps, except in the case of "**", which is
- // set to the GLOBSTAR object for globstar behavior,
- // and will not contain any / characters
- set = this.globParts = set.map(function (s) {
- return s.split(slashSplit)
- })
+/**/
+var Buffer = require('buffer').Buffer;
+/**/
- this.debug(this.pattern, set)
+Writable.WritableState = WritableState;
- // glob --> regexps
- set = set.map(function (s, si, set) {
- return s.map(this.parse, this)
- }, this)
- this.debug(this.pattern, set)
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
- // filter out everything that didn't compile properly.
- set = set.filter(function (s) {
- return s.indexOf(false) === -1
- })
+var Stream = require('stream');
- this.debug(this.pattern, set)
+util.inherits(Writable, Stream);
- this.set = set
+function WriteReq(chunk, encoding, cb) {
+ this.chunk = chunk;
+ this.encoding = encoding;
+ this.callback = cb;
}
-Minimatch.prototype.parseNegate = parseNegate
-function parseNegate () {
- var pattern = this.pattern
- var negate = false
- var options = this.options
- var negateOffset = 0
+function WritableState(options, stream) {
+ var Duplex = require('./_stream_duplex');
- if (options.nonegate) return
+ options = options || {};
- for (var i = 0, l = pattern.length
- ; i < l && pattern.charAt(i) === '!'
- ; i++) {
- negate = !negate
- negateOffset++
- }
+ // the point at which write() starts returning false
+ // Note: 0 is a valid value, means that we always return false if
+ // the entire buffer is not flushed immediately on write()
+ var hwm = options.highWaterMark;
+ var defaultHwm = options.objectMode ? 16 : 16 * 1024;
+ this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
+
+ // object stream flag to indicate whether or not this stream
+ // contains buffers or objects.
+ this.objectMode = !!options.objectMode;
+
+ if (stream instanceof Duplex)
+ this.objectMode = this.objectMode || !!options.writableObjectMode;
+
+ // cast to ints.
+ this.highWaterMark = ~~this.highWaterMark;
+
+ this.needDrain = false;
+ // at the start of calling end()
+ this.ending = false;
+ // when end() has been called, and returned
+ this.ended = false;
+ // when 'finish' is emitted
+ this.finished = false;
- if (negateOffset) this.pattern = pattern.substr(negateOffset)
- this.negate = negate
-}
+ // should we decode strings into buffers before passing to _write?
+ // this is here so that some node-core streams can optimize string
+ // handling at a lower level.
+ var noDecode = options.decodeStrings === false;
+ this.decodeStrings = !noDecode;
-// Brace expansion:
-// a{b,c}d -> abd acd
-// a{b,}c -> abc ac
-// a{0..3}d -> a0d a1d a2d a3d
-// a{b,c{d,e}f}g -> abg acdfg acefg
-// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
-//
-// Invalid sets are not expanded.
-// a{2..}b -> a{2..}b
-// a{b}c -> a{b}c
-minimatch.braceExpand = function (pattern, options) {
- return braceExpand(pattern, options)
-}
+ // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+ this.defaultEncoding = options.defaultEncoding || 'utf8';
-Minimatch.prototype.braceExpand = braceExpand
+ // not an actual buffer we keep track of, but a measurement
+ // of how much we're waiting to get pushed to some underlying
+ // socket or file.
+ this.length = 0;
-function braceExpand (pattern, options) {
- if (!options) {
- if (this instanceof Minimatch) {
- options = this.options
- } else {
- options = {}
- }
- }
+ // a flag to see when we're in the middle of a write.
+ this.writing = false;
- pattern = typeof pattern === 'undefined'
- ? this.pattern : pattern
+ // when true all writes will be buffered until .uncork() call
+ this.corked = 0;
- if (typeof pattern === 'undefined') {
- throw new Error('undefined pattern')
- }
+ // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, because any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+ this.sync = true;
- if (options.nobrace ||
- !pattern.match(/\{.*\}/)) {
- // shortcut. no need to expand.
- return [pattern]
- }
+ // a flag to know if we're processing previously buffered items, which
+ // may call the _write() callback in the same tick, so that we don't
+ // end up in an overlapped onwrite situation.
+ this.bufferProcessing = false;
- return expand(pattern)
-}
+ // the callback that's passed to _write(chunk,cb)
+ this.onwrite = function(er) {
+ onwrite(stream, er);
+ };
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion. Otherwise, any series
-// of * is equivalent to a single *. Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-Minimatch.prototype.parse = parse
-var SUBPARSE = {}
-function parse (pattern, isSub) {
- var options = this.options
+ // the callback that the user supplies to write(chunk,encoding,cb)
+ this.writecb = null;
- // shortcuts
- if (!options.noglobstar && pattern === '**') return GLOBSTAR
- if (pattern === '') return ''
+ // the amount that is being written when _write is called.
+ this.writelen = 0;
- var re = ''
- var hasMagic = !!options.nocase
- var escaping = false
- // ? => one single character
- var patternListStack = []
- var negativeLists = []
- var plType
- var stateChar
- var inClass = false
- var reClassStart = -1
- var classStart = -1
- // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- var patternStart = pattern.charAt(0) === '.' ? '' // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
- : '(?!\\.)'
- var self = this
+ this.buffer = [];
- function clearStateChar () {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case '*':
- re += star
- hasMagic = true
- break
- case '?':
- re += qmark
- hasMagic = true
- break
- default:
- re += '\\' + stateChar
- break
- }
- self.debug('clearStateChar %j %j', stateChar, re)
- stateChar = false
- }
- }
+ // number of pending user-supplied write callbacks
+ // this must be 0 before 'finish' can be emitted
+ this.pendingcb = 0;
- for (var i = 0, len = pattern.length, c
- ; (i < len) && (c = pattern.charAt(i))
- ; i++) {
- this.debug('%s\t%s %s %j', pattern, i, re, c)
+ // emit prefinish if the only thing we're waiting for is _write cbs
+ // This is relevant for synchronous Transform streams
+ this.prefinished = false;
- // skip over any that are escaped.
- if (escaping && reSpecials[c]) {
- re += '\\' + c
- escaping = false
- continue
- }
+ // True if the error was already emitted and should not be thrown again
+ this.errorEmitted = false;
+}
- switch (c) {
- case '/':
- // completely not allowed, even escaped.
- // Should already be path-split by now.
- return false
+function Writable(options) {
+ var Duplex = require('./_stream_duplex');
- case '\\':
- clearStateChar()
- escaping = true
- continue
+ // Writable ctor is applied to Duplexes, though they're not
+ // instanceof Writable, they're instanceof Readable.
+ if (!(this instanceof Writable) && !(this instanceof Duplex))
+ return new Writable(options);
- // the various stateChar values
- // for the "extglob" stuff.
- case '?':
- case '*':
- case '+':
- case '@':
- case '!':
- this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
+ this._writableState = new WritableState(options, this);
- // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- this.debug(' in class')
- if (c === '!' && i === classStart + 1) c = '^'
- re += c
- continue
- }
+ // legacy.
+ this.writable = true;
- // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- self.debug('call clearStateChar %j', stateChar)
- clearStateChar()
- stateChar = c
- // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar()
- continue
+ Stream.call(this);
+}
- case '(':
- if (inClass) {
- re += '('
- continue
- }
+// Otherwise people can pipe Writable streams, which is just wrong.
+Writable.prototype.pipe = function() {
+ this.emit('error', new Error('Cannot pipe. Not readable.'));
+};
- if (!stateChar) {
- re += '\\('
- continue
- }
- plType = stateChar
- patternListStack.push({
- type: plType,
- start: i - 1,
- reStart: re.length
- })
- // negation is (?:(?!js)[^/]*)
- re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
- this.debug('plType %j %j', stateChar, re)
- stateChar = false
- continue
+function writeAfterEnd(stream, state, cb) {
+ var er = new Error('write after end');
+ // TODO: defer error events consistently everywhere, not just the cb
+ stream.emit('error', er);
+ process.nextTick(function() {
+ cb(er);
+ });
+}
- case ')':
- if (inClass || !patternListStack.length) {
- re += '\\)'
- continue
- }
+// If we get something that is not a buffer, string, null, or undefined,
+// and we're not in objectMode, then that's an error.
+// Otherwise stream chunks are all considered to be of length=1, and the
+// watermarks determine how many objects to keep in the buffer, rather than
+// how many bytes or characters.
+function validChunk(stream, state, chunk, cb) {
+ var valid = true;
+ if (!util.isBuffer(chunk) &&
+ !util.isString(chunk) &&
+ !util.isNullOrUndefined(chunk) &&
+ !state.objectMode) {
+ var er = new TypeError('Invalid non-string/buffer chunk');
+ stream.emit('error', er);
+ process.nextTick(function() {
+ cb(er);
+ });
+ valid = false;
+ }
+ return valid;
+}
+
+Writable.prototype.write = function(chunk, encoding, cb) {
+ var state = this._writableState;
+ var ret = false;
- clearStateChar()
- hasMagic = true
- re += ')'
- var pl = patternListStack.pop()
- plType = pl.type
- // negation is (?:(?!js)[^/]*)
- // The others are (?:)
- switch (plType) {
- case '!':
- negativeLists.push(pl)
- re += ')[^/]*?)'
- pl.reEnd = re.length
- break
- case '?':
- case '+':
- case '*':
- re += plType
- break
- case '@': break // the default anyway
- }
- continue
+ if (util.isFunction(encoding)) {
+ cb = encoding;
+ encoding = null;
+ }
- case '|':
- if (inClass || !patternListStack.length || escaping) {
- re += '\\|'
- escaping = false
- continue
- }
+ if (util.isBuffer(chunk))
+ encoding = 'buffer';
+ else if (!encoding)
+ encoding = state.defaultEncoding;
- clearStateChar()
- re += '|'
- continue
+ if (!util.isFunction(cb))
+ cb = function() {};
- // these are mostly the same in regexp and glob
- case '[':
- // swallow any state-tracking char before the [
- clearStateChar()
+ if (state.ended)
+ writeAfterEnd(this, state, cb);
+ else if (validChunk(this, state, chunk, cb)) {
+ state.pendingcb++;
+ ret = writeOrBuffer(this, state, chunk, encoding, cb);
+ }
- if (inClass) {
- re += '\\' + c
- continue
- }
+ return ret;
+};
- inClass = true
- classStart = i
- reClassStart = re.length
- re += c
- continue
+Writable.prototype.cork = function() {
+ var state = this._writableState;
- case ']':
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += '\\' + c
- escaping = false
- continue
- }
+ state.corked++;
+};
- // handle the case where we left a class open.
- // "[z-a]" is valid, equivalent to "\[z-a\]"
- if (inClass) {
- // split where the last [ was, make sure we don't have
- // an invalid re. if so, re-walk the contents of the
- // would-be class to re-translate any characters that
- // were passed through as-is
- // TODO: It would probably be faster to determine this
- // without a try/catch and a new RegExp, but it's tricky
- // to do safely. For now, this is safe and works.
- var cs = pattern.substring(classStart + 1, i)
- try {
- RegExp('[' + cs + ']')
- } catch (er) {
- // not a valid class!
- var sp = this.parse(cs, SUBPARSE)
- re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
- hasMagic = hasMagic || sp[1]
- inClass = false
- continue
- }
- }
+Writable.prototype.uncork = function() {
+ var state = this._writableState;
- // finish up the class.
- hasMagic = true
- inClass = false
- re += c
- continue
+ if (state.corked) {
+ state.corked--;
- default:
- // swallow any state char that wasn't consumed
- clearStateChar()
+ if (!state.writing &&
+ !state.corked &&
+ !state.finished &&
+ !state.bufferProcessing &&
+ state.buffer.length)
+ clearBuffer(this, state);
+ }
+};
- if (escaping) {
- // no need
- escaping = false
- } else if (reSpecials[c]
- && !(c === '^' && inClass)) {
- re += '\\'
- }
+function decodeChunk(state, chunk, encoding) {
+ if (!state.objectMode &&
+ state.decodeStrings !== false &&
+ util.isString(chunk)) {
+ chunk = new Buffer(chunk, encoding);
+ }
+ return chunk;
+}
- re += c
+// if we're already writing something, then just put this
+// in the queue, and wait our turn. Otherwise, call _write
+// If we return false, then we need a drain event, so set that flag.
+function writeOrBuffer(stream, state, chunk, encoding, cb) {
+ chunk = decodeChunk(state, chunk, encoding);
+ if (util.isBuffer(chunk))
+ encoding = 'buffer';
+ var len = state.objectMode ? 1 : chunk.length;
- } // switch
- } // for
+ state.length += len;
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- cs = pattern.substr(classStart + 1)
- sp = this.parse(cs, SUBPARSE)
- re = re.substr(0, reClassStart) + '\\[' + sp[0]
- hasMagic = hasMagic || sp[1]
- }
+ var ret = state.length < state.highWaterMark;
+ // we must ensure that previous needDrain will not be reset to false.
+ if (!ret)
+ state.needDrain = true;
- // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
- var tail = re.slice(pl.reStart + 3)
- // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = '\\'
- }
+ if (state.writing || state.corked)
+ state.buffer.push(new WriteReq(chunk, encoding, cb));
+ else
+ doWrite(stream, state, false, len, chunk, encoding, cb);
- // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + '|'
- })
+ return ret;
+}
- this.debug('tail=%j\n %s', tail, tail)
- var t = pl.type === '*' ? star
- : pl.type === '?' ? qmark
- : '\\' + pl.type
+function doWrite(stream, state, writev, len, chunk, encoding, cb) {
+ state.writelen = len;
+ state.writecb = cb;
+ state.writing = true;
+ state.sync = true;
+ if (writev)
+ stream._writev(chunk, state.onwrite);
+ else
+ stream._write(chunk, encoding, state.onwrite);
+ state.sync = false;
+}
- hasMagic = true
- re = re.slice(0, pl.reStart) + t + '\\(' + tail
+function onwriteError(stream, state, sync, er, cb) {
+ if (sync)
+ process.nextTick(function() {
+ state.pendingcb--;
+ cb(er);
+ });
+ else {
+ state.pendingcb--;
+ cb(er);
}
- // handle trailing things that only matter at the very end.
- clearStateChar()
- if (escaping) {
- // trailing \\
- re += '\\\\'
- }
+ stream._writableState.errorEmitted = true;
+ stream.emit('error', er);
+}
- // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- var addPatternStart = false
- switch (re.charAt(0)) {
- case '.':
- case '[':
- case '(': addPatternStart = true
- }
+function onwriteStateUpdate(state) {
+ state.writing = false;
+ state.writecb = null;
+ state.length -= state.writelen;
+ state.writelen = 0;
+}
- // Hack to work around lack of negative lookbehind in JS
- // A pattern like: *.!(x).!(y|z) needs to ensure that a name
- // like 'a.xyz.yz' doesn't match. So, the first negative
- // lookahead, has to look ALL the way ahead, to the end of
- // the pattern.
- for (var n = negativeLists.length - 1; n > -1; n--) {
- var nl = negativeLists[n]
+function onwrite(stream, er) {
+ var state = stream._writableState;
+ var sync = state.sync;
+ var cb = state.writecb;
- var nlBefore = re.slice(0, nl.reStart)
- var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
- var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
- var nlAfter = re.slice(nl.reEnd)
+ onwriteStateUpdate(state);
- nlLast += nlAfter
+ if (er)
+ onwriteError(stream, state, sync, er, cb);
+ else {
+ // Check if we're actually ready to finish, but don't emit yet
+ var finished = needFinish(stream, state);
- // Handle nested stuff like *(*.js|!(*.json)), where open parens
- // mean that we should *not* include the ) in the bit that is considered
- // "after" the negated section.
- var openParensBefore = nlBefore.split('(').length - 1
- var cleanAfter = nlAfter
- for (i = 0; i < openParensBefore; i++) {
- cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
+ if (!finished &&
+ !state.corked &&
+ !state.bufferProcessing &&
+ state.buffer.length) {
+ clearBuffer(stream, state);
}
- nlAfter = cleanAfter
- var dollar = ''
- if (nlAfter === '' && isSub !== SUBPARSE) {
- dollar = '$'
+ if (sync) {
+ process.nextTick(function() {
+ afterWrite(stream, state, finished, cb);
+ });
+ } else {
+ afterWrite(stream, state, finished, cb);
}
- var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
- re = newRe
- }
-
- // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== '' && hasMagic) {
- re = '(?=.)' + re
}
+}
- if (addPatternStart) {
- re = patternStart + re
- }
+function afterWrite(stream, state, finished, cb) {
+ if (!finished)
+ onwriteDrain(stream, state);
+ state.pendingcb--;
+ cb();
+ finishMaybe(stream, state);
+}
- // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic]
+// Must force callback to be called on nextTick, so that we don't
+// emit 'drain' before the write() consumer gets the 'false' return
+// value, and has a chance to attach a 'drain' listener.
+function onwriteDrain(stream, state) {
+ if (state.length === 0 && state.needDrain) {
+ state.needDrain = false;
+ stream.emit('drain');
}
+}
- // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern)
- }
- var flags = options.nocase ? 'i' : ''
- var regExp = new RegExp('^' + re + '$', flags)
+// if there's something in the buffer waiting, then process it
+function clearBuffer(stream, state) {
+ state.bufferProcessing = true;
- regExp._glob = pattern
- regExp._src = re
+ if (stream._writev && state.buffer.length > 1) {
+ // Fast case, write everything using _writev()
+ var cbs = [];
+ for (var c = 0; c < state.buffer.length; c++)
+ cbs.push(state.buffer[c].callback);
- return regExp
-}
+ // count the one we are adding, as well.
+ // TODO(isaacs) clean this up
+ state.pendingcb++;
+ doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
+ for (var i = 0; i < cbs.length; i++) {
+ state.pendingcb--;
+ cbs[i](err);
+ }
+ });
-minimatch.makeRe = function (pattern, options) {
- return new Minimatch(pattern, options || {}).makeRe()
-}
+ // Clear buffer
+ state.buffer = [];
+ } else {
+ // Slow case, write chunks one-by-one
+ for (var c = 0; c < state.buffer.length; c++) {
+ var entry = state.buffer[c];
+ var chunk = entry.chunk;
+ var encoding = entry.encoding;
+ var cb = entry.callback;
+ var len = state.objectMode ? 1 : chunk.length;
-Minimatch.prototype.makeRe = makeRe
-function makeRe () {
- if (this.regexp || this.regexp === false) return this.regexp
+ doWrite(stream, state, false, len, chunk, encoding, cb);
- // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- var set = this.set
+ // if we didn't call the onwrite immediately, then
+ // it means that we need to wait until it does.
+ // also, that means that the chunk and cb are currently
+ // being processed, so move the buffer counter past them.
+ if (state.writing) {
+ c++;
+ break;
+ }
+ }
- if (!set.length) {
- this.regexp = false
- return this.regexp
+ if (c < state.buffer.length)
+ state.buffer = state.buffer.slice(c);
+ else
+ state.buffer.length = 0;
}
- var options = this.options
- var twoStar = options.noglobstar ? star
- : options.dot ? twoStarDot
- : twoStarNoDot
- var flags = options.nocase ? 'i' : ''
+ state.bufferProcessing = false;
+}
- var re = set.map(function (pattern) {
- return pattern.map(function (p) {
- return (p === GLOBSTAR) ? twoStar
- : (typeof p === 'string') ? regExpEscape(p)
- : p._src
- }).join('\\\/')
- }).join('|')
+Writable.prototype._write = function(chunk, encoding, cb) {
+ cb(new Error('not implemented'));
- // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = '^(?:' + re + ')$'
+};
- // can match anything, as long as it's not this.
- if (this.negate) re = '^(?!' + re + ').*$'
+Writable.prototype._writev = null;
- try {
- this.regexp = new RegExp(re, flags)
- } catch (ex) {
- this.regexp = false
+Writable.prototype.end = function(chunk, encoding, cb) {
+ var state = this._writableState;
+
+ if (util.isFunction(chunk)) {
+ cb = chunk;
+ chunk = null;
+ encoding = null;
+ } else if (util.isFunction(encoding)) {
+ cb = encoding;
+ encoding = null;
}
- return this.regexp
-}
-minimatch.match = function (list, pattern, options) {
- options = options || {}
- var mm = new Minimatch(pattern, options)
- list = list.filter(function (f) {
- return mm.match(f)
- })
- if (mm.options.nonull && !list.length) {
- list.push(pattern)
+ if (!util.isNullOrUndefined(chunk))
+ this.write(chunk, encoding);
+
+ // .end() fully uncorks
+ if (state.corked) {
+ state.corked = 1;
+ this.uncork();
}
- return list
-}
-Minimatch.prototype.match = match
-function match (f, partial) {
- this.debug('match', f, this.pattern)
- // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false
- if (this.empty) return f === ''
+ // ignore unnecessary end() calls.
+ if (!state.ending && !state.finished)
+ endWritable(this, state, cb);
+};
- if (f === '/' && partial) return true
- var options = this.options
+function needFinish(stream, state) {
+ return (state.ending &&
+ state.length === 0 &&
+ !state.finished &&
+ !state.writing);
+}
- // windows: need to use /, not \
- if (path.sep !== '/') {
- f = f.split(path.sep).join('/')
+function prefinish(stream, state) {
+ if (!state.prefinished) {
+ state.prefinished = true;
+ stream.emit('prefinish');
}
+}
- // treat the test path as a set of pathparts.
- f = f.split(slashSplit)
- this.debug(this.pattern, 'split', f)
+function finishMaybe(stream, state) {
+ var need = needFinish(stream, state);
+ if (need) {
+ if (state.pendingcb === 0) {
+ prefinish(stream, state);
+ state.finished = true;
+ stream.emit('finish');
+ } else
+ prefinish(stream, state);
+ }
+ return need;
+}
- // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
+function endWritable(stream, state, cb) {
+ state.ending = true;
+ finishMaybe(stream, state);
+ if (cb) {
+ if (state.finished)
+ process.nextTick(cb);
+ else
+ stream.once('finish', cb);
+ }
+ state.ended = true;
+}
- var set = this.set
- this.debug(this.pattern, 'set', set)
+}).call(this,require('_process'))
+},{"./_stream_duplex":97,"_process":107,"buffer":8,"core-util-is":15,"inherits":47,"stream":124}],102:[function(require,module,exports){
+exports = module.exports = require('./lib/_stream_readable.js');
+exports.Stream = require('stream');
+exports.Readable = exports;
+exports.Writable = require('./lib/_stream_writable.js');
+exports.Duplex = require('./lib/_stream_duplex.js');
+exports.Transform = require('./lib/_stream_transform.js');
+exports.PassThrough = require('./lib/_stream_passthrough.js');
- // Find the basename of the path by looking for the last non-empty segment
- var filename
- var i
- for (i = f.length - 1; i >= 0; i--) {
- filename = f[i]
- if (filename) break
- }
+},{"./lib/_stream_duplex.js":97,"./lib/_stream_passthrough.js":98,"./lib/_stream_readable.js":99,"./lib/_stream_transform.js":100,"./lib/_stream_writable.js":101,"stream":124}],103:[function(require,module,exports){
+exports.endianness = function () { return 'LE' };
- for (i = 0; i < set.length; i++) {
- var pattern = set[i]
- var file = f
- if (options.matchBase && pattern.length === 1) {
- file = [filename]
- }
- var hit = this.matchOne(file, pattern, partial)
- if (hit) {
- if (options.flipNegate) return true
- return !this.negate
+exports.hostname = function () {
+ if (typeof location !== 'undefined') {
+ return location.hostname
}
- }
+ else return '';
+};
- // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false
- return this.negate
-}
+exports.loadavg = function () { return [] };
-// set partial to true to test if, for example,
-// "/a/b" matches the start of "/*/b/*/d"
-// Partial means, if you run out of file before you run
-// out of pattern, then that's fine, as long as all
-// the parts match.
-Minimatch.prototype.matchOne = function (file, pattern, partial) {
- var options = this.options
+exports.uptime = function () { return 0 };
- this.debug('matchOne',
- { 'this': this, file: file, pattern: pattern })
+exports.freemem = function () {
+ return Number.MAX_VALUE;
+};
- this.debug('matchOne', file.length, pattern.length)
+exports.totalmem = function () {
+ return Number.MAX_VALUE;
+};
- for (var fi = 0,
- pi = 0,
- fl = file.length,
- pl = pattern.length
- ; (fi < fl) && (pi < pl)
- ; fi++, pi++) {
- this.debug('matchOne loop')
- var p = pattern[pi]
- var f = file[fi]
+exports.cpus = function () { return [] };
- this.debug(pattern, p, f)
+exports.type = function () { return 'Browser' };
- // should be impossible.
- // some invalid regexp stuff in the set.
- if (p === false) return false
+exports.release = function () {
+ if (typeof navigator !== 'undefined') {
+ return navigator.appVersion;
+ }
+ return '';
+};
- if (p === GLOBSTAR) {
- this.debug('GLOBSTAR', [pattern, p, f])
+exports.networkInterfaces
+= exports.getNetworkInterfaces
+= function () { return {} };
- // "**"
- // a/**/b/**/c would match the following:
- // a/b/x/y/z/c
- // a/x/y/z/b/c
- // a/b/x/b/x/c
- // a/b/c
- // To do this, take the rest of the pattern after
- // the **, and see if it would match the file remainder.
- // If so, return success.
- // If not, the ** "swallows" a segment, and try again.
- // This is recursively awful.
- //
- // a/**/b/**/c matching a/b/x/y/z/c
- // - a matches a
- // - doublestar
- // - matchOne(b/x/y/z/c, b/**/c)
- // - b matches b
- // - doublestar
- // - matchOne(x/y/z/c, c) -> no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi
- var pr = pi + 1
- if (pr === pl) {
- this.debug('** at the end')
- // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === '.' || file[fi] === '..' ||
- (!options.dot && file[fi].charAt(0) === '.')) return false
- }
- return true
- }
+exports.arch = function () { return 'javascript' };
- // ok, let's see if we can swallow whatever we can.
- while (fr < fl) {
- var swallowee = file[fr]
+exports.platform = function () { return 'browser' };
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
+exports.tmpdir = exports.tmpDir = function () {
+ return '/tmp';
+};
- // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- this.debug('globstar found match!', fr, fl, swallowee)
- // found a match.
- return true
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === '.' || swallowee === '..' ||
- (!options.dot && swallowee.charAt(0) === '.')) {
- this.debug('dot detected!', file, fr, pattern, pr)
- break
- }
+exports.EOL = '\n';
- // ** swallows a segment, and continue.
- this.debug('globstar swallow a segment, and continue')
- fr++
- }
- }
+},{}],104:[function(require,module,exports){
+(function (process){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
- // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- if (partial) {
- // ran out of file
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
- if (fr === fl) return true
- }
- return false
+// resolves . and .. elements in a path array with directory names there
+// must be no slashes, empty elements, or device names (c:\) in the array
+// (so also no leading and trailing slashes - it does not distinguish
+// relative and absolute paths)
+function normalizeArray(parts, allowAboveRoot) {
+ // if the path tries to go above the root, `up` ends up > 0
+ var up = 0;
+ for (var i = parts.length - 1; i >= 0; i--) {
+ var last = parts[i];
+ if (last === '.') {
+ parts.splice(i, 1);
+ } else if (last === '..') {
+ parts.splice(i, 1);
+ up++;
+ } else if (up) {
+ parts.splice(i, 1);
+ up--;
}
+ }
- // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit
- if (typeof p === 'string') {
- if (options.nocase) {
- hit = f.toLowerCase() === p.toLowerCase()
- } else {
- hit = f === p
- }
- this.debug('string match', p, f, hit)
- } else {
- hit = f.match(p)
- this.debug('pattern match', p, f, hit)
+ // if the path is allowed to go above the root, restore leading ..s
+ if (allowAboveRoot) {
+ for (; up--; up) {
+ parts.unshift('..');
}
-
- if (!hit) return false
}
- // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
+ return parts;
+}
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial
- } else if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')
- return emptyFileEnd
- }
+// Split a filename into [root, dir, basename, ext], unix version
+// 'root' is just a slash, or nothing.
+var splitPathRe =
+ /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
+var splitPath = function(filename) {
+ return splitPathRe.exec(filename).slice(1);
+};
- // should be unreachable.
- throw new Error('wtf?')
-}
+// path.resolve([from ...], to)
+// posix version
+exports.resolve = function() {
+ var resolvedPath = '',
+ resolvedAbsolute = false;
-// replace stuff like \* with *
-function globUnescape (s) {
- return s.replace(/\\(.)/g, '$1')
-}
+ for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
+ var path = (i >= 0) ? arguments[i] : process.cwd();
+
+ // Skip empty and invalid entries
+ if (typeof path !== 'string') {
+ throw new TypeError('Arguments to path.resolve must be strings');
+ } else if (!path) {
+ continue;
+ }
-function regExpEscape (s) {
- return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
-}
+ resolvedPath = path + '/' + resolvedPath;
+ resolvedAbsolute = path.charAt(0) === '/';
+ }
-},{"brace-expansion":157,"path":62}],157:[function(require,module,exports){
-var concatMap = require('concat-map');
-var balanced = require('balanced-match');
+ // At this point the path should be resolved to a full absolute path, but
+ // handle relative paths to be safe (might happen when process.cwd() fails)
-module.exports = expandTop;
+ // Normalize the path
+ resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
+ return !!p;
+ }), !resolvedAbsolute).join('/');
-var escSlash = '\0SLASH'+Math.random()+'\0';
-var escOpen = '\0OPEN'+Math.random()+'\0';
-var escClose = '\0CLOSE'+Math.random()+'\0';
-var escComma = '\0COMMA'+Math.random()+'\0';
-var escPeriod = '\0PERIOD'+Math.random()+'\0';
+ return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
+};
-function numeric(str) {
- return parseInt(str, 10) == str
- ? parseInt(str, 10)
- : str.charCodeAt(0);
-}
+// path.normalize(path)
+// posix version
+exports.normalize = function(path) {
+ var isAbsolute = exports.isAbsolute(path),
+ trailingSlash = substr(path, -1) === '/';
-function escapeBraces(str) {
- return str.split('\\\\').join(escSlash)
- .split('\\{').join(escOpen)
- .split('\\}').join(escClose)
- .split('\\,').join(escComma)
- .split('\\.').join(escPeriod);
-}
+ // Normalize the path
+ path = normalizeArray(filter(path.split('/'), function(p) {
+ return !!p;
+ }), !isAbsolute).join('/');
-function unescapeBraces(str) {
- return str.split(escSlash).join('\\')
- .split(escOpen).join('{')
- .split(escClose).join('}')
- .split(escComma).join(',')
- .split(escPeriod).join('.');
-}
+ if (!path && !isAbsolute) {
+ path = '.';
+ }
+ if (path && trailingSlash) {
+ path += '/';
+ }
+ return (isAbsolute ? '/' : '') + path;
+};
-// Basically just str.split(","), but handling cases
-// where we have nested braced sections, which should be
-// treated as individual members, like {a,{b,c},d}
-function parseCommaParts(str) {
- if (!str)
- return [''];
+// posix version
+exports.isAbsolute = function(path) {
+ return path.charAt(0) === '/';
+};
- var parts = [];
- var m = balanced('{', '}', str);
+// posix version
+exports.join = function() {
+ var paths = Array.prototype.slice.call(arguments, 0);
+ return exports.normalize(filter(paths, function(p, index) {
+ if (typeof p !== 'string') {
+ throw new TypeError('Arguments to path.join must be strings');
+ }
+ return p;
+ }).join('/'));
+};
- if (!m)
- return str.split(',');
- var pre = m.pre;
- var body = m.body;
- var post = m.post;
- var p = pre.split(',');
+// path.relative(from, to)
+// posix version
+exports.relative = function(from, to) {
+ from = exports.resolve(from).substr(1);
+ to = exports.resolve(to).substr(1);
- p[p.length-1] += '{' + body + '}';
- var postParts = parseCommaParts(post);
- if (post.length) {
- p[p.length-1] += postParts.shift();
- p.push.apply(p, postParts);
- }
+ function trim(arr) {
+ var start = 0;
+ for (; start < arr.length; start++) {
+ if (arr[start] !== '') break;
+ }
- parts.push.apply(parts, p);
+ var end = arr.length - 1;
+ for (; end >= 0; end--) {
+ if (arr[end] !== '') break;
+ }
- return parts;
-}
+ if (start > end) return [];
+ return arr.slice(start, end - start + 1);
+ }
-function expandTop(str) {
- if (!str)
- return [];
+ var fromParts = trim(from.split('/'));
+ var toParts = trim(to.split('/'));
- return expand(escapeBraces(str), true).map(unescapeBraces);
-}
+ var length = Math.min(fromParts.length, toParts.length);
+ var samePartsLength = length;
+ for (var i = 0; i < length; i++) {
+ if (fromParts[i] !== toParts[i]) {
+ samePartsLength = i;
+ break;
+ }
+ }
-function identity(e) {
- return e;
-}
+ var outputParts = [];
+ for (var i = samePartsLength; i < fromParts.length; i++) {
+ outputParts.push('..');
+ }
-function embrace(str) {
- return '{' + str + '}';
-}
-function isPadded(el) {
- return /^-?0\d/.test(el);
-}
+ outputParts = outputParts.concat(toParts.slice(samePartsLength));
-function lte(i, y) {
- return i <= y;
-}
-function gte(i, y) {
- return i >= y;
-}
+ return outputParts.join('/');
+};
-function expand(str, isTop) {
- var expansions = [];
+exports.sep = '/';
+exports.delimiter = ':';
- var m = balanced('{', '}', str);
- if (!m || /\$$/.test(m.pre)) return [str];
+exports.dirname = function(path) {
+ var result = splitPath(path),
+ root = result[0],
+ dir = result[1];
- var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
- var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
- var isSequence = isNumericSequence || isAlphaSequence;
- var isOptions = /^(.*,)+(.+)?$/.test(m.body);
- if (!isSequence && !isOptions) {
- // {a},b}
- if (m.post.match(/,.*}/)) {
- str = m.pre + '{' + m.body + escClose + m.post;
- return expand(str);
- }
- return [str];
+ if (!root && !dir) {
+ // No dirname whatsoever
+ return '.';
}
- var n;
- if (isSequence) {
- n = m.body.split(/\.\./);
- } else {
- n = parseCommaParts(m.body);
- if (n.length === 1) {
- // x{{a,b}}y ==> x{a}y x{b}y
- n = expand(n[0], false).map(embrace);
- if (n.length === 1) {
- var post = m.post.length
- ? expand(m.post, false)
- : [''];
- return post.map(function(p) {
- return m.pre + n[0] + p;
- });
- }
- }
+ if (dir) {
+ // It has a dirname, strip trailing slash
+ dir = dir.substr(0, dir.length - 1);
}
- // at this point, n is the parts, and we know it's not a comma set
- // with a single entry.
+ return root + dir;
+};
- // no need to expand pre, since it is guaranteed to be free of brace-sets
- var pre = m.pre;
- var post = m.post.length
- ? expand(m.post, false)
- : [''];
- var N;
+exports.basename = function(path, ext) {
+ var f = splitPath(path)[2];
+ // TODO: make this comparison case-insensitive on windows?
+ if (ext && f.substr(-1 * ext.length) === ext) {
+ f = f.substr(0, f.length - ext.length);
+ }
+ return f;
+};
- if (isSequence) {
- var x = numeric(n[0]);
- var y = numeric(n[1]);
- var width = Math.max(n[0].length, n[1].length)
- var incr = n.length == 3
- ? Math.abs(numeric(n[2]))
- : 1;
- var test = lte;
- var reverse = y < x;
- if (reverse) {
- incr *= -1;
- test = gte;
- }
- var pad = n.some(isPadded);
- N = [];
+exports.extname = function(path) {
+ return splitPath(path)[3];
+};
- for (var i = x; test(i, y); i += incr) {
- var c;
- if (isAlphaSequence) {
- c = String.fromCharCode(i);
- if (c === '\\')
- c = '';
- } else {
- c = String(i);
- if (pad) {
- var need = width - c.length;
- if (need > 0) {
- var z = new Array(need + 1).join('0');
- if (i < 0)
- c = '-' + z + c.slice(1);
- else
- c = z + c;
- }
- }
- }
- N.push(c);
+function filter (xs, f) {
+ if (xs.filter) return xs.filter(f);
+ var res = [];
+ for (var i = 0; i < xs.length; i++) {
+ if (f(xs[i], i, xs)) res.push(xs[i]);
}
- } else {
- N = concatMap(n, function(el) { return expand(el, false) });
- }
+ return res;
+}
- for (var j = 0; j < N.length; j++) {
- for (var k = 0; k < post.length; k++) {
- var expansion = pre + N[j] + post[k];
- if (!isTop || isSequence || expansion)
- expansions.push(expansion);
+// String.prototype.substr - negative index don't work in IE8
+var substr = 'ab'.substr(-1) === 'b'
+ ? function (str, start, len) { return str.substr(start, len) }
+ : function (str, start, len) {
+ if (start < 0) start = str.length + start;
+ return str.substr(start, len);
}
- }
+;
- return expansions;
+}).call(this,require('_process'))
+},{"_process":107}],105:[function(require,module,exports){
+(function (process){
+'use strict';
+
+function posix(path) {
+ return path.charAt(0) === '/';
+};
+
+function win32(path) {
+ // https://github.com/joyent/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
+ var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
+ var result = splitDeviceRe.exec(path);
+ var device = result[1] || '';
+ var isUnc = !!device && device.charAt(1) !== ':';
+
+ // UNC paths are always absolute
+ return !!result[2] || isUnc;
+};
+
+module.exports = process.platform === 'win32' ? win32 : posix;
+module.exports.posix = posix;
+module.exports.win32 = win32;
+
+}).call(this,require('_process'))
+},{"_process":107}],106:[function(require,module,exports){
+(function (process){
+'use strict';
+module.exports = nextTick;
+
+function nextTick(fn) {
+ var args = new Array(arguments.length - 1);
+ var i = 0;
+ while (i < args.length) {
+ args[i++] = arguments[i];
+ }
+ process.nextTick(function afterTick() {
+ fn.apply(null, args);
+ });
}
+}).call(this,require('_process'))
+},{"_process":107}],107:[function(require,module,exports){
+// shim for using process in browser
-},{"balanced-match":158,"concat-map":159}],158:[function(require,module,exports){
-module.exports = balanced;
-function balanced(a, b, str) {
- var bal = 0;
- var m = {};
- var ended = false;
+var process = module.exports = {};
+var queue = [];
+var draining = false;
+var currentQueue;
+var queueIndex = -1;
- for (var i = 0; i < str.length; i++) {
- if (a == str.substr(i, a.length)) {
- if (!('start' in m)) m.start = i;
- bal++;
+function cleanUpNextTick() {
+ draining = false;
+ if (currentQueue.length) {
+ queue = currentQueue.concat(queue);
+ } else {
+ queueIndex = -1;
}
- else if (b == str.substr(i, b.length) && 'start' in m) {
- ended = true;
- bal--;
- if (!bal) {
- m.end = i;
- m.pre = str.substr(0, m.start);
- m.body = (m.end - m.start > 1)
- ? str.substring(m.start + a.length, m.end)
- : '';
- m.post = str.slice(m.end + b.length);
- return m;
- }
+ if (queue.length) {
+ drainQueue();
}
- }
+}
- // if we opened more than we closed, find the one we closed
- if (bal && ended) {
- var start = m.start + a.length;
- m = balanced(a, b, str.substr(start));
- if (m) {
- m.start += start;
- m.end += start;
- m.pre = str.slice(0, start) + m.pre;
+function drainQueue() {
+ if (draining) {
+ return;
}
- return m;
- }
+ var timeout = setTimeout(cleanUpNextTick);
+ draining = true;
+
+ var len = queue.length;
+ while(len) {
+ currentQueue = queue;
+ queue = [];
+ while (++queueIndex < len) {
+ if (currentQueue) {
+ currentQueue[queueIndex].run();
+ }
+ }
+ queueIndex = -1;
+ len = queue.length;
+ }
+ currentQueue = null;
+ draining = false;
+ clearTimeout(timeout);
}
-},{}],159:[function(require,module,exports){
-module.exports = function (xs, fn) {
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- var x = fn(xs[i], i);
- if (isArray(x)) res.push.apply(res, x);
- else res.push(x);
+process.nextTick = function (fun) {
+ var args = new Array(arguments.length - 1);
+ if (arguments.length > 1) {
+ for (var i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+ }
+ queue.push(new Item(fun, args));
+ if (queue.length === 1 && !draining) {
+ setTimeout(drainQueue, 0);
}
- return res;
};
-var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
+// v8 likes predictible objects
+function Item(fun, array) {
+ this.fun = fun;
+ this.array = array;
+}
+Item.prototype.run = function () {
+ this.fun.apply(null, this.array);
};
+process.title = 'browser';
+process.browser = true;
+process.env = {};
+process.argv = [];
+process.version = ''; // empty string to avoid regexp issues
+process.versions = {};
-},{}],160:[function(require,module,exports){
-var Readable = require('readable-stream').Readable;
-var isReadable = require('isstream').isReadable;
-var util = require('util');
+function noop() {}
+process.on = noop;
+process.addListener = noop;
+process.once = noop;
+process.off = noop;
+process.removeListener = noop;
+process.removeAllListeners = noop;
+process.emit = noop;
-function addStream(streams, stream)
-{
- if(!isReadable(stream)) throw new Error('All input streams must be readable');
+process.binding = function (name) {
+ throw new Error('process.binding is not supported');
+};
- var self = this;
+process.cwd = function () { return '/' };
+process.chdir = function (dir) {
+ throw new Error('process.chdir is not supported');
+};
+process.umask = function() { return 0; };
- stream._buffer = [];
+},{}],108:[function(require,module,exports){
+(function (global){
+/*! https://mths.be/punycode v1.3.2 by @mathias */
+;(function(root) {
- stream.on('readable', function()
- {
- var chunk = stream.read();
- if (chunk === null)
- return;
+ /** Detect free variables */
+ var freeExports = typeof exports == 'object' && exports &&
+ !exports.nodeType && exports;
+ var freeModule = typeof module == 'object' && module &&
+ !module.nodeType && module;
+ var freeGlobal = typeof global == 'object' && global;
+ if (
+ freeGlobal.global === freeGlobal ||
+ freeGlobal.window === freeGlobal ||
+ freeGlobal.self === freeGlobal
+ ) {
+ root = freeGlobal;
+ }
- if(this === streams[0])
- self.push(chunk);
+ /**
+ * The `punycode` object.
+ * @name punycode
+ * @type Object
+ */
+ var punycode,
- else
- this._buffer.push(chunk);
- });
+ /** Highest positive signed 32-bit float value */
+ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
- stream.on('end', function()
- {
- for(var stream = streams[0];
- stream && stream._readableState.ended;
- stream = streams[0])
- {
- while(stream._buffer.length)
- self.push(stream._buffer.shift());
+ /** Bootstring parameters */
+ base = 36,
+ tMin = 1,
+ tMax = 26,
+ skew = 38,
+ damp = 700,
+ initialBias = 72,
+ initialN = 128, // 0x80
+ delimiter = '-', // '\x2D'
- streams.shift();
- }
+ /** Regular expressions */
+ regexPunycode = /^xn--/,
+ regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
+ regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
- if(!streams.length) self.push(null);
- });
+ /** Error messages */
+ errors = {
+ 'overflow': 'Overflow: input needs wider integers to process',
+ 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
+ 'invalid-input': 'Invalid input'
+ },
- stream.on('error', this.emit.bind(this, 'error'));
+ /** Convenience shortcuts */
+ baseMinusTMin = base - tMin,
+ floor = Math.floor,
+ stringFromCharCode = String.fromCharCode,
- streams.push(stream);
-}
+ /** Temporary variable */
+ key;
+
+ /*--------------------------------------------------------------------------*/
+ /**
+ * A generic error utility function.
+ * @private
+ * @param {String} type The error type.
+ * @returns {Error} Throws a `RangeError` with the applicable error message.
+ */
+ function error(type) {
+ throw RangeError(errors[type]);
+ }
-function OrderedStreams(streams, options) {
- if (!(this instanceof(OrderedStreams))) {
- return new OrderedStreams(streams, options);
- }
+ /**
+ * A generic `Array#map` utility function.
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} callback The function that gets called for every array
+ * item.
+ * @returns {Array} A new array of values returned by the callback function.
+ */
+ function map(array, fn) {
+ var length = array.length;
+ var result = [];
+ while (length--) {
+ result[length] = fn(array[length]);
+ }
+ return result;
+ }
- streams = streams || [];
- options = options || {};
+ /**
+ * A simple `Array#map`-like wrapper to work with domain name strings or email
+ * addresses.
+ * @private
+ * @param {String} domain The domain name or email address.
+ * @param {Function} callback The function that gets called for every
+ * character.
+ * @returns {Array} A new string of characters returned by the callback
+ * function.
+ */
+ function mapDomain(string, fn) {
+ var parts = string.split('@');
+ var result = '';
+ if (parts.length > 1) {
+ // In email addresses, only the domain name should be punycoded. Leave
+ // the local part (i.e. everything up to `@`) intact.
+ result = parts[0] + '@';
+ string = parts[1];
+ }
+ // Avoid `split(regex)` for IE8 compatibility. See #17.
+ string = string.replace(regexSeparators, '\x2E');
+ var labels = string.split('.');
+ var encoded = map(labels, fn).join('.');
+ return result + encoded;
+ }
- options.objectMode = true;
+ /**
+ * Creates an array containing the numeric code points of each Unicode
+ * character in the string. While JavaScript uses UCS-2 internally,
+ * this function will convert a pair of surrogate halves (each of which
+ * UCS-2 exposes as separate characters) into a single code point,
+ * matching UTF-16.
+ * @see `punycode.ucs2.encode`
+ * @see
+ * @memberOf punycode.ucs2
+ * @name decode
+ * @param {String} string The Unicode input string (UCS-2).
+ * @returns {Array} The new array of code points.
+ */
+ function ucs2decode(string) {
+ var output = [],
+ counter = 0,
+ length = string.length,
+ value,
+ extra;
+ while (counter < length) {
+ value = string.charCodeAt(counter++);
+ if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
+ // high surrogate, and there is a next character
+ extra = string.charCodeAt(counter++);
+ if ((extra & 0xFC00) == 0xDC00) { // low surrogate
+ output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
+ } else {
+ // unmatched surrogate; only append this code unit, in case the next
+ // code unit is the high surrogate of a surrogate pair
+ output.push(value);
+ counter--;
+ }
+ } else {
+ output.push(value);
+ }
+ }
+ return output;
+ }
- Readable.call(this, options);
+ /**
+ * Creates a string based on an array of numeric code points.
+ * @see `punycode.ucs2.decode`
+ * @memberOf punycode.ucs2
+ * @name encode
+ * @param {Array} codePoints The array of numeric code points.
+ * @returns {String} The new Unicode string (UCS-2).
+ */
+ function ucs2encode(array) {
+ return map(array, function(value) {
+ var output = '';
+ if (value > 0xFFFF) {
+ value -= 0x10000;
+ output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
+ value = 0xDC00 | value & 0x3FF;
+ }
+ output += stringFromCharCode(value);
+ return output;
+ }).join('');
+ }
+ /**
+ * Converts a basic code point into a digit/integer.
+ * @see `digitToBasic()`
+ * @private
+ * @param {Number} codePoint The basic numeric code point value.
+ * @returns {Number} The numeric value of a basic code point (for use in
+ * representing integers) in the range `0` to `base - 1`, or `base` if
+ * the code point does not represent a value.
+ */
+ function basicToDigit(codePoint) {
+ if (codePoint - 48 < 10) {
+ return codePoint - 22;
+ }
+ if (codePoint - 65 < 26) {
+ return codePoint - 65;
+ }
+ if (codePoint - 97 < 26) {
+ return codePoint - 97;
+ }
+ return base;
+ }
- if(!Array.isArray(streams)) streams = [streams];
- if(!streams.length) return this.push(null); // no streams, close
+ /**
+ * Converts a digit/integer into a basic code point.
+ * @see `basicToDigit()`
+ * @private
+ * @param {Number} digit The numeric value of a basic code point.
+ * @returns {Number} The basic code point whose value (when used for
+ * representing integers) is `digit`, which needs to be in the range
+ * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
+ * used; else, the lowercase form is used. The behavior is undefined
+ * if `flag` is non-zero and `digit` has no uppercase form.
+ */
+ function digitToBasic(digit, flag) {
+ // 0..25 map to ASCII a..z or A..Z
+ // 26..35 map to ASCII 0..9
+ return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
+ }
+ /**
+ * Bias adaptation function as per section 3.4 of RFC 3492.
+ * http://tools.ietf.org/html/rfc3492#section-3.4
+ * @private
+ */
+ function adapt(delta, numPoints, firstTime) {
+ var k = 0;
+ delta = firstTime ? floor(delta / damp) : delta >> 1;
+ delta += floor(delta / numPoints);
+ for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
+ delta = floor(delta / baseMinusTMin);
+ }
+ return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
+ }
- var addStream_bind = addStream.bind(this, []);
+ /**
+ * Converts a Punycode string of ASCII-only symbols to a string of Unicode
+ * symbols.
+ * @memberOf punycode
+ * @param {String} input The Punycode string of ASCII-only symbols.
+ * @returns {String} The resulting string of Unicode symbols.
+ */
+ function decode(input) {
+ // Don't use UCS-2
+ var output = [],
+ inputLength = input.length,
+ out,
+ i = 0,
+ n = initialN,
+ bias = initialBias,
+ basic,
+ j,
+ index,
+ oldi,
+ w,
+ k,
+ digit,
+ t,
+ /** Cached calculation results */
+ baseMinusT;
+ // Handle the basic code points: let `basic` be the number of input code
+ // points before the last delimiter, or `0` if there is none, then copy
+ // the first basic code points to the output.
- streams.forEach(function(item)
- {
- if(Array.isArray(item))
- item.forEach(addStream_bind);
+ basic = input.lastIndexOf(delimiter);
+ if (basic < 0) {
+ basic = 0;
+ }
- else
- addStream_bind(item);
- });
-}
-util.inherits(OrderedStreams, Readable);
+ for (j = 0; j < basic; ++j) {
+ // if it's not a basic code point
+ if (input.charCodeAt(j) >= 0x80) {
+ error('not-basic');
+ }
+ output.push(input.charCodeAt(j));
+ }
-OrderedStreams.prototype._read = function () {};
+ // Main decoding loop: start just after the last delimiter if any basic code
+ // points were copied; start at the beginning otherwise.
+ for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
-module.exports = OrderedStreams;
+ // `index` is the index of the next character to be consumed.
+ // Decode a generalized variable-length integer into `delta`,
+ // which gets added to `i`. The overflow checking is easier
+ // if we increase `i` as we go, then subtract off its starting
+ // value at the end to obtain `delta`.
+ for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
-},{"isstream":161,"readable-stream":171,"util":90}],161:[function(require,module,exports){
-var stream = require('stream')
+ if (index >= inputLength) {
+ error('invalid-input');
+ }
+ digit = basicToDigit(input.charCodeAt(index++));
-function isStream (obj) {
- return obj instanceof stream.Stream
-}
+ if (digit >= base || digit > floor((maxInt - i) / w)) {
+ error('overflow');
+ }
+ i += digit * w;
+ t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
-function isReadable (obj) {
- return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object'
-}
+ if (digit < t) {
+ break;
+ }
+ baseMinusT = base - t;
+ if (w > floor(maxInt / baseMinusT)) {
+ error('overflow');
+ }
-function isWritable (obj) {
- return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object'
-}
+ w *= baseMinusT;
+ }
-function isDuplex (obj) {
- return isReadable(obj) && isWritable(obj)
-}
+ out = output.length + 1;
+ bias = adapt(i - oldi, out, oldi == 0);
+ // `i` was supposed to wrap around from `out` to `0`,
+ // incrementing `n` each time, so we'll fix that now:
+ if (floor(i / out) > maxInt - n) {
+ error('overflow');
+ }
-module.exports = isStream
-module.exports.isReadable = isReadable
-module.exports.isWritable = isWritable
-module.exports.isDuplex = isDuplex
+ n += floor(i / out);
+ i %= out;
-},{"stream":81}],162:[function(require,module,exports){
-(function (process){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+ // Insert `n` at position `i` of the output
+ output.splice(i++, 0, n);
-// a duplex stream is just a stream that is both readable and writable.
-// Since JS doesn't have multiple prototypal inheritance, this class
-// prototypally inherits from Readable, and then parasitically from
-// Writable.
+ }
-module.exports = Duplex;
+ return ucs2encode(output);
+ }
-/**/
-var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) keys.push(key);
- return keys;
-}
-/**/
+ /**
+ * Converts a string of Unicode symbols (e.g. a domain name label) to a
+ * Punycode string of ASCII-only symbols.
+ * @memberOf punycode
+ * @param {String} input The string of Unicode symbols.
+ * @returns {String} The resulting Punycode string of ASCII-only symbols.
+ */
+ function encode(input) {
+ var n,
+ delta,
+ handledCPCount,
+ basicLength,
+ bias,
+ j,
+ m,
+ q,
+ k,
+ t,
+ currentValue,
+ output = [],
+ /** `inputLength` will hold the number of code points in `input`. */
+ inputLength,
+ /** Cached calculation results */
+ handledCPCountPlusOne,
+ baseMinusT,
+ qMinusT;
+ // Convert the input in UCS-2 to Unicode
+ input = ucs2decode(input);
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+ // Cache the length
+ inputLength = input.length;
-var Readable = require('./_stream_readable');
-var Writable = require('./_stream_writable');
+ // Initialize the state
+ n = initialN;
+ delta = 0;
+ bias = initialBias;
-util.inherits(Duplex, Readable);
+ // Handle the basic code points
+ for (j = 0; j < inputLength; ++j) {
+ currentValue = input[j];
+ if (currentValue < 0x80) {
+ output.push(stringFromCharCode(currentValue));
+ }
+ }
-forEach(objectKeys(Writable.prototype), function(method) {
- if (!Duplex.prototype[method])
- Duplex.prototype[method] = Writable.prototype[method];
-});
+ handledCPCount = basicLength = output.length;
-function Duplex(options) {
- if (!(this instanceof Duplex))
- return new Duplex(options);
+ // `handledCPCount` is the number of code points that have been handled;
+ // `basicLength` is the number of basic code points.
- Readable.call(this, options);
- Writable.call(this, options);
+ // Finish the basic string - if it is not empty - with a delimiter
+ if (basicLength) {
+ output.push(delimiter);
+ }
- if (options && options.readable === false)
- this.readable = false;
+ // Main encoding loop:
+ while (handledCPCount < inputLength) {
- if (options && options.writable === false)
- this.writable = false;
+ // All non-basic code points < n have been handled already. Find the next
+ // larger one:
+ for (m = maxInt, j = 0; j < inputLength; ++j) {
+ currentValue = input[j];
+ if (currentValue >= n && currentValue < m) {
+ m = currentValue;
+ }
+ }
- this.allowHalfOpen = true;
- if (options && options.allowHalfOpen === false)
- this.allowHalfOpen = false;
+ // Increase `delta` enough to advance the decoder's state to ,
+ // but guard against overflow
+ handledCPCountPlusOne = handledCPCount + 1;
+ if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
+ error('overflow');
+ }
- this.once('end', onend);
-}
+ delta += (m - n) * handledCPCountPlusOne;
+ n = m;
-// the no-half-open enforcer
-function onend() {
- // if we allow half-open state, or if the writable side ended,
- // then we're ok.
- if (this.allowHalfOpen || this._writableState.ended)
- return;
+ for (j = 0; j < inputLength; ++j) {
+ currentValue = input[j];
- // no more data can be written.
- // But allow more writes to happen in this tick.
- process.nextTick(this.end.bind(this));
-}
+ if (currentValue < n && ++delta > maxInt) {
+ error('overflow');
+ }
-function forEach (xs, f) {
- for (var i = 0, l = xs.length; i < l; i++) {
- f(xs[i], i);
- }
-}
+ if (currentValue == n) {
+ // Represent delta as a generalized variable-length integer
+ for (q = delta, k = base; /* no condition */; k += base) {
+ t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
+ if (q < t) {
+ break;
+ }
+ qMinusT = q - t;
+ baseMinusT = base - t;
+ output.push(
+ stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
+ );
+ q = floor(qMinusT / baseMinusT);
+ }
-}).call(this,require('_process'))
-},{"./_stream_readable":164,"./_stream_writable":166,"_process":64,"core-util-is":167,"inherits":168}],163:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+ output.push(stringFromCharCode(digitToBasic(q, 0)));
+ bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
+ delta = 0;
+ ++handledCPCount;
+ }
+ }
-// a passthrough stream.
-// basically just the most minimal sort of Transform stream.
-// Every written chunk gets output as-is.
+ ++delta;
+ ++n;
-module.exports = PassThrough;
+ }
+ return output.join('');
+ }
-var Transform = require('./_stream_transform');
+ /**
+ * Converts a Punycode string representing a domain name or an email address
+ * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
+ * it doesn't matter if you call it on a string that has already been
+ * converted to Unicode.
+ * @memberOf punycode
+ * @param {String} input The Punycoded domain name or email address to
+ * convert to Unicode.
+ * @returns {String} The Unicode representation of the given Punycode
+ * string.
+ */
+ function toUnicode(input) {
+ return mapDomain(input, function(string) {
+ return regexPunycode.test(string)
+ ? decode(string.slice(4).toLowerCase())
+ : string;
+ });
+ }
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+ /**
+ * Converts a Unicode string representing a domain name or an email address to
+ * Punycode. Only the non-ASCII parts of the domain name will be converted,
+ * i.e. it doesn't matter if you call it with a domain that's already in
+ * ASCII.
+ * @memberOf punycode
+ * @param {String} input The domain name or email address to convert, as a
+ * Unicode string.
+ * @returns {String} The Punycode representation of the given domain name or
+ * email address.
+ */
+ function toASCII(input) {
+ return mapDomain(input, function(string) {
+ return regexNonASCII.test(string)
+ ? 'xn--' + encode(string)
+ : string;
+ });
+ }
-util.inherits(PassThrough, Transform);
+ /*--------------------------------------------------------------------------*/
-function PassThrough(options) {
- if (!(this instanceof PassThrough))
- return new PassThrough(options);
+ /** Define the public API */
+ punycode = {
+ /**
+ * A string representing the current Punycode.js version number.
+ * @memberOf punycode
+ * @type String
+ */
+ 'version': '1.3.2',
+ /**
+ * An object of methods to convert from JavaScript's internal character
+ * representation (UCS-2) to Unicode code points, and back.
+ * @see
+ * @memberOf punycode
+ * @type Object
+ */
+ 'ucs2': {
+ 'decode': ucs2decode,
+ 'encode': ucs2encode
+ },
+ 'decode': decode,
+ 'encode': encode,
+ 'toASCII': toASCII,
+ 'toUnicode': toUnicode
+ };
- Transform.call(this, options);
-}
+ /** Expose `punycode` */
+ // Some AMD build optimizers, like r.js, check for specific condition patterns
+ // like the following:
+ if (
+ typeof define == 'function' &&
+ typeof define.amd == 'object' &&
+ define.amd
+ ) {
+ define('punycode', function() {
+ return punycode;
+ });
+ } else if (freeExports && freeModule) {
+ if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+
+ freeModule.exports = punycode;
+ } else { // in Narwhal or RingoJS v0.7.0-
+ for (key in punycode) {
+ punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
+ }
+ }
+ } else { // in Rhino or a web browser
+ root.punycode = punycode;
+ }
-PassThrough.prototype._transform = function(chunk, encoding, cb) {
- cb(null, chunk);
-};
+}(this));
-},{"./_stream_transform":165,"core-util-is":167,"inherits":168}],164:[function(require,module,exports){
-(function (process){
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],109:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -16555,1676 +15239,1454 @@ PassThrough.prototype._transform = function(chunk, encoding, cb) {
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-module.exports = Readable;
-
-/**/
-var isArray = require('isarray');
-/**/
-
-
-/**/
-var Buffer = require('buffer').Buffer;
-/**/
-
-Readable.ReadableState = ReadableState;
-
-var EE = require('events').EventEmitter;
-
-/**/
-if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
- return emitter.listeners(type).length;
-};
-/**/
-
-var Stream = require('stream');
-
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
-
-var StringDecoder;
-
-
-/**/
-var debug = require('util');
-if (debug && debug.debuglog) {
- debug = debug.debuglog('stream');
-} else {
- debug = function () {};
-}
-/**/
-
-
-util.inherits(Readable, Stream);
-
-function ReadableState(options, stream) {
- var Duplex = require('./_stream_duplex');
-
- options = options || {};
-
- // the point at which it stops calling _read() to fill the buffer
- // Note: 0 is a valid value, means "don't call _read preemptively ever"
- var hwm = options.highWaterMark;
- var defaultHwm = options.objectMode ? 16 : 16 * 1024;
- this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
-
- // cast to ints.
- this.highWaterMark = ~~this.highWaterMark;
-
- this.buffer = [];
- this.length = 0;
- this.pipes = null;
- this.pipesCount = 0;
- this.flowing = null;
- this.ended = false;
- this.endEmitted = false;
- this.reading = false;
-
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
-
- // whenever we return null, then we set a flag to say
- // that we're awaiting a 'readable' event emission.
- this.needReadable = false;
- this.emittedReadable = false;
- this.readableListening = false;
-
-
- // object stream flag. Used to make read(n) ignore n and to
- // make all the buffer merging and length checks go away
- this.objectMode = !!options.objectMode;
-
- if (stream instanceof Duplex)
- this.objectMode = this.objectMode || !!options.readableObjectMode;
-
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
-
- // when piping, we only care about 'readable' events that happen
- // after read()ing all the bytes and not getting any pushback.
- this.ranOut = false;
-
- // the number of writers that are awaiting a drain event in .pipe()s
- this.awaitDrain = 0;
-
- // if true, a maybeReadMore has been scheduled
- this.readingMore = false;
-
- this.decoder = null;
- this.encoding = null;
- if (options.encoding) {
- if (!StringDecoder)
- StringDecoder = require('string_decoder/').StringDecoder;
- this.decoder = new StringDecoder(options.encoding);
- this.encoding = options.encoding;
- }
-}
-
-function Readable(options) {
- var Duplex = require('./_stream_duplex');
-
- if (!(this instanceof Readable))
- return new Readable(options);
-
- this._readableState = new ReadableState(options, this);
-
- // legacy
- this.readable = true;
+'use strict';
- Stream.call(this);
+// If obj.hasOwnProperty has been overridden, then calling
+// obj.hasOwnProperty(prop) will break.
+// See: https://github.com/joyent/node/issues/1707
+function hasOwnProperty(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
}
-// Manually shove something into the read() buffer.
-// This returns true if the highWaterMark has not been hit yet,
-// similar to how Writable.write() returns true if you should
-// write() some more.
-Readable.prototype.push = function(chunk, encoding) {
- var state = this._readableState;
+module.exports = function(qs, sep, eq, options) {
+ sep = sep || '&';
+ eq = eq || '=';
+ var obj = {};
- if (util.isString(chunk) && !state.objectMode) {
- encoding = encoding || state.defaultEncoding;
- if (encoding !== state.encoding) {
- chunk = new Buffer(chunk, encoding);
- encoding = '';
- }
+ if (typeof qs !== 'string' || qs.length === 0) {
+ return obj;
}
- return readableAddChunk(this, state, chunk, encoding, false);
-};
-
-// Unshift should *always* be something directly out of read()
-Readable.prototype.unshift = function(chunk) {
- var state = this._readableState;
- return readableAddChunk(this, state, chunk, '', true);
-};
-
-function readableAddChunk(stream, state, chunk, encoding, addToFront) {
- var er = chunkInvalid(state, chunk);
- if (er) {
- stream.emit('error', er);
- } else if (util.isNullOrUndefined(chunk)) {
- state.reading = false;
- if (!state.ended)
- onEofChunk(stream, state);
- } else if (state.objectMode || chunk && chunk.length > 0) {
- if (state.ended && !addToFront) {
- var e = new Error('stream.push() after EOF');
- stream.emit('error', e);
- } else if (state.endEmitted && addToFront) {
- var e = new Error('stream.unshift() after end event');
- stream.emit('error', e);
- } else {
- if (state.decoder && !addToFront && !encoding)
- chunk = state.decoder.write(chunk);
-
- if (!addToFront)
- state.reading = false;
-
- // if we want the data now, just emit it.
- if (state.flowing && state.length === 0 && !state.sync) {
- stream.emit('data', chunk);
- stream.read(0);
- } else {
- // update the buffer info.
- state.length += state.objectMode ? 1 : chunk.length;
- if (addToFront)
- state.buffer.unshift(chunk);
- else
- state.buffer.push(chunk);
+ var regexp = /\+/g;
+ qs = qs.split(sep);
- if (state.needReadable)
- emitReadable(stream);
- }
+ var maxKeys = 1000;
+ if (options && typeof options.maxKeys === 'number') {
+ maxKeys = options.maxKeys;
+ }
- maybeReadMore(stream, state);
- }
- } else if (!addToFront) {
- state.reading = false;
+ var len = qs.length;
+ // maxKeys <= 0 means that we should not limit keys count
+ if (maxKeys > 0 && len > maxKeys) {
+ len = maxKeys;
}
- return needMoreData(state);
-}
+ for (var i = 0; i < len; ++i) {
+ var x = qs[i].replace(regexp, '%20'),
+ idx = x.indexOf(eq),
+ kstr, vstr, k, v;
+ if (idx >= 0) {
+ kstr = x.substr(0, idx);
+ vstr = x.substr(idx + 1);
+ } else {
+ kstr = x;
+ vstr = '';
+ }
+ k = decodeURIComponent(kstr);
+ v = decodeURIComponent(vstr);
-// if it's past the high water mark, we can push in some more.
-// Also, if we have no data yet, we can stand some
-// more bytes. This is to work around cases where hwm=0,
-// such as the repl. Also, if the push() triggered a
-// readable event, and the user called read(largeNumber) such that
-// needReadable was set, then we ought to push more, so that another
-// 'readable' event will be triggered.
-function needMoreData(state) {
- return !state.ended &&
- (state.needReadable ||
- state.length < state.highWaterMark ||
- state.length === 0);
-}
+ if (!hasOwnProperty(obj, k)) {
+ obj[k] = v;
+ } else if (isArray(obj[k])) {
+ obj[k].push(v);
+ } else {
+ obj[k] = [obj[k], v];
+ }
+ }
-// backwards compatibility.
-Readable.prototype.setEncoding = function(enc) {
- if (!StringDecoder)
- StringDecoder = require('string_decoder/').StringDecoder;
- this._readableState.decoder = new StringDecoder(enc);
- this._readableState.encoding = enc;
- return this;
+ return obj;
};
-// Don't raise the hwm > 128MB
-var MAX_HWM = 0x800000;
-function roundUpToNextPowerOf2(n) {
- if (n >= MAX_HWM) {
- n = MAX_HWM;
- } else {
- // Get the next highest power of 2
- n--;
- for (var p = 1; p < 32; p <<= 1) n |= n >> p;
- n++;
- }
- return n;
-}
+var isArray = Array.isArray || function (xs) {
+ return Object.prototype.toString.call(xs) === '[object Array]';
+};
-function howMuchToRead(n, state) {
- if (state.length === 0 && state.ended)
- return 0;
+},{}],110:[function(require,module,exports){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
- if (state.objectMode)
- return n === 0 ? 0 : 1;
+'use strict';
- if (isNaN(n) || util.isNull(n)) {
- // only flow one buffer at a time
- if (state.flowing && state.buffer.length)
- return state.buffer[0].length;
- else
- return state.length;
- }
+var stringifyPrimitive = function(v) {
+ switch (typeof v) {
+ case 'string':
+ return v;
- if (n <= 0)
- return 0;
+ case 'boolean':
+ return v ? 'true' : 'false';
- // If we're asking for more than the target buffer level,
- // then raise the water mark. Bump up to the next highest
- // power of 2, to prevent increasing it excessively in tiny
- // amounts.
- if (n > state.highWaterMark)
- state.highWaterMark = roundUpToNextPowerOf2(n);
+ case 'number':
+ return isFinite(v) ? v : '';
- // don't have that much. return null, unless we've ended.
- if (n > state.length) {
- if (!state.ended) {
- state.needReadable = true;
- return 0;
- } else
- return state.length;
+ default:
+ return '';
}
+};
- return n;
-}
-
-// you can override either this method, or the async _read(n) below.
-Readable.prototype.read = function(n) {
- debug('read', n);
- var state = this._readableState;
- var nOrig = n;
-
- if (!util.isNumber(n) || n > 0)
- state.emittedReadable = false;
-
- // if we're doing read(0) to trigger a readable event, but we
- // already have a bunch of data in the buffer, then just trigger
- // the 'readable' event and move on.
- if (n === 0 &&
- state.needReadable &&
- (state.length >= state.highWaterMark || state.ended)) {
- debug('read: emitReadable', state.length, state.ended);
- if (state.length === 0 && state.ended)
- endReadable(this);
- else
- emitReadable(this);
- return null;
+module.exports = function(obj, sep, eq, name) {
+ sep = sep || '&';
+ eq = eq || '=';
+ if (obj === null) {
+ obj = undefined;
}
- n = howMuchToRead(n, state);
+ if (typeof obj === 'object') {
+ return map(objectKeys(obj), function(k) {
+ var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
+ if (isArray(obj[k])) {
+ return map(obj[k], function(v) {
+ return ks + encodeURIComponent(stringifyPrimitive(v));
+ }).join(sep);
+ } else {
+ return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
+ }
+ }).join(sep);
- // if we've ended, and we're now clear, then finish it up.
- if (n === 0 && state.ended) {
- if (state.length === 0)
- endReadable(this);
- return null;
}
- // All the actual chunk generation logic needs to be
- // *below* the call to _read. The reason is that in certain
- // synthetic stream cases, such as passthrough streams, _read
- // may be a completely synchronous operation which may change
- // the state of the read buffer, providing enough data when
- // before there was *not* enough.
- //
- // So, the steps are:
- // 1. Figure out what the state of things will be after we do
- // a read from the buffer.
- //
- // 2. If that resulting state will trigger a _read, then call _read.
- // Note that this may be asynchronous, or synchronous. Yes, it is
- // deeply ugly to write APIs this way, but that still doesn't mean
- // that the Readable class should behave improperly, as streams are
- // designed to be sync/async agnostic.
- // Take note if the _read call is sync or async (ie, if the read call
- // has returned yet), so that we know whether or not it's safe to emit
- // 'readable' etc.
- //
- // 3. Actually pull the requested chunks out of the buffer and return.
+ if (!name) return '';
+ return encodeURIComponent(stringifyPrimitive(name)) + eq +
+ encodeURIComponent(stringifyPrimitive(obj));
+};
- // if we need a readable event, then we need to do some reading.
- var doRead = state.needReadable;
- debug('need readable', doRead);
+var isArray = Array.isArray || function (xs) {
+ return Object.prototype.toString.call(xs) === '[object Array]';
+};
- // if we currently have less than the highWaterMark, then also read some
- if (state.length === 0 || state.length - n < state.highWaterMark) {
- doRead = true;
- debug('length less than watermark', doRead);
+function map (xs, f) {
+ if (xs.map) return xs.map(f);
+ var res = [];
+ for (var i = 0; i < xs.length; i++) {
+ res.push(f(xs[i], i));
}
+ return res;
+}
- // however, if we've ended, then there's no point, and if we're already
- // reading, then it's unnecessary.
- if (state.ended || state.reading) {
- doRead = false;
- debug('reading or ended', doRead);
+var objectKeys = Object.keys || function (obj) {
+ var res = [];
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
+ return res;
+};
- if (doRead) {
- debug('do read');
- state.reading = true;
- state.sync = true;
- // if the length is currently zero, then we *need* a readable event.
- if (state.length === 0)
- state.needReadable = true;
- // call internal read method
- this._read(state.highWaterMark);
- state.sync = false;
- }
+},{}],111:[function(require,module,exports){
+'use strict';
+
+exports.decode = exports.parse = require('./decode');
+exports.encode = exports.stringify = require('./encode');
+
+},{"./decode":109,"./encode":110}],112:[function(require,module,exports){
+module.exports = require("./lib/_stream_duplex.js")
+
+},{"./lib/_stream_duplex.js":113}],113:[function(require,module,exports){
+// a duplex stream is just a stream that is both readable and writable.
+// Since JS doesn't have multiple prototypal inheritance, this class
+// prototypally inherits from Readable, and then parasitically from
+// Writable.
+
+'use strict';
+
+/**/
+var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+ for (var key in obj) keys.push(key);
+ return keys;
+}
+/**/
- // If _read pushed data synchronously, then `reading` will be false,
- // and we need to re-evaluate how much data we can return to the user.
- if (doRead && !state.reading)
- n = howMuchToRead(nOrig, state);
- var ret;
- if (n > 0)
- ret = fromList(n, state);
- else
- ret = null;
+module.exports = Duplex;
- if (util.isNull(ret)) {
- state.needReadable = true;
- n = 0;
- }
+/**/
+var processNextTick = require('process-nextick-args');
+/**/
- state.length -= n;
- // If we have nothing in the buffer, then we want to know
- // as soon as we *do* get something into the buffer.
- if (state.length === 0 && !state.ended)
- state.needReadable = true;
- // If we tried to read() past the EOF, then emit end on the next tick.
- if (nOrig !== n && state.ended && state.length === 0)
- endReadable(this);
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
- if (!util.isNull(ret))
- this.emit('data', ret);
+var Readable = require('./_stream_readable');
+var Writable = require('./_stream_writable');
- return ret;
-};
+util.inherits(Duplex, Readable);
-function chunkInvalid(state, chunk) {
- var er = null;
- if (!util.isBuffer(chunk) &&
- !util.isString(chunk) &&
- !util.isNullOrUndefined(chunk) &&
- !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- return er;
+var keys = objectKeys(Writable.prototype);
+for (var v = 0; v < keys.length; v++) {
+ var method = keys[v];
+ if (!Duplex.prototype[method])
+ Duplex.prototype[method] = Writable.prototype[method];
}
+function Duplex(options) {
+ if (!(this instanceof Duplex))
+ return new Duplex(options);
-function onEofChunk(stream, state) {
- if (state.decoder && !state.ended) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) {
- state.buffer.push(chunk);
- state.length += state.objectMode ? 1 : chunk.length;
- }
- }
- state.ended = true;
+ Readable.call(this, options);
+ Writable.call(this, options);
- // emit 'readable' now to make sure it gets picked up.
- emitReadable(stream);
-}
+ if (options && options.readable === false)
+ this.readable = false;
-// Don't emit readable right away in sync mode, because this can trigger
-// another read() call => stack overflow. This way, it might trigger
-// a nextTick recursion warning, but that's not so bad.
-function emitReadable(stream) {
- var state = stream._readableState;
- state.needReadable = false;
- if (!state.emittedReadable) {
- debug('emitReadable', state.flowing);
- state.emittedReadable = true;
- if (state.sync)
- process.nextTick(function() {
- emitReadable_(stream);
- });
- else
- emitReadable_(stream);
- }
-}
+ if (options && options.writable === false)
+ this.writable = false;
-function emitReadable_(stream) {
- debug('emit readable');
- stream.emit('readable');
- flow(stream);
+ this.allowHalfOpen = true;
+ if (options && options.allowHalfOpen === false)
+ this.allowHalfOpen = false;
+
+ this.once('end', onend);
}
+// the no-half-open enforcer
+function onend() {
+ // if we allow half-open state, or if the writable side ended,
+ // then we're ok.
+ if (this.allowHalfOpen || this._writableState.ended)
+ return;
-// at this point, the user has presumably seen the 'readable' event,
-// and called read() to consume some data. that may have triggered
-// in turn another _read(n) call, in which case reading = true if
-// it's in progress.
-// However, if we're not ended, or reading, and the length < hwm,
-// then go ahead and try to read some more preemptively.
-function maybeReadMore(stream, state) {
- if (!state.readingMore) {
- state.readingMore = true;
- process.nextTick(function() {
- maybeReadMore_(stream, state);
- });
- }
+ // no more data can be written.
+ // But allow more writes to happen in this tick.
+ processNextTick(onEndNT, this);
}
-function maybeReadMore_(stream, state) {
- var len = state.length;
- while (!state.reading && !state.flowing && !state.ended &&
- state.length < state.highWaterMark) {
- debug('maybeReadMore read 0');
- stream.read(0);
- if (len === state.length)
- // didn't get any data, stop spinning.
- break;
- else
- len = state.length;
- }
- state.readingMore = false;
+function onEndNT(self) {
+ self.end();
}
-// abstract method. to be overridden in specific implementation classes.
-// call cb(er, data) where data is <= n in length.
-// for virtual (non-string, non-buffer) streams, "length" is somewhat
-// arbitrary, and perhaps not very meaningful.
-Readable.prototype._read = function(n) {
- this.emit('error', new Error('not implemented'));
-};
-
-Readable.prototype.pipe = function(dest, pipeOpts) {
- var src = this;
- var state = this._readableState;
-
- switch (state.pipesCount) {
- case 0:
- state.pipes = dest;
- break;
- case 1:
- state.pipes = [state.pipes, dest];
- break;
- default:
- state.pipes.push(dest);
- break;
+function forEach (xs, f) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ f(xs[i], i);
}
- state.pipesCount += 1;
- debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
+}
- var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
- dest !== process.stdout &&
- dest !== process.stderr;
+},{"./_stream_readable":115,"./_stream_writable":117,"core-util-is":15,"inherits":47,"process-nextick-args":106}],114:[function(require,module,exports){
+// a passthrough stream.
+// basically just the most minimal sort of Transform stream.
+// Every written chunk gets output as-is.
- var endFn = doEnd ? onend : cleanup;
- if (state.endEmitted)
- process.nextTick(endFn);
- else
- src.once('end', endFn);
+'use strict';
- dest.on('unpipe', onunpipe);
- function onunpipe(readable) {
- debug('onunpipe');
- if (readable === src) {
- cleanup();
- }
- }
+module.exports = PassThrough;
- function onend() {
- debug('onend');
- dest.end();
- }
+var Transform = require('./_stream_transform');
- // when the dest drains, it reduces the awaitDrain counter
- // on the source. This would be more elegant with a .once()
- // handler in flow(), but adding and removing repeatedly is
- // too slow.
- var ondrain = pipeOnDrain(src);
- dest.on('drain', ondrain);
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
- function cleanup() {
- debug('cleanup');
- // cleanup event handlers once the pipe is broken
- dest.removeListener('close', onclose);
- dest.removeListener('finish', onfinish);
- dest.removeListener('drain', ondrain);
- dest.removeListener('error', onerror);
- dest.removeListener('unpipe', onunpipe);
- src.removeListener('end', onend);
- src.removeListener('end', cleanup);
- src.removeListener('data', ondata);
+util.inherits(PassThrough, Transform);
- // if the reader is waiting for a drain event from this
- // specific writer, then it would cause it to never start
- // flowing again.
- // So, if this is awaiting a drain, then we just call it now.
- // If we don't know, then assume that we are waiting for one.
- if (state.awaitDrain &&
- (!dest._writableState || dest._writableState.needDrain))
- ondrain();
- }
+function PassThrough(options) {
+ if (!(this instanceof PassThrough))
+ return new PassThrough(options);
- src.on('data', ondata);
- function ondata(chunk) {
- debug('ondata');
- var ret = dest.write(chunk);
- if (false === ret) {
- debug('false write response, pause',
- src._readableState.awaitDrain);
- src._readableState.awaitDrain++;
- src.pause();
- }
- }
+ Transform.call(this, options);
+}
- // if the dest has an error, then stop piping into it.
- // however, don't suppress the throwing behavior for this.
- function onerror(er) {
- debug('onerror', er);
- unpipe();
- dest.removeListener('error', onerror);
- if (EE.listenerCount(dest, 'error') === 0)
- dest.emit('error', er);
- }
- // This is a brutally ugly hack to make sure that our error handler
- // is attached before any userland ones. NEVER DO THIS.
- if (!dest._events || !dest._events.error)
- dest.on('error', onerror);
- else if (isArray(dest._events.error))
- dest._events.error.unshift(onerror);
- else
- dest._events.error = [onerror, dest._events.error];
+PassThrough.prototype._transform = function(chunk, encoding, cb) {
+ cb(null, chunk);
+};
+},{"./_stream_transform":116,"core-util-is":15,"inherits":47}],115:[function(require,module,exports){
+(function (process){
+'use strict';
+module.exports = Readable;
- // Both close and finish should trigger unpipe, but only once.
- function onclose() {
- dest.removeListener('finish', onfinish);
- unpipe();
- }
- dest.once('close', onclose);
- function onfinish() {
- debug('onfinish');
- dest.removeListener('close', onclose);
- unpipe();
- }
- dest.once('finish', onfinish);
+/**/
+var processNextTick = require('process-nextick-args');
+/**/
- function unpipe() {
- debug('unpipe');
- src.unpipe(dest);
- }
- // tell the dest that it's being piped to
- dest.emit('pipe', src);
+/**/
+var isArray = require('isarray');
+/**/
- // start the flow if it hasn't been started already.
- if (!state.flowing) {
- debug('pipe resume');
- src.resume();
- }
- return dest;
+/**/
+var Buffer = require('buffer').Buffer;
+/**/
+
+Readable.ReadableState = ReadableState;
+
+var EE = require('events');
+
+/**/
+var EElistenerCount = function(emitter, type) {
+ return emitter.listeners(type).length;
};
+/**/
-function pipeOnDrain(src) {
- return function() {
- var state = src._readableState;
- debug('pipeOnDrain', state.awaitDrain);
- if (state.awaitDrain)
- state.awaitDrain--;
- if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
- state.flowing = true;
- flow(src);
- }
- };
-}
-Readable.prototype.unpipe = function(dest) {
- var state = this._readableState;
+/**/
+var Stream;
+(function (){try{
+ Stream = require('st' + 'ream');
+}catch(_){}finally{
+ if (!Stream)
+ Stream = require('events').EventEmitter;
+}}())
+/**/
- // if we're not piping anywhere, then do nothing.
- if (state.pipesCount === 0)
- return this;
+var Buffer = require('buffer').Buffer;
- // just one destination. most common case.
- if (state.pipesCount === 1) {
- // passed in one, but it's not the right one.
- if (dest && dest !== state.pipes)
- return this;
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
- if (!dest)
- dest = state.pipes;
- // got a match.
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
- if (dest)
- dest.emit('unpipe', this);
- return this;
- }
- // slow case. multiple pipe destinations.
+/**/
+var debugUtil = require('util');
+var debug;
+if (debugUtil && debugUtil.debuglog) {
+ debug = debugUtil.debuglog('stream');
+} else {
+ debug = function () {};
+}
+/**/
- if (!dest) {
- // remove all.
- var dests = state.pipes;
- var len = state.pipesCount;
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
+var StringDecoder;
- for (var i = 0; i < len; i++)
- dests[i].emit('unpipe', this);
- return this;
- }
+util.inherits(Readable, Stream);
- // try to find the right one.
- var i = indexOf(state.pipes, dest);
- if (i === -1)
- return this;
+function ReadableState(options, stream) {
+ var Duplex = require('./_stream_duplex');
- state.pipes.splice(i, 1);
- state.pipesCount -= 1;
- if (state.pipesCount === 1)
- state.pipes = state.pipes[0];
+ options = options || {};
- dest.emit('unpipe', this);
+ // object stream flag. Used to make read(n) ignore n and to
+ // make all the buffer merging and length checks go away
+ this.objectMode = !!options.objectMode;
- return this;
-};
+ if (stream instanceof Duplex)
+ this.objectMode = this.objectMode || !!options.readableObjectMode;
-// set up data events if they are asked for
-// Ensure readable listeners eventually get something
-Readable.prototype.on = function(ev, fn) {
- var res = Stream.prototype.on.call(this, ev, fn);
+ // the point at which it stops calling _read() to fill the buffer
+ // Note: 0 is a valid value, means "don't call _read preemptively ever"
+ var hwm = options.highWaterMark;
+ var defaultHwm = this.objectMode ? 16 : 16 * 1024;
+ this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
- // If listening to data, and it has not explicitly been paused,
- // then call resume to start the flow of data on the next tick.
- if (ev === 'data' && false !== this._readableState.flowing) {
- this.resume();
- }
+ // cast to ints.
+ this.highWaterMark = ~~this.highWaterMark;
- if (ev === 'readable' && this.readable) {
- var state = this._readableState;
- if (!state.readableListening) {
- state.readableListening = true;
- state.emittedReadable = false;
- state.needReadable = true;
- if (!state.reading) {
- var self = this;
- process.nextTick(function() {
- debug('readable nexttick read 0');
- self.read(0);
- });
- } else if (state.length) {
- emitReadable(this, state);
- }
- }
- }
+ this.buffer = [];
+ this.length = 0;
+ this.pipes = null;
+ this.pipesCount = 0;
+ this.flowing = null;
+ this.ended = false;
+ this.endEmitted = false;
+ this.reading = false;
- return res;
-};
-Readable.prototype.addListener = Readable.prototype.on;
+ // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, because any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+ this.sync = true;
-// pause() and resume() are remnants of the legacy readable stream API
-// If the user uses them, then switch into old mode.
-Readable.prototype.resume = function() {
- var state = this._readableState;
- if (!state.flowing) {
- debug('resume');
- state.flowing = true;
- if (!state.reading) {
- debug('resume read 0');
- this.read(0);
- }
- resume(this, state);
- }
- return this;
-};
+ // whenever we return null, then we set a flag to say
+ // that we're awaiting a 'readable' event emission.
+ this.needReadable = false;
+ this.emittedReadable = false;
+ this.readableListening = false;
-function resume(stream, state) {
- if (!state.resumeScheduled) {
- state.resumeScheduled = true;
- process.nextTick(function() {
- resume_(stream, state);
- });
- }
-}
+ // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+ this.defaultEncoding = options.defaultEncoding || 'utf8';
-function resume_(stream, state) {
- state.resumeScheduled = false;
- stream.emit('resume');
- flow(stream);
- if (state.flowing && !state.reading)
- stream.read(0);
-}
+ // when piping, we only care about 'readable' events that happen
+ // after read()ing all the bytes and not getting any pushback.
+ this.ranOut = false;
-Readable.prototype.pause = function() {
- debug('call pause flowing=%j', this._readableState.flowing);
- if (false !== this._readableState.flowing) {
- debug('pause');
- this._readableState.flowing = false;
- this.emit('pause');
- }
- return this;
-};
+ // the number of writers that are awaiting a drain event in .pipe()s
+ this.awaitDrain = 0;
-function flow(stream) {
- var state = stream._readableState;
- debug('flow', state.flowing);
- if (state.flowing) {
- do {
- var chunk = stream.read();
- } while (null !== chunk && state.flowing);
+ // if true, a maybeReadMore has been scheduled
+ this.readingMore = false;
+
+ this.decoder = null;
+ this.encoding = null;
+ if (options.encoding) {
+ if (!StringDecoder)
+ StringDecoder = require('string_decoder/').StringDecoder;
+ this.decoder = new StringDecoder(options.encoding);
+ this.encoding = options.encoding;
}
}
-// wrap an old-style stream as the async data source.
-// This is *not* part of the readable stream interface.
-// It is an ugly unfortunate mess of history.
-Readable.prototype.wrap = function(stream) {
- var state = this._readableState;
- var paused = false;
+function Readable(options) {
+ var Duplex = require('./_stream_duplex');
- var self = this;
- stream.on('end', function() {
- debug('wrapped end');
- if (state.decoder && !state.ended) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length)
- self.push(chunk);
- }
+ if (!(this instanceof Readable))
+ return new Readable(options);
- self.push(null);
- });
+ this._readableState = new ReadableState(options, this);
- stream.on('data', function(chunk) {
- debug('wrapped data');
- if (state.decoder)
- chunk = state.decoder.write(chunk);
- if (!chunk || !state.objectMode && !chunk.length)
- return;
+ // legacy
+ this.readable = true;
- var ret = self.push(chunk);
- if (!ret) {
- paused = true;
- stream.pause();
- }
- });
+ if (options && typeof options.read === 'function')
+ this._read = options.read;
- // proxy all the other methods.
- // important when wrapping filters and duplexes.
- for (var i in stream) {
- if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
- this[i] = function(method) { return function() {
- return stream[method].apply(stream, arguments);
- }}(i);
- }
- }
+ Stream.call(this);
+}
- // proxy certain important events.
- var events = ['error', 'close', 'destroy', 'pause', 'resume'];
- forEach(events, function(ev) {
- stream.on(ev, self.emit.bind(self, ev));
- });
+// Manually shove something into the read() buffer.
+// This returns true if the highWaterMark has not been hit yet,
+// similar to how Writable.write() returns true if you should
+// write() some more.
+Readable.prototype.push = function(chunk, encoding) {
+ var state = this._readableState;
- // when we try to consume some more bytes, simply unpause the
- // underlying stream.
- self._read = function(n) {
- debug('wrapped _read', n);
- if (paused) {
- paused = false;
- stream.resume();
+ if (!state.objectMode && typeof chunk === 'string') {
+ encoding = encoding || state.defaultEncoding;
+ if (encoding !== state.encoding) {
+ chunk = new Buffer(chunk, encoding);
+ encoding = '';
}
- };
+ }
- return self;
+ return readableAddChunk(this, state, chunk, encoding, false);
};
+// Unshift should *always* be something directly out of read()
+Readable.prototype.unshift = function(chunk) {
+ var state = this._readableState;
+ return readableAddChunk(this, state, chunk, '', true);
+};
+Readable.prototype.isPaused = function() {
+ return this._readableState.flowing === false;
+};
-// exposed for testing purposes only.
-Readable._fromList = fromList;
-
-// Pluck off n bytes from an array of buffers.
-// Length is the combined lengths of all the buffers in the list.
-function fromList(n, state) {
- var list = state.buffer;
- var length = state.length;
- var stringMode = !!state.decoder;
- var objectMode = !!state.objectMode;
- var ret;
-
- // nothing in the list, definitely empty.
- if (list.length === 0)
- return null;
-
- if (length === 0)
- ret = null;
- else if (objectMode)
- ret = list.shift();
- else if (!n || n >= length) {
- // read it all, truncate the array.
- if (stringMode)
- ret = list.join('');
- else
- ret = Buffer.concat(list, length);
- list.length = 0;
- } else {
- // read just some of it.
- if (n < list[0].length) {
- // just take a part of the first list item.
- // slice is the same for buffers and strings.
- var buf = list[0];
- ret = buf.slice(0, n);
- list[0] = buf.slice(n);
- } else if (n === list[0].length) {
- // first list is a perfect match
- ret = list.shift();
+function readableAddChunk(stream, state, chunk, encoding, addToFront) {
+ var er = chunkInvalid(state, chunk);
+ if (er) {
+ stream.emit('error', er);
+ } else if (chunk === null) {
+ state.reading = false;
+ onEofChunk(stream, state);
+ } else if (state.objectMode || chunk && chunk.length > 0) {
+ if (state.ended && !addToFront) {
+ var e = new Error('stream.push() after EOF');
+ stream.emit('error', e);
+ } else if (state.endEmitted && addToFront) {
+ var e = new Error('stream.unshift() after end event');
+ stream.emit('error', e);
} else {
- // complex case.
- // we have enough to cover it, but it spans past the first buffer.
- if (stringMode)
- ret = '';
- else
- ret = new Buffer(n);
-
- var c = 0;
- for (var i = 0, l = list.length; i < l && c < n; i++) {
- var buf = list[0];
- var cpy = Math.min(n - c, buf.length);
+ if (state.decoder && !addToFront && !encoding)
+ chunk = state.decoder.write(chunk);
- if (stringMode)
- ret += buf.slice(0, cpy);
- else
- buf.copy(ret, c, 0, cpy);
+ if (!addToFront)
+ state.reading = false;
- if (cpy < buf.length)
- list[0] = buf.slice(cpy);
+ // if we want the data now, just emit it.
+ if (state.flowing && state.length === 0 && !state.sync) {
+ stream.emit('data', chunk);
+ stream.read(0);
+ } else {
+ // update the buffer info.
+ state.length += state.objectMode ? 1 : chunk.length;
+ if (addToFront)
+ state.buffer.unshift(chunk);
else
- list.shift();
+ state.buffer.push(chunk);
- c += cpy;
+ if (state.needReadable)
+ emitReadable(stream);
}
+
+ maybeReadMore(stream, state);
}
+ } else if (!addToFront) {
+ state.reading = false;
}
- return ret;
+ return needMoreData(state);
}
-function endReadable(stream) {
- var state = stream._readableState;
-
- // If we get here before consuming all the bytes, then that is a
- // bug in node. Should never happen.
- if (state.length > 0)
- throw new Error('endReadable called on non-empty stream');
- if (!state.endEmitted) {
- state.ended = true;
- process.nextTick(function() {
- // Check that we didn't get one last unshift.
- if (!state.endEmitted && state.length === 0) {
- state.endEmitted = true;
- stream.readable = false;
- stream.emit('end');
- }
- });
- }
+// if it's past the high water mark, we can push in some more.
+// Also, if we have no data yet, we can stand some
+// more bytes. This is to work around cases where hwm=0,
+// such as the repl. Also, if the push() triggered a
+// readable event, and the user called read(largeNumber) such that
+// needReadable was set, then we ought to push more, so that another
+// 'readable' event will be triggered.
+function needMoreData(state) {
+ return !state.ended &&
+ (state.needReadable ||
+ state.length < state.highWaterMark ||
+ state.length === 0);
}
-function forEach (xs, f) {
- for (var i = 0, l = xs.length; i < l; i++) {
- f(xs[i], i);
- }
-}
+// backwards compatibility.
+Readable.prototype.setEncoding = function(enc) {
+ if (!StringDecoder)
+ StringDecoder = require('string_decoder/').StringDecoder;
+ this._readableState.decoder = new StringDecoder(enc);
+ this._readableState.encoding = enc;
+ return this;
+};
-function indexOf (xs, x) {
- for (var i = 0, l = xs.length; i < l; i++) {
- if (xs[i] === x) return i;
+// Don't raise the hwm > 8MB
+var MAX_HWM = 0x800000;
+function computeNewHighWaterMark(n) {
+ if (n >= MAX_HWM) {
+ n = MAX_HWM;
+ } else {
+ // Get the next highest power of 2
+ n--;
+ n |= n >>> 1;
+ n |= n >>> 2;
+ n |= n >>> 4;
+ n |= n >>> 8;
+ n |= n >>> 16;
+ n++;
}
- return -1;
+ return n;
}
-}).call(this,require('_process'))
-},{"./_stream_duplex":162,"_process":64,"buffer":6,"core-util-is":167,"events":14,"inherits":168,"isarray":169,"stream":81,"string_decoder/":170,"util":3}],165:[function(require,module,exports){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+function howMuchToRead(n, state) {
+ if (state.length === 0 && state.ended)
+ return 0;
+
+ if (state.objectMode)
+ return n === 0 ? 0 : 1;
+
+ if (n === null || isNaN(n)) {
+ // only flow one buffer at a time
+ if (state.flowing && state.buffer.length)
+ return state.buffer[0].length;
+ else
+ return state.length;
+ }
+ if (n <= 0)
+ return 0;
-// a transform stream is a readable/writable stream where you do
-// something with the data. Sometimes it's called a "filter",
-// but that's not a great name for it, since that implies a thing where
-// some bits pass through, and others are simply ignored. (That would
-// be a valid example of a transform, of course.)
-//
-// While the output is causally related to the input, it's not a
-// necessarily symmetric or synchronous transformation. For example,
-// a zlib stream might take multiple plain-text writes(), and then
-// emit a single compressed chunk some time in the future.
-//
-// Here's how this works:
-//
-// The Transform stream has all the aspects of the readable and writable
-// stream classes. When you write(chunk), that calls _write(chunk,cb)
-// internally, and returns false if there's a lot of pending writes
-// buffered up. When you call read(), that calls _read(n) until
-// there's enough pending readable data buffered up.
-//
-// In a transform stream, the written data is placed in a buffer. When
-// _read(n) is called, it transforms the queued up data, calling the
-// buffered _write cb's as it consumes chunks. If consuming a single
-// written chunk would result in multiple output chunks, then the first
-// outputted bit calls the readcb, and subsequent chunks just go into
-// the read buffer, and will cause it to emit 'readable' if necessary.
-//
-// This way, back-pressure is actually determined by the reading side,
-// since _read has to be called to start processing a new chunk. However,
-// a pathological inflate type of transform can cause excessive buffering
-// here. For example, imagine a stream where every byte of input is
-// interpreted as an integer from 0-255, and then results in that many
-// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
-// 1kb of data being output. In this case, you could write a very small
-// amount of input, and end up with a very large amount of output. In
-// such a pathological inflating mechanism, there'd be no way to tell
-// the system to stop doing the transform. A single 4MB write could
-// cause the system to run out of memory.
-//
-// However, even in such a pathological case, only a single written chunk
-// would be consumed, and then the rest would wait (un-transformed) until
-// the results of the previous transformed chunk were consumed.
+ // If we're asking for more than the target buffer level,
+ // then raise the water mark. Bump up to the next highest
+ // power of 2, to prevent increasing it excessively in tiny
+ // amounts.
+ if (n > state.highWaterMark)
+ state.highWaterMark = computeNewHighWaterMark(n);
-module.exports = Transform;
+ // don't have that much. return null, unless we've ended.
+ if (n > state.length) {
+ if (!state.ended) {
+ state.needReadable = true;
+ return 0;
+ } else {
+ return state.length;
+ }
+ }
-var Duplex = require('./_stream_duplex');
+ return n;
+}
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+// you can override either this method, or the async _read(n) below.
+Readable.prototype.read = function(n) {
+ debug('read', n);
+ var state = this._readableState;
+ var nOrig = n;
-util.inherits(Transform, Duplex);
+ if (typeof n !== 'number' || n > 0)
+ state.emittedReadable = false;
+ // if we're doing read(0) to trigger a readable event, but we
+ // already have a bunch of data in the buffer, then just trigger
+ // the 'readable' event and move on.
+ if (n === 0 &&
+ state.needReadable &&
+ (state.length >= state.highWaterMark || state.ended)) {
+ debug('read: emitReadable', state.length, state.ended);
+ if (state.length === 0 && state.ended)
+ endReadable(this);
+ else
+ emitReadable(this);
+ return null;
+ }
-function TransformState(options, stream) {
- this.afterTransform = function(er, data) {
- return afterTransform(stream, er, data);
- };
+ n = howMuchToRead(n, state);
- this.needTransform = false;
- this.transforming = false;
- this.writecb = null;
- this.writechunk = null;
-}
+ // if we've ended, and we're now clear, then finish it up.
+ if (n === 0 && state.ended) {
+ if (state.length === 0)
+ endReadable(this);
+ return null;
+ }
-function afterTransform(stream, er, data) {
- var ts = stream._transformState;
- ts.transforming = false;
+ // All the actual chunk generation logic needs to be
+ // *below* the call to _read. The reason is that in certain
+ // synthetic stream cases, such as passthrough streams, _read
+ // may be a completely synchronous operation which may change
+ // the state of the read buffer, providing enough data when
+ // before there was *not* enough.
+ //
+ // So, the steps are:
+ // 1. Figure out what the state of things will be after we do
+ // a read from the buffer.
+ //
+ // 2. If that resulting state will trigger a _read, then call _read.
+ // Note that this may be asynchronous, or synchronous. Yes, it is
+ // deeply ugly to write APIs this way, but that still doesn't mean
+ // that the Readable class should behave improperly, as streams are
+ // designed to be sync/async agnostic.
+ // Take note if the _read call is sync or async (ie, if the read call
+ // has returned yet), so that we know whether or not it's safe to emit
+ // 'readable' etc.
+ //
+ // 3. Actually pull the requested chunks out of the buffer and return.
- var cb = ts.writecb;
+ // if we need a readable event, then we need to do some reading.
+ var doRead = state.needReadable;
+ debug('need readable', doRead);
- if (!cb)
- return stream.emit('error', new Error('no writecb in Transform class'));
+ // if we currently have less than the highWaterMark, then also read some
+ if (state.length === 0 || state.length - n < state.highWaterMark) {
+ doRead = true;
+ debug('length less than watermark', doRead);
+ }
- ts.writechunk = null;
- ts.writecb = null;
+ // however, if we've ended, then there's no point, and if we're already
+ // reading, then it's unnecessary.
+ if (state.ended || state.reading) {
+ doRead = false;
+ debug('reading or ended', doRead);
+ }
- if (!util.isNullOrUndefined(data))
- stream.push(data);
+ if (doRead) {
+ debug('do read');
+ state.reading = true;
+ state.sync = true;
+ // if the length is currently zero, then we *need* a readable event.
+ if (state.length === 0)
+ state.needReadable = true;
+ // call internal read method
+ this._read(state.highWaterMark);
+ state.sync = false;
+ }
- if (cb)
- cb(er);
+ // If _read pushed data synchronously, then `reading` will be false,
+ // and we need to re-evaluate how much data we can return to the user.
+ if (doRead && !state.reading)
+ n = howMuchToRead(nOrig, state);
- var rs = stream._readableState;
- rs.reading = false;
- if (rs.needReadable || rs.length < rs.highWaterMark) {
- stream._read(rs.highWaterMark);
+ var ret;
+ if (n > 0)
+ ret = fromList(n, state);
+ else
+ ret = null;
+
+ if (ret === null) {
+ state.needReadable = true;
+ n = 0;
}
-}
+ state.length -= n;
-function Transform(options) {
- if (!(this instanceof Transform))
- return new Transform(options);
+ // If we have nothing in the buffer, then we want to know
+ // as soon as we *do* get something into the buffer.
+ if (state.length === 0 && !state.ended)
+ state.needReadable = true;
- Duplex.call(this, options);
+ // If we tried to read() past the EOF, then emit end on the next tick.
+ if (nOrig !== n && state.ended && state.length === 0)
+ endReadable(this);
- this._transformState = new TransformState(options, this);
+ if (ret !== null)
+ this.emit('data', ret);
- // when the writable side finishes, then flush out anything remaining.
- var stream = this;
+ return ret;
+};
- // start out asking for a readable event once data is transformed.
- this._readableState.needReadable = true;
+function chunkInvalid(state, chunk) {
+ var er = null;
+ if (!(Buffer.isBuffer(chunk)) &&
+ typeof chunk !== 'string' &&
+ chunk !== null &&
+ chunk !== undefined &&
+ !state.objectMode) {
+ er = new TypeError('Invalid non-string/buffer chunk');
+ }
+ return er;
+}
- // we have implemented the _read method, and done the other things
- // that Readable wants before the first _read call, so unset the
- // sync guard flag.
- this._readableState.sync = false;
- this.once('prefinish', function() {
- if (util.isFunction(this._flush))
- this._flush(function(er) {
- done(stream, er);
- });
+function onEofChunk(stream, state) {
+ if (state.ended) return;
+ if (state.decoder) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length) {
+ state.buffer.push(chunk);
+ state.length += state.objectMode ? 1 : chunk.length;
+ }
+ }
+ state.ended = true;
+
+ // emit 'readable' now to make sure it gets picked up.
+ emitReadable(stream);
+}
+
+// Don't emit readable right away in sync mode, because this can trigger
+// another read() call => stack overflow. This way, it might trigger
+// a nextTick recursion warning, but that's not so bad.
+function emitReadable(stream) {
+ var state = stream._readableState;
+ state.needReadable = false;
+ if (!state.emittedReadable) {
+ debug('emitReadable', state.flowing);
+ state.emittedReadable = true;
+ if (state.sync)
+ processNextTick(emitReadable_, stream);
else
- done(stream);
- });
+ emitReadable_(stream);
+ }
}
-Transform.prototype.push = function(chunk, encoding) {
- this._transformState.needTransform = false;
- return Duplex.prototype.push.call(this, chunk, encoding);
-};
+function emitReadable_(stream) {
+ debug('emit readable');
+ stream.emit('readable');
+ flow(stream);
+}
-// This is the part where you do stuff!
-// override this function in implementation classes.
-// 'chunk' is an input chunk.
-//
-// Call `push(newChunk)` to pass along transformed output
-// to the readable side. You may call 'push' zero or more times.
-//
-// Call `cb(err)` when you are done with this chunk. If you pass
-// an error, then that'll put the hurt on the whole operation. If you
-// never call cb(), then you'll never get another chunk.
-Transform.prototype._transform = function(chunk, encoding, cb) {
- throw new Error('not implemented');
-};
-Transform.prototype._write = function(chunk, encoding, cb) {
- var ts = this._transformState;
- ts.writecb = cb;
- ts.writechunk = chunk;
- ts.writeencoding = encoding;
- if (!ts.transforming) {
- var rs = this._readableState;
- if (ts.needTransform ||
- rs.needReadable ||
- rs.length < rs.highWaterMark)
- this._read(rs.highWaterMark);
+// at this point, the user has presumably seen the 'readable' event,
+// and called read() to consume some data. that may have triggered
+// in turn another _read(n) call, in which case reading = true if
+// it's in progress.
+// However, if we're not ended, or reading, and the length < hwm,
+// then go ahead and try to read some more preemptively.
+function maybeReadMore(stream, state) {
+ if (!state.readingMore) {
+ state.readingMore = true;
+ processNextTick(maybeReadMore_, stream, state);
}
-};
-
-// Doesn't matter what the args are here.
-// _transform does all the work.
-// That we got here means that the readable side wants more data.
-Transform.prototype._read = function(n) {
- var ts = this._transformState;
+}
- if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
- ts.transforming = true;
- this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
- } else {
- // mark that we need a transform, so that any data that comes in
- // will get processed, now that we've asked for it.
- ts.needTransform = true;
+function maybeReadMore_(stream, state) {
+ var len = state.length;
+ while (!state.reading && !state.flowing && !state.ended &&
+ state.length < state.highWaterMark) {
+ debug('maybeReadMore read 0');
+ stream.read(0);
+ if (len === state.length)
+ // didn't get any data, stop spinning.
+ break;
+ else
+ len = state.length;
}
-};
+ state.readingMore = false;
+}
+// abstract method. to be overridden in specific implementation classes.
+// call cb(er, data) where data is <= n in length.
+// for virtual (non-string, non-buffer) streams, "length" is somewhat
+// arbitrary, and perhaps not very meaningful.
+Readable.prototype._read = function(n) {
+ this.emit('error', new Error('not implemented'));
+};
-function done(stream, er) {
- if (er)
- return stream.emit('error', er);
+Readable.prototype.pipe = function(dest, pipeOpts) {
+ var src = this;
+ var state = this._readableState;
- // if there's nothing in the write buffer, then that means
- // that nothing more will ever be provided
- var ws = stream._writableState;
- var ts = stream._transformState;
+ switch (state.pipesCount) {
+ case 0:
+ state.pipes = dest;
+ break;
+ case 1:
+ state.pipes = [state.pipes, dest];
+ break;
+ default:
+ state.pipes.push(dest);
+ break;
+ }
+ state.pipesCount += 1;
+ debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
- if (ws.length)
- throw new Error('calling transform done when ws.length != 0');
+ var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
+ dest !== process.stdout &&
+ dest !== process.stderr;
- if (ts.transforming)
- throw new Error('calling transform done when still transforming');
+ var endFn = doEnd ? onend : cleanup;
+ if (state.endEmitted)
+ processNextTick(endFn);
+ else
+ src.once('end', endFn);
- return stream.push(null);
-}
+ dest.on('unpipe', onunpipe);
+ function onunpipe(readable) {
+ debug('onunpipe');
+ if (readable === src) {
+ cleanup();
+ }
+ }
-},{"./_stream_duplex":162,"core-util-is":167,"inherits":168}],166:[function(require,module,exports){
-(function (process){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+ function onend() {
+ debug('onend');
+ dest.end();
+ }
-// A bit simpler than readable streams.
-// Implement an async ._write(chunk, cb), and it'll handle all
-// the drain event emission and buffering.
+ // when the dest drains, it reduces the awaitDrain counter
+ // on the source. This would be more elegant with a .once()
+ // handler in flow(), but adding and removing repeatedly is
+ // too slow.
+ var ondrain = pipeOnDrain(src);
+ dest.on('drain', ondrain);
-module.exports = Writable;
+ function cleanup() {
+ debug('cleanup');
+ // cleanup event handlers once the pipe is broken
+ dest.removeListener('close', onclose);
+ dest.removeListener('finish', onfinish);
+ dest.removeListener('drain', ondrain);
+ dest.removeListener('error', onerror);
+ dest.removeListener('unpipe', onunpipe);
+ src.removeListener('end', onend);
+ src.removeListener('end', cleanup);
+ src.removeListener('data', ondata);
-/**/
-var Buffer = require('buffer').Buffer;
-/**/
+ // if the reader is waiting for a drain event from this
+ // specific writer, then it would cause it to never start
+ // flowing again.
+ // So, if this is awaiting a drain, then we just call it now.
+ // If we don't know, then assume that we are waiting for one.
+ if (state.awaitDrain &&
+ (!dest._writableState || dest._writableState.needDrain))
+ ondrain();
+ }
-Writable.WritableState = WritableState;
+ src.on('data', ondata);
+ function ondata(chunk) {
+ debug('ondata');
+ var ret = dest.write(chunk);
+ if (false === ret) {
+ debug('false write response, pause',
+ src._readableState.awaitDrain);
+ src._readableState.awaitDrain++;
+ src.pause();
+ }
+ }
+ // if the dest has an error, then stop piping into it.
+ // however, don't suppress the throwing behavior for this.
+ function onerror(er) {
+ debug('onerror', er);
+ unpipe();
+ dest.removeListener('error', onerror);
+ if (EElistenerCount(dest, 'error') === 0)
+ dest.emit('error', er);
+ }
+ // This is a brutally ugly hack to make sure that our error handler
+ // is attached before any userland ones. NEVER DO THIS.
+ if (!dest._events || !dest._events.error)
+ dest.on('error', onerror);
+ else if (isArray(dest._events.error))
+ dest._events.error.unshift(onerror);
+ else
+ dest._events.error = [onerror, dest._events.error];
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
-var Stream = require('stream');
+ // Both close and finish should trigger unpipe, but only once.
+ function onclose() {
+ dest.removeListener('finish', onfinish);
+ unpipe();
+ }
+ dest.once('close', onclose);
+ function onfinish() {
+ debug('onfinish');
+ dest.removeListener('close', onclose);
+ unpipe();
+ }
+ dest.once('finish', onfinish);
-util.inherits(Writable, Stream);
+ function unpipe() {
+ debug('unpipe');
+ src.unpipe(dest);
+ }
-function WriteReq(chunk, encoding, cb) {
- this.chunk = chunk;
- this.encoding = encoding;
- this.callback = cb;
-}
+ // tell the dest that it's being piped to
+ dest.emit('pipe', src);
-function WritableState(options, stream) {
- var Duplex = require('./_stream_duplex');
+ // start the flow if it hasn't been started already.
+ if (!state.flowing) {
+ debug('pipe resume');
+ src.resume();
+ }
- options = options || {};
+ return dest;
+};
- // the point at which write() starts returning false
- // Note: 0 is a valid value, means that we always return false if
- // the entire buffer is not flushed immediately on write()
- var hwm = options.highWaterMark;
- var defaultHwm = options.objectMode ? 16 : 16 * 1024;
- this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
+function pipeOnDrain(src) {
+ return function() {
+ var state = src._readableState;
+ debug('pipeOnDrain', state.awaitDrain);
+ if (state.awaitDrain)
+ state.awaitDrain--;
+ if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
+ state.flowing = true;
+ flow(src);
+ }
+ };
+}
- // object stream flag to indicate whether or not this stream
- // contains buffers or objects.
- this.objectMode = !!options.objectMode;
- if (stream instanceof Duplex)
- this.objectMode = this.objectMode || !!options.writableObjectMode;
+Readable.prototype.unpipe = function(dest) {
+ var state = this._readableState;
- // cast to ints.
- this.highWaterMark = ~~this.highWaterMark;
+ // if we're not piping anywhere, then do nothing.
+ if (state.pipesCount === 0)
+ return this;
- this.needDrain = false;
- // at the start of calling end()
- this.ending = false;
- // when end() has been called, and returned
- this.ended = false;
- // when 'finish' is emitted
- this.finished = false;
+ // just one destination. most common case.
+ if (state.pipesCount === 1) {
+ // passed in one, but it's not the right one.
+ if (dest && dest !== state.pipes)
+ return this;
- // should we decode strings into buffers before passing to _write?
- // this is here so that some node-core streams can optimize string
- // handling at a lower level.
- var noDecode = options.decodeStrings === false;
- this.decodeStrings = !noDecode;
+ if (!dest)
+ dest = state.pipes;
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
+ // got a match.
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+ if (dest)
+ dest.emit('unpipe', this);
+ return this;
+ }
- // not an actual buffer we keep track of, but a measurement
- // of how much we're waiting to get pushed to some underlying
- // socket or file.
- this.length = 0;
+ // slow case. multiple pipe destinations.
- // a flag to see when we're in the middle of a write.
- this.writing = false;
+ if (!dest) {
+ // remove all.
+ var dests = state.pipes;
+ var len = state.pipesCount;
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
- // when true all writes will be buffered until .uncork() call
- this.corked = 0;
+ for (var i = 0; i < len; i++)
+ dests[i].emit('unpipe', this);
+ return this;
+ }
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
+ // try to find the right one.
+ var i = indexOf(state.pipes, dest);
+ if (i === -1)
+ return this;
- // a flag to know if we're processing previously buffered items, which
- // may call the _write() callback in the same tick, so that we don't
- // end up in an overlapped onwrite situation.
- this.bufferProcessing = false;
+ state.pipes.splice(i, 1);
+ state.pipesCount -= 1;
+ if (state.pipesCount === 1)
+ state.pipes = state.pipes[0];
- // the callback that's passed to _write(chunk,cb)
- this.onwrite = function(er) {
- onwrite(stream, er);
- };
+ dest.emit('unpipe', this);
- // the callback that the user supplies to write(chunk,encoding,cb)
- this.writecb = null;
+ return this;
+};
- // the amount that is being written when _write is called.
- this.writelen = 0;
+// set up data events if they are asked for
+// Ensure readable listeners eventually get something
+Readable.prototype.on = function(ev, fn) {
+ var res = Stream.prototype.on.call(this, ev, fn);
- this.buffer = [];
+ // If listening to data, and it has not explicitly been paused,
+ // then call resume to start the flow of data on the next tick.
+ if (ev === 'data' && false !== this._readableState.flowing) {
+ this.resume();
+ }
- // number of pending user-supplied write callbacks
- // this must be 0 before 'finish' can be emitted
- this.pendingcb = 0;
+ if (ev === 'readable' && this.readable) {
+ var state = this._readableState;
+ if (!state.readableListening) {
+ state.readableListening = true;
+ state.emittedReadable = false;
+ state.needReadable = true;
+ if (!state.reading) {
+ processNextTick(nReadingNextTick, this);
+ } else if (state.length) {
+ emitReadable(this, state);
+ }
+ }
+ }
- // emit prefinish if the only thing we're waiting for is _write cbs
- // This is relevant for synchronous Transform streams
- this.prefinished = false;
+ return res;
+};
+Readable.prototype.addListener = Readable.prototype.on;
- // True if the error was already emitted and should not be thrown again
- this.errorEmitted = false;
+function nReadingNextTick(self) {
+ debug('readable nexttick read 0');
+ self.read(0);
}
-function Writable(options) {
- var Duplex = require('./_stream_duplex');
-
- // Writable ctor is applied to Duplexes, though they're not
- // instanceof Writable, they're instanceof Readable.
- if (!(this instanceof Writable) && !(this instanceof Duplex))
- return new Writable(options);
+// pause() and resume() are remnants of the legacy readable stream API
+// If the user uses them, then switch into old mode.
+Readable.prototype.resume = function() {
+ var state = this._readableState;
+ if (!state.flowing) {
+ debug('resume');
+ state.flowing = true;
+ resume(this, state);
+ }
+ return this;
+};
- this._writableState = new WritableState(options, this);
+function resume(stream, state) {
+ if (!state.resumeScheduled) {
+ state.resumeScheduled = true;
+ processNextTick(resume_, stream, state);
+ }
+}
- // legacy.
- this.writable = true;
+function resume_(stream, state) {
+ if (!state.reading) {
+ debug('resume read 0');
+ stream.read(0);
+ }
- Stream.call(this);
+ state.resumeScheduled = false;
+ stream.emit('resume');
+ flow(stream);
+ if (state.flowing && !state.reading)
+ stream.read(0);
}
-// Otherwise people can pipe Writable streams, which is just wrong.
-Writable.prototype.pipe = function() {
- this.emit('error', new Error('Cannot pipe. Not readable.'));
+Readable.prototype.pause = function() {
+ debug('call pause flowing=%j', this._readableState.flowing);
+ if (false !== this._readableState.flowing) {
+ debug('pause');
+ this._readableState.flowing = false;
+ this.emit('pause');
+ }
+ return this;
};
-
-function writeAfterEnd(stream, state, cb) {
- var er = new Error('write after end');
- // TODO: defer error events consistently everywhere, not just the cb
- stream.emit('error', er);
- process.nextTick(function() {
- cb(er);
- });
-}
-
-// If we get something that is not a buffer, string, null, or undefined,
-// and we're not in objectMode, then that's an error.
-// Otherwise stream chunks are all considered to be of length=1, and the
-// watermarks determine how many objects to keep in the buffer, rather than
-// how many bytes or characters.
-function validChunk(stream, state, chunk, cb) {
- var valid = true;
- if (!util.isBuffer(chunk) &&
- !util.isString(chunk) &&
- !util.isNullOrUndefined(chunk) &&
- !state.objectMode) {
- var er = new TypeError('Invalid non-string/buffer chunk');
- stream.emit('error', er);
- process.nextTick(function() {
- cb(er);
- });
- valid = false;
+function flow(stream) {
+ var state = stream._readableState;
+ debug('flow', state.flowing);
+ if (state.flowing) {
+ do {
+ var chunk = stream.read();
+ } while (null !== chunk && state.flowing);
}
- return valid;
}
-Writable.prototype.write = function(chunk, encoding, cb) {
- var state = this._writableState;
- var ret = false;
+// wrap an old-style stream as the async data source.
+// This is *not* part of the readable stream interface.
+// It is an ugly unfortunate mess of history.
+Readable.prototype.wrap = function(stream) {
+ var state = this._readableState;
+ var paused = false;
- if (util.isFunction(encoding)) {
- cb = encoding;
- encoding = null;
- }
+ var self = this;
+ stream.on('end', function() {
+ debug('wrapped end');
+ if (state.decoder && !state.ended) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length)
+ self.push(chunk);
+ }
- if (util.isBuffer(chunk))
- encoding = 'buffer';
- else if (!encoding)
- encoding = state.defaultEncoding;
+ self.push(null);
+ });
- if (!util.isFunction(cb))
- cb = function() {};
+ stream.on('data', function(chunk) {
+ debug('wrapped data');
+ if (state.decoder)
+ chunk = state.decoder.write(chunk);
+
+ // don't skip over falsy values in objectMode
+ if (state.objectMode && (chunk === null || chunk === undefined))
+ return;
+ else if (!state.objectMode && (!chunk || !chunk.length))
+ return;
+
+ var ret = self.push(chunk);
+ if (!ret) {
+ paused = true;
+ stream.pause();
+ }
+ });
- if (state.ended)
- writeAfterEnd(this, state, cb);
- else if (validChunk(this, state, chunk, cb)) {
- state.pendingcb++;
- ret = writeOrBuffer(this, state, chunk, encoding, cb);
+ // proxy all the other methods.
+ // important when wrapping filters and duplexes.
+ for (var i in stream) {
+ if (this[i] === undefined && typeof stream[i] === 'function') {
+ this[i] = function(method) { return function() {
+ return stream[method].apply(stream, arguments);
+ }; }(i);
+ }
}
- return ret;
-};
+ // proxy certain important events.
+ var events = ['error', 'close', 'destroy', 'pause', 'resume'];
+ forEach(events, function(ev) {
+ stream.on(ev, self.emit.bind(self, ev));
+ });
-Writable.prototype.cork = function() {
- var state = this._writableState;
+ // when we try to consume some more bytes, simply unpause the
+ // underlying stream.
+ self._read = function(n) {
+ debug('wrapped _read', n);
+ if (paused) {
+ paused = false;
+ stream.resume();
+ }
+ };
- state.corked++;
+ return self;
};
-Writable.prototype.uncork = function() {
- var state = this._writableState;
- if (state.corked) {
- state.corked--;
+// exposed for testing purposes only.
+Readable._fromList = fromList;
- if (!state.writing &&
- !state.corked &&
- !state.finished &&
- !state.bufferProcessing &&
- state.buffer.length)
- clearBuffer(this, state);
- }
-};
+// Pluck off n bytes from an array of buffers.
+// Length is the combined lengths of all the buffers in the list.
+function fromList(n, state) {
+ var list = state.buffer;
+ var length = state.length;
+ var stringMode = !!state.decoder;
+ var objectMode = !!state.objectMode;
+ var ret;
-function decodeChunk(state, chunk, encoding) {
- if (!state.objectMode &&
- state.decodeStrings !== false &&
- util.isString(chunk)) {
- chunk = new Buffer(chunk, encoding);
- }
- return chunk;
-}
+ // nothing in the list, definitely empty.
+ if (list.length === 0)
+ return null;
-// if we're already writing something, then just put this
-// in the queue, and wait our turn. Otherwise, call _write
-// If we return false, then we need a drain event, so set that flag.
-function writeOrBuffer(stream, state, chunk, encoding, cb) {
- chunk = decodeChunk(state, chunk, encoding);
- if (util.isBuffer(chunk))
- encoding = 'buffer';
- var len = state.objectMode ? 1 : chunk.length;
+ if (length === 0)
+ ret = null;
+ else if (objectMode)
+ ret = list.shift();
+ else if (!n || n >= length) {
+ // read it all, truncate the array.
+ if (stringMode)
+ ret = list.join('');
+ else
+ ret = Buffer.concat(list, length);
+ list.length = 0;
+ } else {
+ // read just some of it.
+ if (n < list[0].length) {
+ // just take a part of the first list item.
+ // slice is the same for buffers and strings.
+ var buf = list[0];
+ ret = buf.slice(0, n);
+ list[0] = buf.slice(n);
+ } else if (n === list[0].length) {
+ // first list is a perfect match
+ ret = list.shift();
+ } else {
+ // complex case.
+ // we have enough to cover it, but it spans past the first buffer.
+ if (stringMode)
+ ret = '';
+ else
+ ret = new Buffer(n);
- state.length += len;
+ var c = 0;
+ for (var i = 0, l = list.length; i < l && c < n; i++) {
+ var buf = list[0];
+ var cpy = Math.min(n - c, buf.length);
- var ret = state.length < state.highWaterMark;
- // we must ensure that previous needDrain will not be reset to false.
- if (!ret)
- state.needDrain = true;
+ if (stringMode)
+ ret += buf.slice(0, cpy);
+ else
+ buf.copy(ret, c, 0, cpy);
- if (state.writing || state.corked)
- state.buffer.push(new WriteReq(chunk, encoding, cb));
- else
- doWrite(stream, state, false, len, chunk, encoding, cb);
+ if (cpy < buf.length)
+ list[0] = buf.slice(cpy);
+ else
+ list.shift();
+
+ c += cpy;
+ }
+ }
+ }
return ret;
}
-function doWrite(stream, state, writev, len, chunk, encoding, cb) {
- state.writelen = len;
- state.writecb = cb;
- state.writing = true;
- state.sync = true;
- if (writev)
- stream._writev(chunk, state.onwrite);
- else
- stream._write(chunk, encoding, state.onwrite);
- state.sync = false;
-}
+function endReadable(stream) {
+ var state = stream._readableState;
-function onwriteError(stream, state, sync, er, cb) {
- if (sync)
- process.nextTick(function() {
- state.pendingcb--;
- cb(er);
- });
- else {
- state.pendingcb--;
- cb(er);
- }
+ // If we get here before consuming all the bytes, then that is a
+ // bug in node. Should never happen.
+ if (state.length > 0)
+ throw new Error('endReadable called on non-empty stream');
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
+ if (!state.endEmitted) {
+ state.ended = true;
+ processNextTick(endReadableNT, state, stream);
+ }
}
-function onwriteStateUpdate(state) {
- state.writing = false;
- state.writecb = null;
- state.length -= state.writelen;
- state.writelen = 0;
+function endReadableNT(state, stream) {
+ // Check that we didn't get one last unshift.
+ if (!state.endEmitted && state.length === 0) {
+ state.endEmitted = true;
+ stream.readable = false;
+ stream.emit('end');
+ }
}
-function onwrite(stream, er) {
- var state = stream._writableState;
- var sync = state.sync;
- var cb = state.writecb;
-
- onwriteStateUpdate(state);
-
- if (er)
- onwriteError(stream, state, sync, er, cb);
- else {
- // Check if we're actually ready to finish, but don't emit yet
- var finished = needFinish(stream, state);
-
- if (!finished &&
- !state.corked &&
- !state.bufferProcessing &&
- state.buffer.length) {
- clearBuffer(stream, state);
- }
-
- if (sync) {
- process.nextTick(function() {
- afterWrite(stream, state, finished, cb);
- });
- } else {
- afterWrite(stream, state, finished, cb);
- }
+function forEach (xs, f) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ f(xs[i], i);
}
}
-function afterWrite(stream, state, finished, cb) {
- if (!finished)
- onwriteDrain(stream, state);
- state.pendingcb--;
- cb();
- finishMaybe(stream, state);
+function indexOf (xs, x) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ if (xs[i] === x) return i;
+ }
+ return -1;
}
-// Must force callback to be called on nextTick, so that we don't
-// emit 'drain' before the write() consumer gets the 'false' return
-// value, and has a chance to attach a 'drain' listener.
-function onwriteDrain(stream, state) {
- if (state.length === 0 && state.needDrain) {
- state.needDrain = false;
- stream.emit('drain');
- }
-}
+}).call(this,require('_process'))
+},{"./_stream_duplex":113,"_process":107,"buffer":8,"core-util-is":15,"events":18,"inherits":47,"isarray":53,"process-nextick-args":106,"string_decoder/":129,"util":5}],116:[function(require,module,exports){
+// a transform stream is a readable/writable stream where you do
+// something with the data. Sometimes it's called a "filter",
+// but that's not a great name for it, since that implies a thing where
+// some bits pass through, and others are simply ignored. (That would
+// be a valid example of a transform, of course.)
+//
+// While the output is causally related to the input, it's not a
+// necessarily symmetric or synchronous transformation. For example,
+// a zlib stream might take multiple plain-text writes(), and then
+// emit a single compressed chunk some time in the future.
+//
+// Here's how this works:
+//
+// The Transform stream has all the aspects of the readable and writable
+// stream classes. When you write(chunk), that calls _write(chunk,cb)
+// internally, and returns false if there's a lot of pending writes
+// buffered up. When you call read(), that calls _read(n) until
+// there's enough pending readable data buffered up.
+//
+// In a transform stream, the written data is placed in a buffer. When
+// _read(n) is called, it transforms the queued up data, calling the
+// buffered _write cb's as it consumes chunks. If consuming a single
+// written chunk would result in multiple output chunks, then the first
+// outputted bit calls the readcb, and subsequent chunks just go into
+// the read buffer, and will cause it to emit 'readable' if necessary.
+//
+// This way, back-pressure is actually determined by the reading side,
+// since _read has to be called to start processing a new chunk. However,
+// a pathological inflate type of transform can cause excessive buffering
+// here. For example, imagine a stream where every byte of input is
+// interpreted as an integer from 0-255, and then results in that many
+// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
+// 1kb of data being output. In this case, you could write a very small
+// amount of input, and end up with a very large amount of output. In
+// such a pathological inflating mechanism, there'd be no way to tell
+// the system to stop doing the transform. A single 4MB write could
+// cause the system to run out of memory.
+//
+// However, even in such a pathological case, only a single written chunk
+// would be consumed, and then the rest would wait (un-transformed) until
+// the results of the previous transformed chunk were consumed.
+
+'use strict';
+module.exports = Transform;
-// if there's something in the buffer waiting, then process it
-function clearBuffer(stream, state) {
- state.bufferProcessing = true;
+var Duplex = require('./_stream_duplex');
- if (stream._writev && state.buffer.length > 1) {
- // Fast case, write everything using _writev()
- var cbs = [];
- for (var c = 0; c < state.buffer.length; c++)
- cbs.push(state.buffer[c].callback);
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
- // count the one we are adding, as well.
- // TODO(isaacs) clean this up
- state.pendingcb++;
- doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
- for (var i = 0; i < cbs.length; i++) {
- state.pendingcb--;
- cbs[i](err);
- }
- });
+util.inherits(Transform, Duplex);
- // Clear buffer
- state.buffer = [];
- } else {
- // Slow case, write chunks one-by-one
- for (var c = 0; c < state.buffer.length; c++) {
- var entry = state.buffer[c];
- var chunk = entry.chunk;
- var encoding = entry.encoding;
- var cb = entry.callback;
- var len = state.objectMode ? 1 : chunk.length;
- doWrite(stream, state, false, len, chunk, encoding, cb);
+function TransformState(stream) {
+ this.afterTransform = function(er, data) {
+ return afterTransform(stream, er, data);
+ };
- // if we didn't call the onwrite immediately, then
- // it means that we need to wait until it does.
- // also, that means that the chunk and cb are currently
- // being processed, so move the buffer counter past them.
- if (state.writing) {
- c++;
- break;
- }
- }
+ this.needTransform = false;
+ this.transforming = false;
+ this.writecb = null;
+ this.writechunk = null;
+}
- if (c < state.buffer.length)
- state.buffer = state.buffer.slice(c);
- else
- state.buffer.length = 0;
- }
+function afterTransform(stream, er, data) {
+ var ts = stream._transformState;
+ ts.transforming = false;
- state.bufferProcessing = false;
-}
+ var cb = ts.writecb;
-Writable.prototype._write = function(chunk, encoding, cb) {
- cb(new Error('not implemented'));
+ if (!cb)
+ return stream.emit('error', new Error('no writecb in Transform class'));
-};
+ ts.writechunk = null;
+ ts.writecb = null;
-Writable.prototype._writev = null;
+ if (data !== null && data !== undefined)
+ stream.push(data);
-Writable.prototype.end = function(chunk, encoding, cb) {
- var state = this._writableState;
+ if (cb)
+ cb(er);
- if (util.isFunction(chunk)) {
- cb = chunk;
- chunk = null;
- encoding = null;
- } else if (util.isFunction(encoding)) {
- cb = encoding;
- encoding = null;
+ var rs = stream._readableState;
+ rs.reading = false;
+ if (rs.needReadable || rs.length < rs.highWaterMark) {
+ stream._read(rs.highWaterMark);
}
+}
- if (!util.isNullOrUndefined(chunk))
- this.write(chunk, encoding);
- // .end() fully uncorks
- if (state.corked) {
- state.corked = 1;
- this.uncork();
- }
+function Transform(options) {
+ if (!(this instanceof Transform))
+ return new Transform(options);
- // ignore unnecessary end() calls.
- if (!state.ending && !state.finished)
- endWritable(this, state, cb);
-};
+ Duplex.call(this, options);
+ this._transformState = new TransformState(this);
-function needFinish(stream, state) {
- return (state.ending &&
- state.length === 0 &&
- !state.finished &&
- !state.writing);
-}
+ // when the writable side finishes, then flush out anything remaining.
+ var stream = this;
-function prefinish(stream, state) {
- if (!state.prefinished) {
- state.prefinished = true;
- stream.emit('prefinish');
- }
-}
+ // start out asking for a readable event once data is transformed.
+ this._readableState.needReadable = true;
-function finishMaybe(stream, state) {
- var need = needFinish(stream, state);
- if (need) {
- if (state.pendingcb === 0) {
- prefinish(stream, state);
- state.finished = true;
- stream.emit('finish');
- } else
- prefinish(stream, state);
+ // we have implemented the _read method, and done the other things
+ // that Readable wants before the first _read call, so unset the
+ // sync guard flag.
+ this._readableState.sync = false;
+
+ if (options) {
+ if (typeof options.transform === 'function')
+ this._transform = options.transform;
+
+ if (typeof options.flush === 'function')
+ this._flush = options.flush;
}
- return need;
-}
-function endWritable(stream, state, cb) {
- state.ending = true;
- finishMaybe(stream, state);
- if (cb) {
- if (state.finished)
- process.nextTick(cb);
+ this.once('prefinish', function() {
+ if (typeof this._flush === 'function')
+ this._flush(function(er) {
+ done(stream, er);
+ });
else
- stream.once('finish', cb);
- }
- state.ended = true;
+ done(stream);
+ });
}
-}).call(this,require('_process'))
-},{"./_stream_duplex":162,"_process":64,"buffer":6,"core-util-is":167,"inherits":168,"stream":81}],167:[function(require,module,exports){
-arguments[4][11][0].apply(exports,arguments)
-},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21,"dup":11}],168:[function(require,module,exports){
-arguments[4][18][0].apply(exports,arguments)
-},{"dup":18}],169:[function(require,module,exports){
-arguments[4][22][0].apply(exports,arguments)
-},{"dup":22}],170:[function(require,module,exports){
-arguments[4][86][0].apply(exports,arguments)
-},{"buffer":6,"dup":86}],171:[function(require,module,exports){
-exports = module.exports = require('./lib/_stream_readable.js');
-exports.Stream = require('stream');
-exports.Readable = exports;
-exports.Writable = require('./lib/_stream_writable.js');
-exports.Duplex = require('./lib/_stream_duplex.js');
-exports.Transform = require('./lib/_stream_transform.js');
-exports.PassThrough = require('./lib/_stream_passthrough.js');
+Transform.prototype.push = function(chunk, encoding) {
+ this._transformState.needTransform = false;
+ return Duplex.prototype.push.call(this, chunk, encoding);
+};
-},{"./lib/_stream_duplex.js":162,"./lib/_stream_passthrough.js":163,"./lib/_stream_readable.js":164,"./lib/_stream_transform.js":165,"./lib/_stream_writable.js":166,"stream":81}],172:[function(require,module,exports){
-arguments[4][162][0].apply(exports,arguments)
-},{"./_stream_readable":173,"./_stream_writable":175,"_process":64,"core-util-is":176,"dup":162,"inherits":177}],173:[function(require,module,exports){
-(function (process){
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
+// This is the part where you do stuff!
+// override this function in implementation classes.
+// 'chunk' is an input chunk.
//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
+// Call `push(newChunk)` to pass along transformed output
+// to the readable side. You may call 'push' zero or more times.
//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+// Call `cb(err)` when you are done with this chunk. If you pass
+// an error, then that'll put the hurt on the whole operation. If you
+// never call cb(), then you'll never get another chunk.
+Transform.prototype._transform = function(chunk, encoding, cb) {
+ throw new Error('not implemented');
+};
+
+Transform.prototype._write = function(chunk, encoding, cb) {
+ var ts = this._transformState;
+ ts.writecb = cb;
+ ts.writechunk = chunk;
+ ts.writeencoding = encoding;
+ if (!ts.transforming) {
+ var rs = this._readableState;
+ if (ts.needTransform ||
+ rs.needReadable ||
+ rs.length < rs.highWaterMark)
+ this._read(rs.highWaterMark);
+ }
+};
+
+// Doesn't matter what the args are here.
+// _transform does all the work.
+// That we got here means that the readable side wants more data.
+Transform.prototype._read = function(n) {
+ var ts = this._transformState;
+
+ if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
+ ts.transforming = true;
+ this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
+ } else {
+ // mark that we need a transform, so that any data that comes in
+ // will get processed, now that we've asked for it.
+ ts.needTransform = true;
+ }
+};
+
+
+function done(stream, er) {
+ if (er)
+ return stream.emit('error', er);
+
+ // if there's nothing in the write buffer, then that means
+ // that nothing more will ever be provided
+ var ws = stream._writableState;
+ var ts = stream._transformState;
-module.exports = Readable;
+ if (ws.length)
+ throw new Error('calling transform done when ws.length != 0');
+
+ if (ts.transforming)
+ throw new Error('calling transform done when still transforming');
+
+ return stream.push(null);
+}
+
+},{"./_stream_duplex":113,"core-util-is":15,"inherits":47}],117:[function(require,module,exports){
+// A bit simpler than readable streams.
+// Implement an async ._write(chunk, cb), and it'll handle all
+// the drain event emission and buffering.
+
+'use strict';
+
+module.exports = Writable;
/**/
-var isArray = require('isarray');
+var processNextTick = require('process-nextick-args');
/**/
@@ -18232,959 +16694,1365 @@ var isArray = require('isarray');
var Buffer = require('buffer').Buffer;
/**/
-Readable.ReadableState = ReadableState;
+Writable.WritableState = WritableState;
-var EE = require('events').EventEmitter;
/**/
-if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
- return emitter.listeners(type).length;
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
+
+
+/**/
+var internalUtil = {
+ deprecate: require('util-deprecate')
};
/**/
-var Stream = require('stream');
+
/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
+var Stream;
+(function (){try{
+ Stream = require('st' + 'ream');
+}catch(_){}finally{
+ if (!Stream)
+ Stream = require('events').EventEmitter;
+}}())
/**/
-var StringDecoder;
+var Buffer = require('buffer').Buffer;
-util.inherits(Readable, Stream);
+util.inherits(Writable, Stream);
+
+function nop() {}
+
+function WriteReq(chunk, encoding, cb) {
+ this.chunk = chunk;
+ this.encoding = encoding;
+ this.callback = cb;
+ this.next = null;
+}
+
+function WritableState(options, stream) {
+ var Duplex = require('./_stream_duplex');
-function ReadableState(options, stream) {
options = options || {};
- // the point at which it stops calling _read() to fill the buffer
- // Note: 0 is a valid value, means "don't call _read preemptively ever"
+ // object stream flag to indicate whether or not this stream
+ // contains buffers or objects.
+ this.objectMode = !!options.objectMode;
+
+ if (stream instanceof Duplex)
+ this.objectMode = this.objectMode || !!options.writableObjectMode;
+
+ // the point at which write() starts returning false
+ // Note: 0 is a valid value, means that we always return false if
+ // the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
- this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
+ var defaultHwm = this.objectMode ? 16 : 16 * 1024;
+ this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
- this.buffer = [];
- this.length = 0;
- this.pipes = null;
- this.pipesCount = 0;
- this.flowing = false;
+ this.needDrain = false;
+ // at the start of calling end()
+ this.ending = false;
+ // when end() has been called, and returned
this.ended = false;
- this.endEmitted = false;
- this.reading = false;
+ // when 'finish' is emitted
+ this.finished = false;
- // In streams that never have any data, and do push(null) right away,
- // the consumer can miss the 'end' event if they do some I/O before
- // consuming the stream. So, we don't emit('end') until some reading
- // happens.
- this.calledRead = false;
+ // should we decode strings into buffers before passing to _write?
+ // this is here so that some node-core streams can optimize string
+ // handling at a lower level.
+ var noDecode = options.decodeStrings === false;
+ this.decodeStrings = !noDecode;
+
+ // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+ this.defaultEncoding = options.defaultEncoding || 'utf8';
+
+ // not an actual buffer we keep track of, but a measurement
+ // of how much we're waiting to get pushed to some underlying
+ // socket or file.
+ this.length = 0;
+
+ // a flag to see when we're in the middle of a write.
+ this.writing = false;
+
+ // when true all writes will be buffered until .uncork() call
+ this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, becuase any
+ // or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
- // whenever we return null, then we set a flag to say
- // that we're awaiting a 'readable' event emission.
- this.needReadable = false;
- this.emittedReadable = false;
- this.readableListening = false;
+ // a flag to know if we're processing previously buffered items, which
+ // may call the _write() callback in the same tick, so that we don't
+ // end up in an overlapped onwrite situation.
+ this.bufferProcessing = false;
+
+ // the callback that's passed to _write(chunk,cb)
+ this.onwrite = function(er) {
+ onwrite(stream, er);
+ };
+
+ // the callback that the user supplies to write(chunk,encoding,cb)
+ this.writecb = null;
+
+ // the amount that is being written when _write is called.
+ this.writelen = 0;
+
+ this.bufferedRequest = null;
+ this.lastBufferedRequest = null;
+
+ // number of pending user-supplied write callbacks
+ // this must be 0 before 'finish' can be emitted
+ this.pendingcb = 0;
+
+ // emit prefinish if the only thing we're waiting for is _write cbs
+ // This is relevant for synchronous Transform streams
+ this.prefinished = false;
+
+ // True if the error was already emitted and should not be thrown again
+ this.errorEmitted = false;
+}
+
+WritableState.prototype.getBuffer = function writableStateGetBuffer() {
+ var current = this.bufferedRequest;
+ var out = [];
+ while (current) {
+ out.push(current);
+ current = current.next;
+ }
+ return out;
+};
+
+(function (){try {
+Object.defineProperty(WritableState.prototype, 'buffer', {
+ get: internalUtil.deprecate(function() {
+ return this.getBuffer();
+ }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' +
+ 'instead.')
+});
+}catch(_){}}());
+
+
+function Writable(options) {
+ var Duplex = require('./_stream_duplex');
+
+ // Writable ctor is applied to Duplexes, though they're not
+ // instanceof Writable, they're instanceof Readable.
+ if (!(this instanceof Writable) && !(this instanceof Duplex))
+ return new Writable(options);
+
+ this._writableState = new WritableState(options, this);
+
+ // legacy.
+ this.writable = true;
+
+ if (options) {
+ if (typeof options.write === 'function')
+ this._write = options.write;
+
+ if (typeof options.writev === 'function')
+ this._writev = options.writev;
+ }
+
+ Stream.call(this);
+}
+
+// Otherwise people can pipe Writable streams, which is just wrong.
+Writable.prototype.pipe = function() {
+ this.emit('error', new Error('Cannot pipe. Not readable.'));
+};
+
+
+function writeAfterEnd(stream, cb) {
+ var er = new Error('write after end');
+ // TODO: defer error events consistently everywhere, not just the cb
+ stream.emit('error', er);
+ processNextTick(cb, er);
+}
+
+// If we get something that is not a buffer, string, null, or undefined,
+// and we're not in objectMode, then that's an error.
+// Otherwise stream chunks are all considered to be of length=1, and the
+// watermarks determine how many objects to keep in the buffer, rather than
+// how many bytes or characters.
+function validChunk(stream, state, chunk, cb) {
+ var valid = true;
+
+ if (!(Buffer.isBuffer(chunk)) &&
+ typeof chunk !== 'string' &&
+ chunk !== null &&
+ chunk !== undefined &&
+ !state.objectMode) {
+ var er = new TypeError('Invalid non-string/buffer chunk');
+ stream.emit('error', er);
+ processNextTick(cb, er);
+ valid = false;
+ }
+ return valid;
+}
+
+Writable.prototype.write = function(chunk, encoding, cb) {
+ var state = this._writableState;
+ var ret = false;
+
+ if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
+
+ if (Buffer.isBuffer(chunk))
+ encoding = 'buffer';
+ else if (!encoding)
+ encoding = state.defaultEncoding;
+
+ if (typeof cb !== 'function')
+ cb = nop;
+
+ if (state.ended)
+ writeAfterEnd(this, cb);
+ else if (validChunk(this, state, chunk, cb)) {
+ state.pendingcb++;
+ ret = writeOrBuffer(this, state, chunk, encoding, cb);
+ }
+ return ret;
+};
+
+Writable.prototype.cork = function() {
+ var state = this._writableState;
- // object stream flag. Used to make read(n) ignore n and to
- // make all the buffer merging and length checks go away
- this.objectMode = !!options.objectMode;
+ state.corked++;
+};
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
+Writable.prototype.uncork = function() {
+ var state = this._writableState;
- // when piping, we only care about 'readable' events that happen
- // after read()ing all the bytes and not getting any pushback.
- this.ranOut = false;
+ if (state.corked) {
+ state.corked--;
- // the number of writers that are awaiting a drain event in .pipe()s
- this.awaitDrain = 0;
+ if (!state.writing &&
+ !state.corked &&
+ !state.finished &&
+ !state.bufferProcessing &&
+ state.bufferedRequest)
+ clearBuffer(this, state);
+ }
+};
- // if true, a maybeReadMore has been scheduled
- this.readingMore = false;
+Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
+ // node::ParseEncoding() requires lower case.
+ if (typeof encoding === 'string')
+ encoding = encoding.toLowerCase();
+ if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64',
+'ucs2', 'ucs-2','utf16le', 'utf-16le', 'raw']
+.indexOf((encoding + '').toLowerCase()) > -1))
+ throw new TypeError('Unknown encoding: ' + encoding);
+ this._writableState.defaultEncoding = encoding;
+};
- this.decoder = null;
- this.encoding = null;
- if (options.encoding) {
- if (!StringDecoder)
- StringDecoder = require('string_decoder/').StringDecoder;
- this.decoder = new StringDecoder(options.encoding);
- this.encoding = options.encoding;
+function decodeChunk(state, chunk, encoding) {
+ if (!state.objectMode &&
+ state.decodeStrings !== false &&
+ typeof chunk === 'string') {
+ chunk = new Buffer(chunk, encoding);
}
+ return chunk;
}
-function Readable(options) {
- if (!(this instanceof Readable))
- return new Readable(options);
-
- this._readableState = new ReadableState(options, this);
+// if we're already writing something, then just put this
+// in the queue, and wait our turn. Otherwise, call _write
+// If we return false, then we need a drain event, so set that flag.
+function writeOrBuffer(stream, state, chunk, encoding, cb) {
+ chunk = decodeChunk(state, chunk, encoding);
- // legacy
- this.readable = true;
+ if (Buffer.isBuffer(chunk))
+ encoding = 'buffer';
+ var len = state.objectMode ? 1 : chunk.length;
- Stream.call(this);
-}
+ state.length += len;
-// Manually shove something into the read() buffer.
-// This returns true if the highWaterMark has not been hit yet,
-// similar to how Writable.write() returns true if you should
-// write() some more.
-Readable.prototype.push = function(chunk, encoding) {
- var state = this._readableState;
+ var ret = state.length < state.highWaterMark;
+ // we must ensure that previous needDrain will not be reset to false.
+ if (!ret)
+ state.needDrain = true;
- if (typeof chunk === 'string' && !state.objectMode) {
- encoding = encoding || state.defaultEncoding;
- if (encoding !== state.encoding) {
- chunk = new Buffer(chunk, encoding);
- encoding = '';
+ if (state.writing || state.corked) {
+ var last = state.lastBufferedRequest;
+ state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
+ if (last) {
+ last.next = state.lastBufferedRequest;
+ } else {
+ state.bufferedRequest = state.lastBufferedRequest;
}
+ } else {
+ doWrite(stream, state, false, len, chunk, encoding, cb);
}
- return readableAddChunk(this, state, chunk, encoding, false);
-};
+ return ret;
+}
-// Unshift should *always* be something directly out of read()
-Readable.prototype.unshift = function(chunk) {
- var state = this._readableState;
- return readableAddChunk(this, state, chunk, '', true);
-};
+function doWrite(stream, state, writev, len, chunk, encoding, cb) {
+ state.writelen = len;
+ state.writecb = cb;
+ state.writing = true;
+ state.sync = true;
+ if (writev)
+ stream._writev(chunk, state.onwrite);
+ else
+ stream._write(chunk, encoding, state.onwrite);
+ state.sync = false;
+}
-function readableAddChunk(stream, state, chunk, encoding, addToFront) {
- var er = chunkInvalid(state, chunk);
- if (er) {
- stream.emit('error', er);
- } else if (chunk === null || chunk === undefined) {
- state.reading = false;
- if (!state.ended)
- onEofChunk(stream, state);
- } else if (state.objectMode || chunk && chunk.length > 0) {
- if (state.ended && !addToFront) {
- var e = new Error('stream.push() after EOF');
- stream.emit('error', e);
- } else if (state.endEmitted && addToFront) {
- var e = new Error('stream.unshift() after end event');
- stream.emit('error', e);
- } else {
- if (state.decoder && !addToFront && !encoding)
- chunk = state.decoder.write(chunk);
+function onwriteError(stream, state, sync, er, cb) {
+ --state.pendingcb;
+ if (sync)
+ processNextTick(cb, er);
+ else
+ cb(er);
- // update the buffer info.
- state.length += state.objectMode ? 1 : chunk.length;
- if (addToFront) {
- state.buffer.unshift(chunk);
- } else {
- state.reading = false;
- state.buffer.push(chunk);
- }
+ stream._writableState.errorEmitted = true;
+ stream.emit('error', er);
+}
- if (state.needReadable)
- emitReadable(stream);
+function onwriteStateUpdate(state) {
+ state.writing = false;
+ state.writecb = null;
+ state.length -= state.writelen;
+ state.writelen = 0;
+}
- maybeReadMore(stream, state);
+function onwrite(stream, er) {
+ var state = stream._writableState;
+ var sync = state.sync;
+ var cb = state.writecb;
+
+ onwriteStateUpdate(state);
+
+ if (er)
+ onwriteError(stream, state, sync, er, cb);
+ else {
+ // Check if we're actually ready to finish, but don't emit yet
+ var finished = needFinish(state);
+
+ if (!finished &&
+ !state.corked &&
+ !state.bufferProcessing &&
+ state.bufferedRequest) {
+ clearBuffer(stream, state);
+ }
+
+ if (sync) {
+ processNextTick(afterWrite, stream, state, finished, cb);
+ } else {
+ afterWrite(stream, state, finished, cb);
}
- } else if (!addToFront) {
- state.reading = false;
}
+}
- return needMoreData(state);
+function afterWrite(stream, state, finished, cb) {
+ if (!finished)
+ onwriteDrain(stream, state);
+ state.pendingcb--;
+ cb();
+ finishMaybe(stream, state);
}
+// Must force callback to be called on nextTick, so that we don't
+// emit 'drain' before the write() consumer gets the 'false' return
+// value, and has a chance to attach a 'drain' listener.
+function onwriteDrain(stream, state) {
+ if (state.length === 0 && state.needDrain) {
+ state.needDrain = false;
+ stream.emit('drain');
+ }
+}
-// if it's past the high water mark, we can push in some more.
-// Also, if we have no data yet, we can stand some
-// more bytes. This is to work around cases where hwm=0,
-// such as the repl. Also, if the push() triggered a
-// readable event, and the user called read(largeNumber) such that
-// needReadable was set, then we ought to push more, so that another
-// 'readable' event will be triggered.
-function needMoreData(state) {
- return !state.ended &&
- (state.needReadable ||
- state.length < state.highWaterMark ||
- state.length === 0);
-}
+// if there's something in the buffer waiting, then process it
+function clearBuffer(stream, state) {
+ state.bufferProcessing = true;
+ var entry = state.bufferedRequest;
-// backwards compatibility.
-Readable.prototype.setEncoding = function(enc) {
- if (!StringDecoder)
- StringDecoder = require('string_decoder/').StringDecoder;
- this._readableState.decoder = new StringDecoder(enc);
- this._readableState.encoding = enc;
-};
+ if (stream._writev && entry && entry.next) {
+ // Fast case, write everything using _writev()
+ var buffer = [];
+ var cbs = [];
+ while (entry) {
+ cbs.push(entry.callback);
+ buffer.push(entry);
+ entry = entry.next;
+ }
+
+ // count the one we are adding, as well.
+ // TODO(isaacs) clean this up
+ state.pendingcb++;
+ state.lastBufferedRequest = null;
+ doWrite(stream, state, true, state.length, buffer, '', function(err) {
+ for (var i = 0; i < cbs.length; i++) {
+ state.pendingcb--;
+ cbs[i](err);
+ }
+ });
+
+ // Clear buffer
+ } else {
+ // Slow case, write chunks one-by-one
+ while (entry) {
+ var chunk = entry.chunk;
+ var encoding = entry.encoding;
+ var cb = entry.callback;
+ var len = state.objectMode ? 1 : chunk.length;
+
+ doWrite(stream, state, false, len, chunk, encoding, cb);
+ entry = entry.next;
+ // if we didn't call the onwrite immediately, then
+ // it means that we need to wait until it does.
+ // also, that means that the chunk and cb are currently
+ // being processed, so move the buffer counter past them.
+ if (state.writing) {
+ break;
+ }
+ }
-// Don't raise the hwm > 128MB
-var MAX_HWM = 0x800000;
-function roundUpToNextPowerOf2(n) {
- if (n >= MAX_HWM) {
- n = MAX_HWM;
- } else {
- // Get the next highest power of 2
- n--;
- for (var p = 1; p < 32; p <<= 1) n |= n >> p;
- n++;
+ if (entry === null)
+ state.lastBufferedRequest = null;
}
- return n;
+ state.bufferedRequest = entry;
+ state.bufferProcessing = false;
}
-function howMuchToRead(n, state) {
- if (state.length === 0 && state.ended)
- return 0;
+Writable.prototype._write = function(chunk, encoding, cb) {
+ cb(new Error('not implemented'));
+};
- if (state.objectMode)
- return n === 0 ? 0 : 1;
+Writable.prototype._writev = null;
- if (n === null || isNaN(n)) {
- // only flow one buffer at a time
- if (state.flowing && state.buffer.length)
- return state.buffer[0].length;
- else
- return state.length;
- }
+Writable.prototype.end = function(chunk, encoding, cb) {
+ var state = this._writableState;
- if (n <= 0)
- return 0;
+ if (typeof chunk === 'function') {
+ cb = chunk;
+ chunk = null;
+ encoding = null;
+ } else if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
- // If we're asking for more than the target buffer level,
- // then raise the water mark. Bump up to the next highest
- // power of 2, to prevent increasing it excessively in tiny
- // amounts.
- if (n > state.highWaterMark)
- state.highWaterMark = roundUpToNextPowerOf2(n);
+ if (chunk !== null && chunk !== undefined)
+ this.write(chunk, encoding);
- // don't have that much. return null, unless we've ended.
- if (n > state.length) {
- if (!state.ended) {
- state.needReadable = true;
- return 0;
- } else
- return state.length;
+ // .end() fully uncorks
+ if (state.corked) {
+ state.corked = 1;
+ this.uncork();
}
- return n;
+ // ignore unnecessary end() calls.
+ if (!state.ending && !state.finished)
+ endWritable(this, state, cb);
+};
+
+
+function needFinish(state) {
+ return (state.ending &&
+ state.length === 0 &&
+ state.bufferedRequest === null &&
+ !state.finished &&
+ !state.writing);
}
-// you can override either this method, or the async _read(n) below.
-Readable.prototype.read = function(n) {
- var state = this._readableState;
- state.calledRead = true;
- var nOrig = n;
- var ret;
+function prefinish(stream, state) {
+ if (!state.prefinished) {
+ state.prefinished = true;
+ stream.emit('prefinish');
+ }
+}
- if (typeof n !== 'number' || n > 0)
- state.emittedReadable = false;
+function finishMaybe(stream, state) {
+ var need = needFinish(state);
+ if (need) {
+ if (state.pendingcb === 0) {
+ prefinish(stream, state);
+ state.finished = true;
+ stream.emit('finish');
+ } else {
+ prefinish(stream, state);
+ }
+ }
+ return need;
+}
- // if we're doing read(0) to trigger a readable event, but we
- // already have a bunch of data in the buffer, then just trigger
- // the 'readable' event and move on.
- if (n === 0 &&
- state.needReadable &&
- (state.length >= state.highWaterMark || state.ended)) {
- emitReadable(this);
- return null;
+function endWritable(stream, state, cb) {
+ state.ending = true;
+ finishMaybe(stream, state);
+ if (cb) {
+ if (state.finished)
+ processNextTick(cb);
+ else
+ stream.once('finish', cb);
}
+ state.ended = true;
+}
- n = howMuchToRead(n, state);
+},{"./_stream_duplex":113,"buffer":8,"core-util-is":15,"events":18,"inherits":47,"process-nextick-args":106,"util-deprecate":136}],118:[function(require,module,exports){
+module.exports = require("./lib/_stream_passthrough.js")
- // if we've ended, and we're now clear, then finish it up.
- if (n === 0 && state.ended) {
- ret = null;
+},{"./lib/_stream_passthrough.js":114}],119:[function(require,module,exports){
+var Stream = (function (){
+ try {
+ return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
+ } catch(_){}
+}());
+exports = module.exports = require('./lib/_stream_readable.js');
+exports.Stream = Stream || exports;
+exports.Readable = exports;
+exports.Writable = require('./lib/_stream_writable.js');
+exports.Duplex = require('./lib/_stream_duplex.js');
+exports.Transform = require('./lib/_stream_transform.js');
+exports.PassThrough = require('./lib/_stream_passthrough.js');
- // In cases where the decoder did not receive enough data
- // to produce a full chunk, then immediately received an
- // EOF, state.buffer will contain [, ].
- // howMuchToRead will see this and coerce the amount to
- // read to zero (because it's looking at the length of the
- // first in state.buffer), and we'll end up here.
- //
- // This can only happen via state.decoder -- no other venue
- // exists for pushing a zero-length chunk into state.buffer
- // and triggering this behavior. In this case, we return our
- // remaining data and end the stream, if appropriate.
- if (state.length > 0 && state.decoder) {
- ret = fromList(n, state);
- state.length -= ret.length;
- }
+},{"./lib/_stream_duplex.js":113,"./lib/_stream_passthrough.js":114,"./lib/_stream_readable.js":115,"./lib/_stream_transform.js":116,"./lib/_stream_writable.js":117}],120:[function(require,module,exports){
+arguments[4][27][0].apply(exports,arguments)
+},{"./lib/_stream_transform.js":116,"dup":27}],121:[function(require,module,exports){
+module.exports = require("./lib/_stream_writable.js")
- if (state.length === 0)
- endReadable(this);
+},{"./lib/_stream_writable.js":117}],122:[function(require,module,exports){
+var path = require('path');
- return ret;
- }
+module.exports = function(npath, ext) {
+ if (typeof npath !== 'string') return npath;
+ if (npath.length === 0) return npath;
- // All the actual chunk generation logic needs to be
- // *below* the call to _read. The reason is that in certain
- // synthetic stream cases, such as passthrough streams, _read
- // may be a completely synchronous operation which may change
- // the state of the read buffer, providing enough data when
- // before there was *not* enough.
- //
- // So, the steps are:
- // 1. Figure out what the state of things will be after we do
- // a read from the buffer.
- //
- // 2. If that resulting state will trigger a _read, then call _read.
- // Note that this may be asynchronous, or synchronous. Yes, it is
- // deeply ugly to write APIs this way, but that still doesn't mean
- // that the Readable class should behave improperly, as streams are
- // designed to be sync/async agnostic.
- // Take note if the _read call is sync or async (ie, if the read call
- // has returned yet), so that we know whether or not it's safe to emit
- // 'readable' etc.
- //
- // 3. Actually pull the requested chunks out of the buffer and return.
+ var nFileName = path.basename(npath, path.extname(npath))+ext;
+ return path.join(path.dirname(npath), nFileName);
+};
+},{"path":104}],123:[function(require,module,exports){
+var Readable = require('stream').Readable;
+var PassThrough = require('stream').PassThrough;
- // if we need a readable event, then we need to do some reading.
- var doRead = state.needReadable;
+function SandwichStream(options) {
+ Readable.call(this, options);
+ options = options || {};
+ this._streamsActive = false;
+ this._streamsAdded = false;
+ this._streams = [];
+ this._currentStream = undefined;
+ this._errorsEmitted = false;
- // if we currently have less than the highWaterMark, then also read some
- if (state.length - n <= state.highWaterMark)
- doRead = true;
+ if (options.head) {
+ this._head = options.head;
+ }
+ if (options.tail) {
+ this._tail = options.tail;
+ }
+ if (options.separator) {
+ this._separator = options.separator;
+ }
+}
- // however, if we've ended, then there's no point, and if we're already
- // reading, then it's unnecessary.
- if (state.ended || state.reading)
- doRead = false;
+SandwichStream.prototype = Object.create(Readable.prototype, {
+ constructor: SandwichStream
+});
- if (doRead) {
- state.reading = true;
- state.sync = true;
- // if the length is currently zero, then we *need* a readable event.
- if (state.length === 0)
- state.needReadable = true;
- // call internal read method
- this._read(state.highWaterMark);
- state.sync = false;
+SandwichStream.prototype._read = function () {
+ if (!this._streamsActive) {
+ this._streamsActive = true;
+ this._pushHead();
+ this._streamNextStream();
}
+};
- // If _read called its callback synchronously, then `reading`
- // will be false, and we need to re-evaluate how much data we
- // can return to the user.
- if (doRead && !state.reading)
- n = howMuchToRead(nOrig, state);
+SandwichStream.prototype.add = function (newStream) {
+ if (!this._streamsActive) {
+ this._streamsAdded = true;
+ this._streams.push(newStream);
+ newStream.on('error', this._substreamOnError.bind(this));
+ }
+ else {
+ throw new Error('SandwichStream error adding new stream while streaming');
+ }
+};
- if (n > 0)
- ret = fromList(n, state);
- else
- ret = null;
+SandwichStream.prototype._substreamOnError = function (error) {
+ this._errorsEmitted = true;
+ this.emit('error', error);
+};
- if (ret === null) {
- state.needReadable = true;
- n = 0;
+SandwichStream.prototype._pushHead = function () {
+ if (this._head) {
+ this.push(this._head);
}
+};
- state.length -= n;
+SandwichStream.prototype._streamNextStream = function () {
+ if (this._nextStream()) {
+ this._bindCurrentStreamEvents();
+ }
+ else {
+ this._pushTail();
+ this.push(null);
+ }
+};
- // If we have nothing in the buffer, then we want to know
- // as soon as we *do* get something into the buffer.
- if (state.length === 0 && !state.ended)
- state.needReadable = true;
+SandwichStream.prototype._nextStream = function () {
+ this._currentStream = this._streams.shift();
+ return this._currentStream !== undefined;
+};
- // If we happened to read() exactly the remaining amount in the
- // buffer, and the EOF has been seen at this point, then make sure
- // that we emit 'end' on the very next tick.
- if (state.ended && !state.endEmitted && state.length === 0)
- endReadable(this);
+SandwichStream.prototype._bindCurrentStreamEvents = function () {
+ this._currentStream.on('readable', this._currentStreamOnReadable.bind(this));
+ this._currentStream.on('end', this._currentStreamOnEnd.bind(this));
+};
- return ret;
+SandwichStream.prototype._currentStreamOnReadable = function () {
+ this.push(this._currentStream.read() || '');
};
-function chunkInvalid(state, chunk) {
- var er = null;
- if (!Buffer.isBuffer(chunk) &&
- 'string' !== typeof chunk &&
- chunk !== null &&
- chunk !== undefined &&
- !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- return er;
-}
+SandwichStream.prototype._currentStreamOnEnd = function () {
+ this._pushSeparator();
+ this._streamNextStream();
+};
+SandwichStream.prototype._pushSeparator = function () {
+ if (this._streams.length > 0 && this._separator) {
+ this.push(this._separator);
+ }
+};
-function onEofChunk(stream, state) {
- if (state.decoder && !state.ended) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) {
- state.buffer.push(chunk);
- state.length += state.objectMode ? 1 : chunk.length;
- }
+SandwichStream.prototype._pushTail = function () {
+ if (this._tail) {
+ this.push(this._tail);
}
- state.ended = true;
+};
- // if we've ended and we have some data left, then emit
- // 'readable' now to make sure it gets picked up.
- if (state.length > 0)
- emitReadable(stream);
- else
- endReadable(stream);
+function sandwichStream(options) {
+ var stream = new SandwichStream(options);
+ return stream;
}
-// Don't emit readable right away in sync mode, because this can trigger
-// another read() call => stack overflow. This way, it might trigger
-// a nextTick recursion warning, but that's not so bad.
-function emitReadable(stream) {
- var state = stream._readableState;
- state.needReadable = false;
- if (state.emittedReadable)
- return;
+sandwichStream.SandwichStream = SandwichStream;
- state.emittedReadable = true;
- if (state.sync)
- process.nextTick(function() {
- emitReadable_(stream);
- });
- else
- emitReadable_(stream);
-}
+module.exports = sandwichStream;
-function emitReadable_(stream) {
- stream.emit('readable');
-}
+},{"stream":124}],124:[function(require,module,exports){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+module.exports = Stream;
+var EE = require('events').EventEmitter;
+var inherits = require('inherits');
-// at this point, the user has presumably seen the 'readable' event,
-// and called read() to consume some data. that may have triggered
-// in turn another _read(n) call, in which case reading = true if
-// it's in progress.
-// However, if we're not ended, or reading, and the length < hwm,
-// then go ahead and try to read some more preemptively.
-function maybeReadMore(stream, state) {
- if (!state.readingMore) {
- state.readingMore = true;
- process.nextTick(function() {
- maybeReadMore_(stream, state);
- });
- }
-}
+inherits(Stream, EE);
+Stream.Readable = require('readable-stream/readable.js');
+Stream.Writable = require('readable-stream/writable.js');
+Stream.Duplex = require('readable-stream/duplex.js');
+Stream.Transform = require('readable-stream/transform.js');
+Stream.PassThrough = require('readable-stream/passthrough.js');
-function maybeReadMore_(stream, state) {
- var len = state.length;
- while (!state.reading && !state.flowing && !state.ended &&
- state.length < state.highWaterMark) {
- stream.read(0);
- if (len === state.length)
- // didn't get any data, stop spinning.
- break;
- else
- len = state.length;
- }
- state.readingMore = false;
-}
+// Backwards-compat with node 0.4.x
+Stream.Stream = Stream;
-// abstract method. to be overridden in specific implementation classes.
-// call cb(er, data) where data is <= n in length.
-// for virtual (non-string, non-buffer) streams, "length" is somewhat
-// arbitrary, and perhaps not very meaningful.
-Readable.prototype._read = function(n) {
- this.emit('error', new Error('not implemented'));
-};
-Readable.prototype.pipe = function(dest, pipeOpts) {
- var src = this;
- var state = this._readableState;
- switch (state.pipesCount) {
- case 0:
- state.pipes = dest;
- break;
- case 1:
- state.pipes = [state.pipes, dest];
- break;
- default:
- state.pipes.push(dest);
- break;
+// old-style streams. Note that the pipe method (the only relevant
+// part of this class) is overridden in the Readable class.
+
+function Stream() {
+ EE.call(this);
+}
+
+Stream.prototype.pipe = function(dest, options) {
+ var source = this;
+
+ function ondata(chunk) {
+ if (dest.writable) {
+ if (false === dest.write(chunk) && source.pause) {
+ source.pause();
+ }
+ }
}
- state.pipesCount += 1;
- var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
- dest !== process.stdout &&
- dest !== process.stderr;
+ source.on('data', ondata);
- var endFn = doEnd ? onend : cleanup;
- if (state.endEmitted)
- process.nextTick(endFn);
- else
- src.once('end', endFn);
+ function ondrain() {
+ if (source.readable && source.resume) {
+ source.resume();
+ }
+ }
- dest.on('unpipe', onunpipe);
- function onunpipe(readable) {
- if (readable !== src) return;
- cleanup();
+ dest.on('drain', ondrain);
+
+ // If the 'end' option is not supplied, dest.end() will be called when
+ // source gets the 'end' or 'close' events. Only dest.end() once.
+ if (!dest._isStdio && (!options || options.end !== false)) {
+ source.on('end', onend);
+ source.on('close', onclose);
}
+ var didOnEnd = false;
function onend() {
+ if (didOnEnd) return;
+ didOnEnd = true;
+
dest.end();
}
- // when the dest drains, it reduces the awaitDrain counter
- // on the source. This would be more elegant with a .once()
- // handler in flow(), but adding and removing repeatedly is
- // too slow.
- var ondrain = pipeOnDrain(src);
- dest.on('drain', ondrain);
-
- function cleanup() {
- // cleanup event handlers once the pipe is broken
- dest.removeListener('close', onclose);
- dest.removeListener('finish', onfinish);
- dest.removeListener('drain', ondrain);
- dest.removeListener('error', onerror);
- dest.removeListener('unpipe', onunpipe);
- src.removeListener('end', onend);
- src.removeListener('end', cleanup);
- // if the reader is waiting for a drain event from this
- // specific writer, then it would cause it to never start
- // flowing again.
- // So, if this is awaiting a drain, then we just call it now.
- // If we don't know, then assume that we are waiting for one.
- if (!dest._writableState || dest._writableState.needDrain)
- ondrain();
+ function onclose() {
+ if (didOnEnd) return;
+ didOnEnd = true;
+
+ if (typeof dest.destroy === 'function') dest.destroy();
}
- // if the dest has an error, then stop piping into it.
- // however, don't suppress the throwing behavior for this.
+ // don't leave dangling pipes when there are errors.
function onerror(er) {
- unpipe();
- dest.removeListener('error', onerror);
- if (EE.listenerCount(dest, 'error') === 0)
- dest.emit('error', er);
+ cleanup();
+ if (EE.listenerCount(this, 'error') === 0) {
+ throw er; // Unhandled stream error in pipe.
+ }
}
- // This is a brutally ugly hack to make sure that our error handler
- // is attached before any userland ones. NEVER DO THIS.
- if (!dest._events || !dest._events.error)
- dest.on('error', onerror);
- else if (isArray(dest._events.error))
- dest._events.error.unshift(onerror);
- else
- dest._events.error = [onerror, dest._events.error];
+ source.on('error', onerror);
+ dest.on('error', onerror);
+ // remove all the event listeners that were added.
+ function cleanup() {
+ source.removeListener('data', ondata);
+ dest.removeListener('drain', ondrain);
- // Both close and finish should trigger unpipe, but only once.
- function onclose() {
- dest.removeListener('finish', onfinish);
- unpipe();
- }
- dest.once('close', onclose);
- function onfinish() {
- dest.removeListener('close', onclose);
- unpipe();
- }
- dest.once('finish', onfinish);
+ source.removeListener('end', onend);
+ source.removeListener('close', onclose);
- function unpipe() {
- src.unpipe(dest);
+ source.removeListener('error', onerror);
+ dest.removeListener('error', onerror);
+
+ source.removeListener('end', cleanup);
+ source.removeListener('close', cleanup);
+
+ dest.removeListener('close', cleanup);
}
- // tell the dest that it's being piped to
- dest.emit('pipe', src);
+ source.on('end', cleanup);
+ source.on('close', cleanup);
- // start the flow if it hasn't been started already.
- if (!state.flowing) {
- // the handler that waits for readable events after all
- // the data gets sucked out in flow.
- // This would be easier to follow with a .once() handler
- // in flow(), but that is too slow.
- this.on('readable', pipeOnReadable);
+ dest.on('close', cleanup);
- state.flowing = true;
- process.nextTick(function() {
- flow(src);
- });
- }
+ dest.emit('pipe', source);
+ // Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
-function pipeOnDrain(src) {
- return function() {
- var dest = this;
- var state = src._readableState;
- state.awaitDrain--;
- if (state.awaitDrain === 0)
- flow(src);
- };
-}
+},{"events":18,"inherits":47,"readable-stream/duplex.js":112,"readable-stream/passthrough.js":118,"readable-stream/readable.js":119,"readable-stream/transform.js":120,"readable-stream/writable.js":121}],125:[function(require,module,exports){
+var ClientRequest = require('./lib/request')
+var extend = require('xtend')
+var statusCodes = require('builtin-status-codes')
+var url = require('url')
-function flow(src) {
- var state = src._readableState;
- var chunk;
- state.awaitDrain = 0;
+var http = exports
- function write(dest, i, list) {
- var written = dest.write(chunk);
- if (false === written) {
- state.awaitDrain++;
- }
- }
+http.request = function (opts, cb) {
+ if (typeof opts === 'string')
+ opts = url.parse(opts)
+ else
+ opts = extend(opts)
- while (state.pipesCount && null !== (chunk = src.read())) {
+ var protocol = opts.protocol || ''
+ var host = opts.hostname || opts.host
+ var port = opts.port
+ var path = opts.path || '/'
- if (state.pipesCount === 1)
- write(state.pipes, 0, null);
- else
- forEach(state.pipes, write);
+ // Necessary for IPv6 addresses
+ if (host && host.indexOf(':') !== -1)
+ host = '[' + host + ']'
- src.emit('data', chunk);
+ // This may be a relative url. The browser should always be able to interpret it correctly.
+ opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
+ opts.method = (opts.method || 'GET').toUpperCase()
+ opts.headers = opts.headers || {}
- // if anyone needs a drain, then we have to wait for that.
- if (state.awaitDrain > 0)
- return;
- }
+ // Also valid opts.auth, opts.mode
- // if every destination was unpiped, either before entering this
- // function, or in the while loop, then stop flowing.
- //
- // NB: This is a pretty rare edge case.
- if (state.pipesCount === 0) {
- state.flowing = false;
+ var req = new ClientRequest(opts)
+ if (cb)
+ req.on('response', cb)
+ return req
+}
- // if there were data event listeners added, then switch to old mode.
- if (EE.listenerCount(src, 'data') > 0)
- emitDataEvents(src);
- return;
- }
+http.get = function get (opts, cb) {
+ var req = http.request(opts, cb)
+ req.end()
+ return req
+}
- // at this point, no one needed a drain, so we just ran out of data
- // on the next readable event, start it over again.
- state.ranOut = true;
+http.Agent = function () {}
+http.Agent.defaultMaxSockets = 4
+
+http.STATUS_CODES = statusCodes
+
+http.METHODS = [
+ 'CHECKOUT',
+ 'CONNECT',
+ 'COPY',
+ 'DELETE',
+ 'GET',
+ 'HEAD',
+ 'LOCK',
+ 'M-SEARCH',
+ 'MERGE',
+ 'MKACTIVITY',
+ 'MKCOL',
+ 'MOVE',
+ 'NOTIFY',
+ 'OPTIONS',
+ 'PATCH',
+ 'POST',
+ 'PROPFIND',
+ 'PROPPATCH',
+ 'PURGE',
+ 'PUT',
+ 'REPORT',
+ 'SEARCH',
+ 'SUBSCRIBE',
+ 'TRACE',
+ 'UNLOCK',
+ 'UNSUBSCRIBE'
+]
+},{"./lib/request":127,"builtin-status-codes":9,"url":135,"xtend":174}],126:[function(require,module,exports){
+(function (global){
+exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableByteStream)
+
+exports.blobConstructor = false
+try {
+ new Blob([new ArrayBuffer(1)])
+ exports.blobConstructor = true
+} catch (e) {}
+
+var xhr = new global.XMLHttpRequest()
+// If location.host is empty, e.g. if this page/worker was loaded
+// from a Blob, then use example.com to avoid an error
+xhr.open('GET', global.location.host ? '/' : 'https://example.com')
+
+function checkTypeSupport (type) {
+ try {
+ xhr.responseType = type
+ return xhr.responseType === type
+ } catch (e) {}
+ return false
}
-function pipeOnReadable() {
- if (this._readableState.ranOut) {
- this._readableState.ranOut = false;
- flow(this);
- }
+// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.
+// Safari 7.1 appears to have fixed this bug.
+var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined'
+var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice)
+
+exports.arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer')
+// These next two tests unavoidably show warnings in Chrome. Since fetch will always
+// be used if it's available, just return false for these to avoid the warnings.
+exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream')
+exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer &&
+ checkTypeSupport('moz-chunked-arraybuffer')
+exports.overrideMimeType = isFunction(xhr.overrideMimeType)
+exports.vbArray = isFunction(global.VBArray)
+
+function isFunction (value) {
+ return typeof value === 'function'
}
+xhr = null // Help gc
-Readable.prototype.unpipe = function(dest) {
- var state = this._readableState;
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],127:[function(require,module,exports){
+(function (process,global,Buffer){
+// var Base64 = require('Base64')
+var capability = require('./capability')
+var foreach = require('foreach')
+var indexOf = require('indexof')
+var inherits = require('inherits')
+var keys = require('object-keys')
+var response = require('./response')
+var stream = require('stream')
- // if we're not piping anywhere, then do nothing.
- if (state.pipesCount === 0)
- return this;
+var IncomingMessage = response.IncomingMessage
+var rStates = response.readyStates
- // just one destination. most common case.
- if (state.pipesCount === 1) {
- // passed in one, but it's not the right one.
- if (dest && dest !== state.pipes)
- return this;
+function decideMode (preferBinary) {
+ if (capability.fetch) {
+ return 'fetch'
+ } else if (capability.mozchunkedarraybuffer) {
+ return 'moz-chunked-arraybuffer'
+ } else if (capability.msstream) {
+ return 'ms-stream'
+ } else if (capability.arraybuffer && preferBinary) {
+ return 'arraybuffer'
+ } else if (capability.vbArray && preferBinary) {
+ return 'text:vbarray'
+ } else {
+ return 'text'
+ }
+}
- if (!dest)
- dest = state.pipes;
+var ClientRequest = module.exports = function (opts) {
+ var self = this
+ stream.Writable.call(self)
- // got a match.
- state.pipes = null;
- state.pipesCount = 0;
- this.removeListener('readable', pipeOnReadable);
- state.flowing = false;
- if (dest)
- dest.emit('unpipe', this);
- return this;
- }
+ self._opts = opts
+ self._body = []
+ self._headers = {}
+ if (opts.auth)
+ self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
+ foreach(keys(opts.headers), function (name) {
+ self.setHeader(name, opts.headers[name])
+ })
- // slow case. multiple pipe destinations.
+ var preferBinary
+ if (opts.mode === 'prefer-streaming') {
+ // If streaming is a high priority but binary compatibility and
+ // the accuracy of the 'content-type' header aren't
+ preferBinary = false
+ } else if (opts.mode === 'allow-wrong-content-type') {
+ // If streaming is more important than preserving the 'content-type' header
+ preferBinary = !capability.overrideMimeType
+ } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
+ // Use binary if text streaming may corrupt data or the content-type header, or for speed
+ preferBinary = true
+ } else {
+ throw new Error('Invalid value for opts.mode')
+ }
+ self._mode = decideMode(preferBinary)
- if (!dest) {
- // remove all.
- var dests = state.pipes;
- var len = state.pipesCount;
- state.pipes = null;
- state.pipesCount = 0;
- this.removeListener('readable', pipeOnReadable);
- state.flowing = false;
+ self.on('finish', function () {
+ self._onFinish()
+ })
+}
- for (var i = 0; i < len; i++)
- dests[i].emit('unpipe', this);
- return this;
- }
+inherits(ClientRequest, stream.Writable)
- // try to find the right one.
- var i = indexOf(state.pipes, dest);
- if (i === -1)
- return this;
+ClientRequest.prototype.setHeader = function (name, value) {
+ var self = this
+ var lowerName = name.toLowerCase()
+ // This check is not necessary, but it prevents warnings from browsers about setting unsafe
+ // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
+ // http-browserify did it, so I will too.
+ if (indexOf(unsafeHeaders, lowerName) !== -1)
+ return
- state.pipes.splice(i, 1);
- state.pipesCount -= 1;
- if (state.pipesCount === 1)
- state.pipes = state.pipes[0];
+ self._headers[lowerName] = {
+ name: name,
+ value: value
+ }
+}
- dest.emit('unpipe', this);
+ClientRequest.prototype.getHeader = function (name) {
+ var self = this
+ return self._headers[name.toLowerCase()].value
+}
- return this;
-};
+ClientRequest.prototype.removeHeader = function (name) {
+ var self = this
+ delete self._headers[name.toLowerCase()]
+}
-// set up data events if they are asked for
-// Ensure readable listeners eventually get something
-Readable.prototype.on = function(ev, fn) {
- var res = Stream.prototype.on.call(this, ev, fn);
+ClientRequest.prototype._onFinish = function () {
+ var self = this
- if (ev === 'data' && !this._readableState.flowing)
- emitDataEvents(this);
+ if (self._destroyed)
+ return
+ var opts = self._opts
- if (ev === 'readable' && this.readable) {
- var state = this._readableState;
- if (!state.readableListening) {
- state.readableListening = true;
- state.emittedReadable = false;
- state.needReadable = true;
- if (!state.reading) {
- this.read(0);
- } else if (state.length) {
- emitReadable(this, state);
- }
- }
- }
+ var headersObj = self._headers
+ var body
+ if (opts.method === 'POST' || opts.method === 'PUT') {
+ if (capability.blobConstructor) {
+ body = new global.Blob(self._body.map(function (buffer) {
+ return buffer.toArrayBuffer()
+ }), {
+ type: (headersObj['content-type'] || {}).value || ''
+ })
+ } else {
+ // get utf8 string
+ body = Buffer.concat(self._body).toString()
+ }
+ }
- return res;
-};
-Readable.prototype.addListener = Readable.prototype.on;
+ if (self._mode === 'fetch') {
+ var headers = keys(headersObj).map(function (name) {
+ return [headersObj[name].name, headersObj[name].value]
+ })
-// pause() and resume() are remnants of the legacy readable stream API
-// If the user uses them, then switch into old mode.
-Readable.prototype.resume = function() {
- emitDataEvents(this);
- this.read(0);
- this.emit('resume');
-};
+ global.fetch(self._opts.url, {
+ method: self._opts.method,
+ headers: headers,
+ body: body,
+ mode: 'cors',
+ credentials: opts.withCredentials ? 'include' : 'same-origin'
+ }).then(function (response) {
+ self._fetchResponse = response
+ self._connect()
+ }).then(undefined, function (reason) {
+ self.emit('error', reason)
+ })
+ } else {
+ var xhr = self._xhr = new global.XMLHttpRequest()
+ try {
+ xhr.open(self._opts.method, self._opts.url, true)
+ } catch (err) {
+ process.nextTick(function () {
+ self.emit('error', err)
+ })
+ return
+ }
-Readable.prototype.pause = function() {
- emitDataEvents(this, true);
- this.emit('pause');
-};
+ // Can't set responseType on really old browsers
+ if ('responseType' in xhr)
+ xhr.responseType = self._mode.split(':')[0]
-function emitDataEvents(stream, startPaused) {
- var state = stream._readableState;
+ if ('withCredentials' in xhr)
+ xhr.withCredentials = !!opts.withCredentials
- if (state.flowing) {
- // https://github.com/isaacs/readable-stream/issues/16
- throw new Error('Cannot switch to old mode now.');
- }
+ if (self._mode === 'text' && 'overrideMimeType' in xhr)
+ xhr.overrideMimeType('text/plain; charset=x-user-defined')
- var paused = startPaused || false;
- var readable = false;
+ foreach(keys(headersObj), function (name) {
+ xhr.setRequestHeader(headersObj[name].name, headersObj[name].value)
+ })
- // convert to an old-style stream.
- stream.readable = true;
- stream.pipe = Stream.prototype.pipe;
- stream.on = stream.addListener = Stream.prototype.on;
+ self._response = null
+ xhr.onreadystatechange = function () {
+ switch (xhr.readyState) {
+ case rStates.LOADING:
+ case rStates.DONE:
+ self._onXHRProgress()
+ break
+ }
+ }
+ // Necessary for streaming in Firefox, since xhr.response is ONLY defined
+ // in onprogress, not in onreadystatechange with xhr.readyState = 3
+ if (self._mode === 'moz-chunked-arraybuffer') {
+ xhr.onprogress = function () {
+ self._onXHRProgress()
+ }
+ }
- stream.on('readable', function() {
- readable = true;
+ xhr.onerror = function () {
+ if (self._destroyed)
+ return
+ self.emit('error', new Error('XHR error'))
+ }
- var c;
- while (!paused && (null !== (c = stream.read())))
- stream.emit('data', c);
+ try {
+ xhr.send(body)
+ } catch (err) {
+ process.nextTick(function () {
+ self.emit('error', err)
+ })
+ return
+ }
+ }
+}
- if (c === null) {
- readable = false;
- stream._readableState.needReadable = true;
- }
- });
+/**
+ * Checks if xhr.status is readable. Even though the spec says it should
+ * be available in readyState 3, accessing it throws an exception in IE8
+ */
+function statusValid (xhr) {
+ try {
+ return (xhr.status !== null)
+ } catch (e) {
+ return false
+ }
+}
- stream.pause = function() {
- paused = true;
- this.emit('pause');
- };
+ClientRequest.prototype._onXHRProgress = function () {
+ var self = this
- stream.resume = function() {
- paused = false;
- if (readable)
- process.nextTick(function() {
- stream.emit('readable');
- });
- else
- this.read(0);
- this.emit('resume');
- };
+ if (!statusValid(self._xhr) || self._destroyed)
+ return
- // now make it start, just in case it hadn't already.
- stream.emit('readable');
+ if (!self._response)
+ self._connect()
+
+ self._response._onXHRProgress()
}
-// wrap an old-style stream as the async data source.
-// This is *not* part of the readable stream interface.
-// It is an ugly unfortunate mess of history.
-Readable.prototype.wrap = function(stream) {
- var state = this._readableState;
- var paused = false;
+ClientRequest.prototype._connect = function () {
+ var self = this
- var self = this;
- stream.on('end', function() {
- if (state.decoder && !state.ended) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length)
- self.push(chunk);
- }
+ if (self._destroyed)
+ return
- self.push(null);
- });
+ self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
+ self.emit('response', self._response)
+}
- stream.on('data', function(chunk) {
- if (state.decoder)
- chunk = state.decoder.write(chunk);
+ClientRequest.prototype._write = function (chunk, encoding, cb) {
+ var self = this
- // don't skip over falsy values in objectMode
- //if (state.objectMode && util.isNullOrUndefined(chunk))
- if (state.objectMode && (chunk === null || chunk === undefined))
- return;
- else if (!state.objectMode && (!chunk || !chunk.length))
- return;
+ self._body.push(chunk)
+ cb()
+}
- var ret = self.push(chunk);
- if (!ret) {
- paused = true;
- stream.pause();
- }
- });
+ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
+ var self = this
+ self._destroyed = true
+ if (self._response)
+ self._response._destroyed = true
+ if (self._xhr)
+ self._xhr.abort()
+ // Currently, there isn't a way to truly abort a fetch.
+ // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27
+}
- // proxy all the other methods.
- // important when wrapping filters and duplexes.
- for (var i in stream) {
- if (typeof stream[i] === 'function' &&
- typeof this[i] === 'undefined') {
- this[i] = function(method) { return function() {
- return stream[method].apply(stream, arguments);
- }}(i);
- }
- }
+ClientRequest.prototype.end = function (data, encoding, cb) {
+ var self = this
+ if (typeof data === 'function') {
+ cb = data
+ data = undefined
+ }
- // proxy certain important events.
- var events = ['error', 'close', 'destroy', 'pause', 'resume'];
- forEach(events, function(ev) {
- stream.on(ev, self.emit.bind(self, ev));
- });
+ stream.Writable.prototype.end.call(self, data, encoding, cb)
+}
- // when we try to consume some more bytes, simply unpause the
- // underlying stream.
- self._read = function(n) {
- if (paused) {
- paused = false;
- stream.resume();
- }
- };
+ClientRequest.prototype.flushHeaders = function () {}
+ClientRequest.prototype.setTimeout = function () {}
+ClientRequest.prototype.setNoDelay = function () {}
+ClientRequest.prototype.setSocketKeepAlive = function () {}
- return self;
-};
+// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
+var unsafeHeaders = [
+ 'accept-charset',
+ 'accept-encoding',
+ 'access-control-request-headers',
+ 'access-control-request-method',
+ 'connection',
+ 'content-length',
+ 'cookie',
+ 'cookie2',
+ 'date',
+ 'dnt',
+ 'expect',
+ 'host',
+ 'keep-alive',
+ 'origin',
+ 'referer',
+ 'te',
+ 'trailer',
+ 'transfer-encoding',
+ 'upgrade',
+ 'user-agent',
+ 'via'
+]
+
+}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
+},{"./capability":126,"./response":128,"_process":107,"buffer":8,"foreach":21,"indexof":45,"inherits":47,"object-keys":93,"stream":124}],128:[function(require,module,exports){
+(function (process,global,Buffer){
+var capability = require('./capability')
+var foreach = require('foreach')
+var inherits = require('inherits')
+var stream = require('stream')
+var rStates = exports.readyStates = {
+ UNSENT: 0,
+ OPENED: 1,
+ HEADERS_RECEIVED: 2,
+ LOADING: 3,
+ DONE: 4
+}
+var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) {
+ var self = this
+ stream.Readable.call(self)
-// exposed for testing purposes only.
-Readable._fromList = fromList;
+ self._mode = mode
+ self.headers = {}
+ self.rawHeaders = []
+ self.trailers = {}
+ self.rawTrailers = []
-// Pluck off n bytes from an array of buffers.
-// Length is the combined lengths of all the buffers in the list.
-function fromList(n, state) {
- var list = state.buffer;
- var length = state.length;
- var stringMode = !!state.decoder;
- var objectMode = !!state.objectMode;
- var ret;
+ // Fake the 'close' event, but only once 'end' fires
+ self.on('end', function () {
+ // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
+ process.nextTick(function () {
+ self.emit('close')
+ })
+ })
- // nothing in the list, definitely empty.
- if (list.length === 0)
- return null;
+ if (mode === 'fetch') {
+ self._fetchResponse = response
- if (length === 0)
- ret = null;
- else if (objectMode)
- ret = list.shift();
- else if (!n || n >= length) {
- // read it all, truncate the array.
- if (stringMode)
- ret = list.join('');
- else
- ret = Buffer.concat(list, length);
- list.length = 0;
- } else {
- // read just some of it.
- if (n < list[0].length) {
- // just take a part of the first list item.
- // slice is the same for buffers and strings.
- var buf = list[0];
- ret = buf.slice(0, n);
- list[0] = buf.slice(n);
- } else if (n === list[0].length) {
- // first list is a perfect match
- ret = list.shift();
- } else {
- // complex case.
- // we have enough to cover it, but it spans past the first buffer.
- if (stringMode)
- ret = '';
- else
- ret = new Buffer(n);
+ self.statusCode = response.status
+ self.statusMessage = response.statusText
+ // backwards compatible version of for (
- of ):
+ // for (var
- ,_i,_it = [Symbol.iterator]();
- = (_i = _it.next()).value,!_i.done;)
+ for (var header, _i, _it = response.headers[Symbol.iterator](); header = (_i = _it.next()).value, !_i.done;) {
+ self.headers[header[0].toLowerCase()] = header[1]
+ self.rawHeaders.push(header[0], header[1])
+ }
- var c = 0;
- for (var i = 0, l = list.length; i < l && c < n; i++) {
- var buf = list[0];
- var cpy = Math.min(n - c, buf.length);
+ // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed
+ var reader = response.body.getReader()
+ function read () {
+ reader.read().then(function (result) {
+ if (self._destroyed)
+ return
+ if (result.done) {
+ self.push(null)
+ return
+ }
+ self.push(new Buffer(result.value))
+ read()
+ })
+ }
+ read()
- if (stringMode)
- ret += buf.slice(0, cpy);
- else
- buf.copy(ret, c, 0, cpy);
+ } else {
+ self._xhr = xhr
+ self._pos = 0
- if (cpy < buf.length)
- list[0] = buf.slice(cpy);
- else
- list.shift();
+ self.statusCode = xhr.status
+ self.statusMessage = xhr.statusText
+ var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
+ foreach(headers, function (header) {
+ var matches = header.match(/^([^:]+):\s*(.*)/)
+ if (matches) {
+ var key = matches[1].toLowerCase()
+ if (self.headers[key] !== undefined)
+ self.headers[key] += ', ' + matches[2]
+ else
+ self.headers[key] = matches[2]
+ self.rawHeaders.push(matches[1], matches[2])
+ }
+ })
+
+ self._charset = 'x-user-defined'
+ if (!capability.overrideMimeType) {
+ var mimeType = self.rawHeaders['mime-type']
+ if (mimeType) {
+ var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
+ if (charsetMatch) {
+ self._charset = charsetMatch[1].toLowerCase()
+ }
+ }
+ if (!self._charset)
+ self._charset = 'utf-8' // best guess
+ }
+ }
+}
- c += cpy;
- }
- }
- }
+inherits(IncomingMessage, stream.Readable)
- return ret;
-}
+IncomingMessage.prototype._read = function () {}
-function endReadable(stream) {
- var state = stream._readableState;
+IncomingMessage.prototype._onXHRProgress = function () {
+ var self = this
- // If we get here before consuming all the bytes, then that is a
- // bug in node. Should never happen.
- if (state.length > 0)
- throw new Error('endReadable called on non-empty stream');
+ var xhr = self._xhr
- if (!state.endEmitted && state.calledRead) {
- state.ended = true;
- process.nextTick(function() {
- // Check that we didn't get one last unshift.
- if (!state.endEmitted && state.length === 0) {
- state.endEmitted = true;
- stream.readable = false;
- stream.emit('end');
- }
- });
- }
-}
+ var response = null
+ switch (self._mode) {
+ case 'text:vbarray': // For IE9
+ if (xhr.readyState !== rStates.DONE)
+ break
+ try {
+ // This fails in IE8
+ response = new global.VBArray(xhr.responseBody).toArray()
+ } catch (e) {}
+ if (response !== null) {
+ self.push(new Buffer(response))
+ break
+ }
+ // Falls through in IE8
+ case 'text':
+ try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4
+ response = xhr.responseText
+ } catch (e) {
+ self._mode = 'text:vbarray'
+ break
+ }
+ if (response.length > self._pos) {
+ var newData = response.substr(self._pos)
+ if (self._charset === 'x-user-defined') {
+ var buffer = new Buffer(newData.length)
+ for (var i = 0; i < newData.length; i++)
+ buffer[i] = newData.charCodeAt(i) & 0xff
-function forEach (xs, f) {
- for (var i = 0, l = xs.length; i < l; i++) {
- f(xs[i], i);
- }
-}
+ self.push(buffer)
+ } else {
+ self.push(newData, self._charset)
+ }
+ self._pos = response.length
+ }
+ break
+ case 'arraybuffer':
+ if (xhr.readyState !== rStates.DONE)
+ break
+ response = xhr.response
+ self.push(new Buffer(new Uint8Array(response)))
+ break
+ case 'moz-chunked-arraybuffer': // take whole
+ response = xhr.response
+ if (xhr.readyState !== rStates.LOADING || !response)
+ break
+ self.push(new Buffer(new Uint8Array(response)))
+ break
+ case 'ms-stream':
+ response = xhr.response
+ if (xhr.readyState !== rStates.LOADING)
+ break
+ var reader = new global.MSStreamReader()
+ reader.onprogress = function () {
+ if (reader.result.byteLength > self._pos) {
+ self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))))
+ self._pos = reader.result.byteLength
+ }
+ }
+ reader.onload = function () {
+ self.push(null)
+ }
+ // reader.onerror = ??? // TODO: this
+ reader.readAsArrayBuffer(response)
+ break
+ }
-function indexOf (xs, x) {
- for (var i = 0, l = xs.length; i < l; i++) {
- if (xs[i] === x) return i;
- }
- return -1;
+ // The ms-stream case handles end separately in reader.onload()
+ if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
+ self.push(null)
+ }
}
-}).call(this,require('_process'))
-},{"_process":64,"buffer":6,"core-util-is":176,"events":14,"inherits":177,"isarray":178,"stream":81,"string_decoder/":179}],174:[function(require,module,exports){
+}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
+},{"./capability":126,"_process":107,"buffer":8,"foreach":21,"inherits":47,"stream":124}],129:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -19206,198 +18074,341 @@ function indexOf (xs, x) {
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
+var Buffer = require('buffer').Buffer;
-// a transform stream is a readable/writable stream where you do
-// something with the data. Sometimes it's called a "filter",
-// but that's not a great name for it, since that implies a thing where
-// some bits pass through, and others are simply ignored. (That would
-// be a valid example of a transform, of course.)
-//
-// While the output is causally related to the input, it's not a
-// necessarily symmetric or synchronous transformation. For example,
-// a zlib stream might take multiple plain-text writes(), and then
-// emit a single compressed chunk some time in the future.
-//
-// Here's how this works:
-//
-// The Transform stream has all the aspects of the readable and writable
-// stream classes. When you write(chunk), that calls _write(chunk,cb)
-// internally, and returns false if there's a lot of pending writes
-// buffered up. When you call read(), that calls _read(n) until
-// there's enough pending readable data buffered up.
-//
-// In a transform stream, the written data is placed in a buffer. When
-// _read(n) is called, it transforms the queued up data, calling the
-// buffered _write cb's as it consumes chunks. If consuming a single
-// written chunk would result in multiple output chunks, then the first
-// outputted bit calls the readcb, and subsequent chunks just go into
-// the read buffer, and will cause it to emit 'readable' if necessary.
+var isBufferEncoding = Buffer.isEncoding
+ || function(encoding) {
+ switch (encoding && encoding.toLowerCase()) {
+ case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
+ default: return false;
+ }
+ }
+
+
+function assertEncoding(encoding) {
+ if (encoding && !isBufferEncoding(encoding)) {
+ throw new Error('Unknown encoding: ' + encoding);
+ }
+}
+
+// StringDecoder provides an interface for efficiently splitting a series of
+// buffers into a series of JS strings without breaking apart multi-byte
+// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
-// This way, back-pressure is actually determined by the reading side,
-// since _read has to be called to start processing a new chunk. However,
-// a pathological inflate type of transform can cause excessive buffering
-// here. For example, imagine a stream where every byte of input is
-// interpreted as an integer from 0-255, and then results in that many
-// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
-// 1kb of data being output. In this case, you could write a very small
-// amount of input, and end up with a very large amount of output. In
-// such a pathological inflating mechanism, there'd be no way to tell
-// the system to stop doing the transform. A single 4MB write could
-// cause the system to run out of memory.
+// @TODO Handling all encodings inside a single object makes it very difficult
+// to reason about this code, so it should be split up in the future.
+// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
+// points as used by CESU-8.
+var StringDecoder = exports.StringDecoder = function(encoding) {
+ this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
+ assertEncoding(encoding);
+ switch (this.encoding) {
+ case 'utf8':
+ // CESU-8 represents each of Surrogate Pair by 3-bytes
+ this.surrogateSize = 3;
+ break;
+ case 'ucs2':
+ case 'utf16le':
+ // UTF-16 represents each of Surrogate Pair by 2-bytes
+ this.surrogateSize = 2;
+ this.detectIncompleteChar = utf16DetectIncompleteChar;
+ break;
+ case 'base64':
+ // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
+ this.surrogateSize = 3;
+ this.detectIncompleteChar = base64DetectIncompleteChar;
+ break;
+ default:
+ this.write = passThroughWrite;
+ return;
+ }
+
+ // Enough space to store all bytes of a single character. UTF-8 needs 4
+ // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
+ this.charBuffer = new Buffer(6);
+ // Number of bytes received for the current incomplete multi-byte character.
+ this.charReceived = 0;
+ // Number of bytes expected for the current incomplete multi-byte character.
+ this.charLength = 0;
+};
+
+
+// write decodes the given buffer and returns it as JS string that is
+// guaranteed to not contain any partial multi-byte characters. Any partial
+// character found at the end of the buffer is buffered up, and will be
+// returned when calling write again with the remaining bytes.
//
-// However, even in such a pathological case, only a single written chunk
-// would be consumed, and then the rest would wait (un-transformed) until
-// the results of the previous transformed chunk were consumed.
+// Note: Converting a Buffer containing an orphan surrogate to a String
+// currently works, but converting a String to a Buffer (via `new Buffer`, or
+// Buffer#write) will replace incomplete surrogates with the unicode
+// replacement character. See https://codereview.chromium.org/121173009/ .
+StringDecoder.prototype.write = function(buffer) {
+ var charStr = '';
+ // if our last write ended with an incomplete multibyte character
+ while (this.charLength) {
+ // determine how many remaining bytes this buffer has to offer for this char
+ var available = (buffer.length >= this.charLength - this.charReceived) ?
+ this.charLength - this.charReceived :
+ buffer.length;
-module.exports = Transform;
+ // add the new bytes to the char buffer
+ buffer.copy(this.charBuffer, this.charReceived, 0, available);
+ this.charReceived += available;
+
+ if (this.charReceived < this.charLength) {
+ // still not enough chars in this buffer? wait for more ...
+ return '';
+ }
+
+ // remove bytes belonging to the current character from the buffer
+ buffer = buffer.slice(available, buffer.length);
+
+ // get the character that was split
+ charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
+
+ // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
+ var charCode = charStr.charCodeAt(charStr.length - 1);
+ if (charCode >= 0xD800 && charCode <= 0xDBFF) {
+ this.charLength += this.surrogateSize;
+ charStr = '';
+ continue;
+ }
+ this.charReceived = this.charLength = 0;
+
+ // if there are no more bytes in this buffer, just emit our char
+ if (buffer.length === 0) {
+ return charStr;
+ }
+ break;
+ }
-var Duplex = require('./_stream_duplex');
+ // determine and set charLength / charReceived
+ this.detectIncompleteChar(buffer);
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+ var end = buffer.length;
+ if (this.charLength) {
+ // buffer the incomplete character bytes we got
+ buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
+ end -= this.charReceived;
+ }
-util.inherits(Transform, Duplex);
+ charStr += buffer.toString(this.encoding, 0, end);
+ var end = charStr.length - 1;
+ var charCode = charStr.charCodeAt(end);
+ // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
+ if (charCode >= 0xD800 && charCode <= 0xDBFF) {
+ var size = this.surrogateSize;
+ this.charLength += size;
+ this.charReceived += size;
+ this.charBuffer.copy(this.charBuffer, size, 0, size);
+ buffer.copy(this.charBuffer, 0, 0, size);
+ return charStr.substring(0, end);
+ }
-function TransformState(options, stream) {
- this.afterTransform = function(er, data) {
- return afterTransform(stream, er, data);
- };
+ // or just emit the charStr
+ return charStr;
+};
- this.needTransform = false;
- this.transforming = false;
- this.writecb = null;
- this.writechunk = null;
-}
+// detectIncompleteChar determines if there is an incomplete UTF-8 character at
+// the end of the given buffer. If so, it sets this.charLength to the byte
+// length that character, and sets this.charReceived to the number of bytes
+// that are available for this character.
+StringDecoder.prototype.detectIncompleteChar = function(buffer) {
+ // determine how many bytes we have to check at the end of this buffer
+ var i = (buffer.length >= 3) ? 3 : buffer.length;
-function afterTransform(stream, er, data) {
- var ts = stream._transformState;
- ts.transforming = false;
+ // Figure out if one of the last i bytes of our buffer announces an
+ // incomplete char.
+ for (; i > 0; i--) {
+ var c = buffer[buffer.length - i];
- var cb = ts.writecb;
+ // See http://en.wikipedia.org/wiki/UTF-8#Description
- if (!cb)
- return stream.emit('error', new Error('no writecb in Transform class'));
+ // 110XXXXX
+ if (i == 1 && c >> 5 == 0x06) {
+ this.charLength = 2;
+ break;
+ }
- ts.writechunk = null;
- ts.writecb = null;
+ // 1110XXXX
+ if (i <= 2 && c >> 4 == 0x0E) {
+ this.charLength = 3;
+ break;
+ }
- if (data !== null && data !== undefined)
- stream.push(data);
+ // 11110XXX
+ if (i <= 3 && c >> 3 == 0x1E) {
+ this.charLength = 4;
+ break;
+ }
+ }
+ this.charReceived = i;
+};
- if (cb)
- cb(er);
+StringDecoder.prototype.end = function(buffer) {
+ var res = '';
+ if (buffer && buffer.length)
+ res = this.write(buffer);
- var rs = stream._readableState;
- rs.reading = false;
- if (rs.needReadable || rs.length < rs.highWaterMark) {
- stream._read(rs.highWaterMark);
+ if (this.charReceived) {
+ var cr = this.charReceived;
+ var buf = this.charBuffer;
+ var enc = this.encoding;
+ res += buf.slice(0, cr).toString(enc);
}
+
+ return res;
+};
+
+function passThroughWrite(buffer) {
+ return buffer.toString(this.encoding);
}
+function utf16DetectIncompleteChar(buffer) {
+ this.charReceived = buffer.length % 2;
+ this.charLength = this.charReceived ? 2 : 0;
+}
-function Transform(options) {
- if (!(this instanceof Transform))
- return new Transform(options);
+function base64DetectIncompleteChar(buffer) {
+ this.charReceived = buffer.length % 3;
+ this.charLength = this.charReceived ? 3 : 0;
+}
- Duplex.call(this, options);
+},{"buffer":8}],130:[function(require,module,exports){
+'use strict';
+var firstChunk = require('first-chunk-stream');
+var stripBom = require('strip-bom');
- var ts = this._transformState = new TransformState(options, this);
+module.exports = function () {
+ return firstChunk({minSize: 3}, function (chunk, enc, cb) {
+ this.push(stripBom(chunk));
+ cb();
+ });
+};
- // when the writable side finishes, then flush out anything remaining.
- var stream = this;
+},{"first-chunk-stream":20,"strip-bom":131}],131:[function(require,module,exports){
+(function (Buffer){
+'use strict';
+var isUtf8 = require('is-utf8');
- // start out asking for a readable event once data is transformed.
- this._readableState.needReadable = true;
+module.exports = function (x) {
+ // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
+ // conversion translates it to FEFF (UTF-16 BOM)
+ if (typeof x === 'string' && x.charCodeAt(0) === 0xFEFF) {
+ return x.slice(1);
+ }
- // we have implemented the _read method, and done the other things
- // that Readable wants before the first _read call, so unset the
- // sync guard flag.
- this._readableState.sync = false;
+ if (Buffer.isBuffer(x) && isUtf8(x) &&
+ x[0] === 0xEF && x[1] === 0xBB && x[2] === 0xBF) {
+ return x.slice(3);
+ }
- this.once('finish', function() {
- if ('function' === typeof this._flush)
- this._flush(function(er) {
- done(stream, er);
- });
- else
- done(stream);
- });
+ return x;
+};
+
+}).call(this,{"isBuffer":require("../is-buffer/index.js")})
+},{"../is-buffer/index.js":50,"is-utf8":51}],132:[function(require,module,exports){
+"use strict";
+
+module.exports = make
+module.exports.ctor = ctor
+module.exports.objCtor = objCtor
+module.exports.obj = obj
+
+var through2 = require("through2")
+var xtend = require("xtend")
+
+function ctor(options, fn) {
+ if (typeof options == "function") {
+ fn = options
+ options = {}
+ }
+
+ var Filter = through2.ctor(options, function (chunk, encoding, callback) {
+ if (this.options.wantStrings) chunk = chunk.toString()
+ if (fn.call(this, chunk, this._index++)) this.push(chunk)
+ return callback()
+ })
+ Filter.prototype._index = 0
+ return Filter
}
-Transform.prototype.push = function(chunk, encoding) {
- this._transformState.needTransform = false;
- return Duplex.prototype.push.call(this, chunk, encoding);
-};
+function objCtor(options, fn) {
+ if (typeof options === "function") {
+ fn = options
+ options = {}
+ }
+ options = xtend({objectMode: true, highWaterMark: 16}, options)
+ return ctor(options, fn)
+}
-// This is the part where you do stuff!
-// override this function in implementation classes.
-// 'chunk' is an input chunk.
-//
-// Call `push(newChunk)` to pass along transformed output
-// to the readable side. You may call 'push' zero or more times.
-//
-// Call `cb(err)` when you are done with this chunk. If you pass
-// an error, then that'll put the hurt on the whole operation. If you
-// never call cb(), then you'll never get another chunk.
-Transform.prototype._transform = function(chunk, encoding, cb) {
- throw new Error('not implemented');
-};
+function make(options, fn) {
+ return ctor(options, fn)()
+}
-Transform.prototype._write = function(chunk, encoding, cb) {
- var ts = this._transformState;
- ts.writecb = cb;
- ts.writechunk = chunk;
- ts.writeencoding = encoding;
- if (!ts.transforming) {
- var rs = this._readableState;
- if (ts.needTransform ||
- rs.needReadable ||
- rs.length < rs.highWaterMark)
- this._read(rs.highWaterMark);
+function obj(options, fn) {
+ if (typeof options === "function") {
+ fn = options
+ options = {}
}
-};
+ options = xtend({objectMode: true, highWaterMark: 16}, options)
+ return make(options, fn)
+}
-// Doesn't matter what the args are here.
-// _transform does all the work.
-// That we got here means that the readable side wants more data.
-Transform.prototype._read = function(n) {
- var ts = this._transformState;
+},{"through2":133,"xtend":174}],133:[function(require,module,exports){
+arguments[4][28][0].apply(exports,arguments)
+},{"_process":107,"dup":28,"readable-stream/transform":120,"util":138,"xtend":174}],134:[function(require,module,exports){
+(function (global){
+'use strict';
- if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
- ts.transforming = true;
- this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
- } else {
- // mark that we need a transform, so that any data that comes in
- // will get processed, now that we've asked for it.
- ts.needTransform = true;
+var filter = require('through2-filter').obj;
+var ES6Set;
+if (typeof global.Set === 'function') {
+ ES6Set = global.Set;
+} else {
+ ES6Set = function() {
+ this.keys = [];
+ this.has = function(val) {
+ return this.keys.indexOf(val) !== -1;
+ },
+ this.add = function(val) {
+ this.keys.push(val);
+ }
}
-};
+}
+function prop(propName) {
+ return function (data) {
+ return data[propName];
+ };
+}
-function done(stream, er) {
- if (er)
- return stream.emit('error', er);
+module.exports = unique;
+function unique(propName, keyStore) {
+ keyStore = keyStore || new ES6Set();
- // if there's nothing in the write buffer, then that means
- // that nothing more will ever be provided
- var ws = stream._writableState;
- var rs = stream._readableState;
- var ts = stream._transformState;
+ var keyfn = JSON.stringify;
+ if (typeof propName === 'string') {
+ keyfn = prop(propName);
+ } else if (typeof propName === 'function') {
+ keyfn = propName;
+ }
- if (ws.length)
- throw new Error('calling transform done when ws.length != 0');
+ return filter(function (data) {
+ var key = keyfn(data);
- if (ts.transforming)
- throw new Error('calling transform done when still transforming');
+ if (keyStore.has(key)) {
+ return false;
+ }
- return stream.push(null);
+ keyStore.add(key);
+ return true;
+ });
}
-},{"./_stream_duplex":172,"core-util-is":176,"inherits":177}],175:[function(require,module,exports){
-(function (process){
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"through2-filter":132}],135:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -19419,2168 +18430,2266 @@ function done(stream, er) {
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-// A bit simpler than readable streams.
-// Implement an async ._write(chunk, cb), and it'll handle all
-// the drain event emission and buffering.
+var punycode = require('punycode');
-module.exports = Writable;
+exports.parse = urlParse;
+exports.resolve = urlResolve;
+exports.resolveObject = urlResolveObject;
+exports.format = urlFormat;
-/**/
-var Buffer = require('buffer').Buffer;
-/**/
+exports.Url = Url;
-Writable.WritableState = WritableState;
+function Url() {
+ this.protocol = null;
+ this.slashes = null;
+ this.auth = null;
+ this.host = null;
+ this.port = null;
+ this.hostname = null;
+ this.hash = null;
+ this.search = null;
+ this.query = null;
+ this.pathname = null;
+ this.path = null;
+ this.href = null;
+}
+// Reference: RFC 3986, RFC 1808, RFC 2396
-/**/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/**/
+// define these here so at least they only have to be
+// compiled once on the first module load.
+var protocolPattern = /^([a-z0-9.+-]+:)/i,
+ portPattern = /:[0-9]*$/,
-var Stream = require('stream');
+ // RFC 2396: characters reserved for delimiting URLs.
+ // We actually just auto-escape these.
+ delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
-util.inherits(Writable, Stream);
+ // RFC 2396: characters not allowed for various reasons.
+ unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
-function WriteReq(chunk, encoding, cb) {
- this.chunk = chunk;
- this.encoding = encoding;
- this.callback = cb;
+ // Allowed by RFCs, but cause of XSS attacks. Always escape these.
+ autoEscape = ['\''].concat(unwise),
+ // Characters that are never ever allowed in a hostname.
+ // Note that any invalid chars are also handled, but these
+ // are the ones that are *expected* to be seen, so we fast-path
+ // them.
+ nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
+ hostEndingChars = ['/', '?', '#'],
+ hostnameMaxLen = 255,
+ hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
+ hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
+ // protocols that can allow "unsafe" and "unwise" chars.
+ unsafeProtocol = {
+ 'javascript': true,
+ 'javascript:': true
+ },
+ // protocols that never have a hostname.
+ hostlessProtocol = {
+ 'javascript': true,
+ 'javascript:': true
+ },
+ // protocols that always contain a // bit.
+ slashedProtocol = {
+ 'http': true,
+ 'https': true,
+ 'ftp': true,
+ 'gopher': true,
+ 'file': true,
+ 'http:': true,
+ 'https:': true,
+ 'ftp:': true,
+ 'gopher:': true,
+ 'file:': true
+ },
+ querystring = require('querystring');
+
+function urlParse(url, parseQueryString, slashesDenoteHost) {
+ if (url && isObject(url) && url instanceof Url) return url;
+
+ var u = new Url;
+ u.parse(url, parseQueryString, slashesDenoteHost);
+ return u;
}
-function WritableState(options, stream) {
- options = options || {};
+Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
+ if (!isString(url)) {
+ throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
+ }
- // the point at which write() starts returning false
- // Note: 0 is a valid value, means that we always return false if
- // the entire buffer is not flushed immediately on write()
- var hwm = options.highWaterMark;
- this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
+ var rest = url;
- // object stream flag to indicate whether or not this stream
- // contains buffers or objects.
- this.objectMode = !!options.objectMode;
+ // trim before proceeding.
+ // This is to support parse stuff like " http://foo.com \n"
+ rest = rest.trim();
- // cast to ints.
- this.highWaterMark = ~~this.highWaterMark;
+ var proto = protocolPattern.exec(rest);
+ if (proto) {
+ proto = proto[0];
+ var lowerProto = proto.toLowerCase();
+ this.protocol = lowerProto;
+ rest = rest.substr(proto.length);
+ }
- this.needDrain = false;
- // at the start of calling end()
- this.ending = false;
- // when end() has been called, and returned
- this.ended = false;
- // when 'finish' is emitted
- this.finished = false;
+ // figure out if it's got a host
+ // user@server is *always* interpreted as a hostname, and url
+ // resolution will treat //foo/bar as host=foo,path=bar because that's
+ // how the browser resolves relative URLs.
+ if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
+ var slashes = rest.substr(0, 2) === '//';
+ if (slashes && !(proto && hostlessProtocol[proto])) {
+ rest = rest.substr(2);
+ this.slashes = true;
+ }
+ }
- // should we decode strings into buffers before passing to _write?
- // this is here so that some node-core streams can optimize string
- // handling at a lower level.
- var noDecode = options.decodeStrings === false;
- this.decodeStrings = !noDecode;
+ if (!hostlessProtocol[proto] &&
+ (slashes || (proto && !slashedProtocol[proto]))) {
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
+ // there's a hostname.
+ // the first instance of /, ?, ;, or # ends the host.
+ //
+ // If there is an @ in the hostname, then non-host chars *are* allowed
+ // to the left of the last @ sign, unless some host-ending character
+ // comes *before* the @-sign.
+ // URLs are obnoxious.
+ //
+ // ex:
+ // http://a@b@c/ => user:a@b host:c
+ // http://a@b?@c => user:a host:c path:/?@c
- // not an actual buffer we keep track of, but a measurement
- // of how much we're waiting to get pushed to some underlying
- // socket or file.
- this.length = 0;
+ // v0.12 TODO(isaacs): This is not quite how Chrome does things.
+ // Review our test case against browsers more comprehensively.
- // a flag to see when we're in the middle of a write.
- this.writing = false;
+ // find the first instance of any hostEndingChars
+ var hostEnd = -1;
+ for (var i = 0; i < hostEndingChars.length; i++) {
+ var hec = rest.indexOf(hostEndingChars[i]);
+ if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
+ hostEnd = hec;
+ }
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, becuase any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
+ // at this point, either we have an explicit point where the
+ // auth portion cannot go past, or the last @ char is the decider.
+ var auth, atSign;
+ if (hostEnd === -1) {
+ // atSign can be anywhere.
+ atSign = rest.lastIndexOf('@');
+ } else {
+ // atSign must be in auth portion.
+ // http://a@b/c@d => host:b auth:a path:/c@d
+ atSign = rest.lastIndexOf('@', hostEnd);
+ }
- // a flag to know if we're processing previously buffered items, which
- // may call the _write() callback in the same tick, so that we don't
- // end up in an overlapped onwrite situation.
- this.bufferProcessing = false;
+ // Now we have a portion which is definitely the auth.
+ // Pull that off.
+ if (atSign !== -1) {
+ auth = rest.slice(0, atSign);
+ rest = rest.slice(atSign + 1);
+ this.auth = decodeURIComponent(auth);
+ }
+
+ // the host is the remaining to the left of the first non-host char
+ hostEnd = -1;
+ for (var i = 0; i < nonHostChars.length; i++) {
+ var hec = rest.indexOf(nonHostChars[i]);
+ if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
+ hostEnd = hec;
+ }
+ // if we still have not hit it, then the entire thing is a host.
+ if (hostEnd === -1)
+ hostEnd = rest.length;
+
+ this.host = rest.slice(0, hostEnd);
+ rest = rest.slice(hostEnd);
+
+ // pull out port.
+ this.parseHost();
+
+ // we've indicated that there is a hostname,
+ // so even if it's empty, it has to be present.
+ this.hostname = this.hostname || '';
+
+ // if hostname begins with [ and ends with ]
+ // assume that it's an IPv6 address.
+ var ipv6Hostname = this.hostname[0] === '[' &&
+ this.hostname[this.hostname.length - 1] === ']';
- // the callback that's passed to _write(chunk,cb)
- this.onwrite = function(er) {
- onwrite(stream, er);
- };
+ // validate a little.
+ if (!ipv6Hostname) {
+ var hostparts = this.hostname.split(/\./);
+ for (var i = 0, l = hostparts.length; i < l; i++) {
+ var part = hostparts[i];
+ if (!part) continue;
+ if (!part.match(hostnamePartPattern)) {
+ var newpart = '';
+ for (var j = 0, k = part.length; j < k; j++) {
+ if (part.charCodeAt(j) > 127) {
+ // we replace non-ASCII char with a temporary placeholder
+ // we need this to make sure size of hostname is not
+ // broken by replacing non-ASCII by nothing
+ newpart += 'x';
+ } else {
+ newpart += part[j];
+ }
+ }
+ // we test again with ASCII char only
+ if (!newpart.match(hostnamePartPattern)) {
+ var validParts = hostparts.slice(0, i);
+ var notHost = hostparts.slice(i + 1);
+ var bit = part.match(hostnamePartStart);
+ if (bit) {
+ validParts.push(bit[1]);
+ notHost.unshift(bit[2]);
+ }
+ if (notHost.length) {
+ rest = '/' + notHost.join('.') + rest;
+ }
+ this.hostname = validParts.join('.');
+ break;
+ }
+ }
+ }
+ }
- // the callback that the user supplies to write(chunk,encoding,cb)
- this.writecb = null;
+ if (this.hostname.length > hostnameMaxLen) {
+ this.hostname = '';
+ } else {
+ // hostnames are always lower case.
+ this.hostname = this.hostname.toLowerCase();
+ }
- // the amount that is being written when _write is called.
- this.writelen = 0;
+ if (!ipv6Hostname) {
+ // IDNA Support: Returns a puny coded representation of "domain".
+ // It only converts the part of the domain name that
+ // has non ASCII characters. I.e. it dosent matter if
+ // you call it with a domain that already is in ASCII.
+ var domainArray = this.hostname.split('.');
+ var newOut = [];
+ for (var i = 0; i < domainArray.length; ++i) {
+ var s = domainArray[i];
+ newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
+ 'xn--' + punycode.encode(s) : s);
+ }
+ this.hostname = newOut.join('.');
+ }
- this.buffer = [];
+ var p = this.port ? ':' + this.port : '';
+ var h = this.hostname || '';
+ this.host = h + p;
+ this.href += this.host;
- // True if the error was already emitted and should not be thrown again
- this.errorEmitted = false;
-}
+ // strip [ and ] from the hostname
+ // the host field still retains them, though
+ if (ipv6Hostname) {
+ this.hostname = this.hostname.substr(1, this.hostname.length - 2);
+ if (rest[0] !== '/') {
+ rest = '/' + rest;
+ }
+ }
+ }
-function Writable(options) {
- var Duplex = require('./_stream_duplex');
+ // now rest is set to the post-host stuff.
+ // chop off any delim chars.
+ if (!unsafeProtocol[lowerProto]) {
- // Writable ctor is applied to Duplexes, though they're not
- // instanceof Writable, they're instanceof Readable.
- if (!(this instanceof Writable) && !(this instanceof Duplex))
- return new Writable(options);
+ // First, make 100% sure that any "autoEscape" chars get
+ // escaped, even if encodeURIComponent doesn't think they
+ // need to be.
+ for (var i = 0, l = autoEscape.length; i < l; i++) {
+ var ae = autoEscape[i];
+ var esc = encodeURIComponent(ae);
+ if (esc === ae) {
+ esc = escape(ae);
+ }
+ rest = rest.split(ae).join(esc);
+ }
+ }
- this._writableState = new WritableState(options, this);
- // legacy.
- this.writable = true;
+ // chop off from the tail first.
+ var hash = rest.indexOf('#');
+ if (hash !== -1) {
+ // got a fragment string.
+ this.hash = rest.substr(hash);
+ rest = rest.slice(0, hash);
+ }
+ var qm = rest.indexOf('?');
+ if (qm !== -1) {
+ this.search = rest.substr(qm);
+ this.query = rest.substr(qm + 1);
+ if (parseQueryString) {
+ this.query = querystring.parse(this.query);
+ }
+ rest = rest.slice(0, qm);
+ } else if (parseQueryString) {
+ // no query string, but parseQueryString still requested
+ this.search = '';
+ this.query = {};
+ }
+ if (rest) this.pathname = rest;
+ if (slashedProtocol[lowerProto] &&
+ this.hostname && !this.pathname) {
+ this.pathname = '/';
+ }
- Stream.call(this);
-}
+ //to support http.request
+ if (this.pathname || this.search) {
+ var p = this.pathname || '';
+ var s = this.search || '';
+ this.path = p + s;
+ }
-// Otherwise people can pipe Writable streams, which is just wrong.
-Writable.prototype.pipe = function() {
- this.emit('error', new Error('Cannot pipe. Not readable.'));
+ // finally, reconstruct the href based on what has been validated.
+ this.href = this.format();
+ return this;
};
-
-function writeAfterEnd(stream, state, cb) {
- var er = new Error('write after end');
- // TODO: defer error events consistently everywhere, not just the cb
- stream.emit('error', er);
- process.nextTick(function() {
- cb(er);
- });
+// format a parsed object into a url string
+function urlFormat(obj) {
+ // ensure it's an object, and not a string url.
+ // If it's an obj, this is a no-op.
+ // this way, you can call url_format() on strings
+ // to clean up potentially wonky urls.
+ if (isString(obj)) obj = urlParse(obj);
+ if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
+ return obj.format();
}
-// If we get something that is not a buffer, string, null, or undefined,
-// and we're not in objectMode, then that's an error.
-// Otherwise stream chunks are all considered to be of length=1, and the
-// watermarks determine how many objects to keep in the buffer, rather than
-// how many bytes or characters.
-function validChunk(stream, state, chunk, cb) {
- var valid = true;
- if (!Buffer.isBuffer(chunk) &&
- 'string' !== typeof chunk &&
- chunk !== null &&
- chunk !== undefined &&
- !state.objectMode) {
- var er = new TypeError('Invalid non-string/buffer chunk');
- stream.emit('error', er);
- process.nextTick(function() {
- cb(er);
- });
- valid = false;
+Url.prototype.format = function() {
+ var auth = this.auth || '';
+ if (auth) {
+ auth = encodeURIComponent(auth);
+ auth = auth.replace(/%3A/i, ':');
+ auth += '@';
}
- return valid;
-}
-Writable.prototype.write = function(chunk, encoding, cb) {
- var state = this._writableState;
- var ret = false;
+ var protocol = this.protocol || '',
+ pathname = this.pathname || '',
+ hash = this.hash || '',
+ host = false,
+ query = '';
- if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
+ if (this.host) {
+ host = auth + this.host;
+ } else if (this.hostname) {
+ host = auth + (this.hostname.indexOf(':') === -1 ?
+ this.hostname :
+ '[' + this.hostname + ']');
+ if (this.port) {
+ host += ':' + this.port;
+ }
}
- if (Buffer.isBuffer(chunk))
- encoding = 'buffer';
- else if (!encoding)
- encoding = state.defaultEncoding;
+ if (this.query &&
+ isObject(this.query) &&
+ Object.keys(this.query).length) {
+ query = querystring.stringify(this.query);
+ }
- if (typeof cb !== 'function')
- cb = function() {};
+ var search = this.search || (query && ('?' + query)) || '';
- if (state.ended)
- writeAfterEnd(this, state, cb);
- else if (validChunk(this, state, chunk, cb))
- ret = writeOrBuffer(this, state, chunk, encoding, cb);
+ if (protocol && protocol.substr(-1) !== ':') protocol += ':';
- return ret;
+ // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
+ // unless they had them to begin with.
+ if (this.slashes ||
+ (!protocol || slashedProtocol[protocol]) && host !== false) {
+ host = '//' + (host || '');
+ if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
+ } else if (!host) {
+ host = '';
+ }
+
+ if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
+ if (search && search.charAt(0) !== '?') search = '?' + search;
+
+ pathname = pathname.replace(/[?#]/g, function(match) {
+ return encodeURIComponent(match);
+ });
+ search = search.replace('#', '%23');
+
+ return protocol + host + pathname + search + hash;
};
-function decodeChunk(state, chunk, encoding) {
- if (!state.objectMode &&
- state.decodeStrings !== false &&
- typeof chunk === 'string') {
- chunk = new Buffer(chunk, encoding);
- }
- return chunk;
+function urlResolve(source, relative) {
+ return urlParse(source, false, true).resolve(relative);
}
-// if we're already writing something, then just put this
-// in the queue, and wait our turn. Otherwise, call _write
-// If we return false, then we need a drain event, so set that flag.
-function writeOrBuffer(stream, state, chunk, encoding, cb) {
- chunk = decodeChunk(state, chunk, encoding);
- if (Buffer.isBuffer(chunk))
- encoding = 'buffer';
- var len = state.objectMode ? 1 : chunk.length;
+Url.prototype.resolve = function(relative) {
+ return this.resolveObject(urlParse(relative, false, true)).format();
+};
- state.length += len;
+function urlResolveObject(source, relative) {
+ if (!source) return relative;
+ return urlParse(source, false, true).resolveObject(relative);
+}
- var ret = state.length < state.highWaterMark;
- // we must ensure that previous needDrain will not be reset to false.
- if (!ret)
- state.needDrain = true;
+Url.prototype.resolveObject = function(relative) {
+ if (isString(relative)) {
+ var rel = new Url();
+ rel.parse(relative, false, true);
+ relative = rel;
+ }
- if (state.writing)
- state.buffer.push(new WriteReq(chunk, encoding, cb));
- else
- doWrite(stream, state, len, chunk, encoding, cb);
+ var result = new Url();
+ Object.keys(this).forEach(function(k) {
+ result[k] = this[k];
+ }, this);
- return ret;
-}
+ // hash is always overridden, no matter what.
+ // even href="" will remove it.
+ result.hash = relative.hash;
-function doWrite(stream, state, len, chunk, encoding, cb) {
- state.writelen = len;
- state.writecb = cb;
- state.writing = true;
- state.sync = true;
- stream._write(chunk, encoding, state.onwrite);
- state.sync = false;
-}
+ // if the relative url is empty, then there's nothing left to do here.
+ if (relative.href === '') {
+ result.href = result.format();
+ return result;
+ }
-function onwriteError(stream, state, sync, er, cb) {
- if (sync)
- process.nextTick(function() {
- cb(er);
+ // hrefs like //foo/bar always cut to the protocol.
+ if (relative.slashes && !relative.protocol) {
+ // take everything except the protocol from relative
+ Object.keys(relative).forEach(function(k) {
+ if (k !== 'protocol')
+ result[k] = relative[k];
});
- else
- cb(er);
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
-}
+ //urlParse appends trailing / to urls like http://www.example.com
+ if (slashedProtocol[result.protocol] &&
+ result.hostname && !result.pathname) {
+ result.path = result.pathname = '/';
+ }
-function onwriteStateUpdate(state) {
- state.writing = false;
- state.writecb = null;
- state.length -= state.writelen;
- state.writelen = 0;
-}
+ result.href = result.format();
+ return result;
+ }
-function onwrite(stream, er) {
- var state = stream._writableState;
- var sync = state.sync;
- var cb = state.writecb;
+ if (relative.protocol && relative.protocol !== result.protocol) {
+ // if it's a known url protocol, then changing
+ // the protocol does weird things
+ // first, if it's not file:, then we MUST have a host,
+ // and if there was a path
+ // to begin with, then we MUST have a path.
+ // if it is file:, then the host is dropped,
+ // because that's known to be hostless.
+ // anything else is assumed to be absolute.
+ if (!slashedProtocol[relative.protocol]) {
+ Object.keys(relative).forEach(function(k) {
+ result[k] = relative[k];
+ });
+ result.href = result.format();
+ return result;
+ }
- onwriteStateUpdate(state);
+ result.protocol = relative.protocol;
+ if (!relative.host && !hostlessProtocol[relative.protocol]) {
+ var relPath = (relative.pathname || '').split('/');
+ while (relPath.length && !(relative.host = relPath.shift()));
+ if (!relative.host) relative.host = '';
+ if (!relative.hostname) relative.hostname = '';
+ if (relPath[0] !== '') relPath.unshift('');
+ if (relPath.length < 2) relPath.unshift('');
+ result.pathname = relPath.join('/');
+ } else {
+ result.pathname = relative.pathname;
+ }
+ result.search = relative.search;
+ result.query = relative.query;
+ result.host = relative.host || '';
+ result.auth = relative.auth;
+ result.hostname = relative.hostname || relative.host;
+ result.port = relative.port;
+ // to support http.request
+ if (result.pathname || result.search) {
+ var p = result.pathname || '';
+ var s = result.search || '';
+ result.path = p + s;
+ }
+ result.slashes = result.slashes || relative.slashes;
+ result.href = result.format();
+ return result;
+ }
- if (er)
- onwriteError(stream, state, sync, er, cb);
- else {
- // Check if we're actually ready to finish, but don't emit yet
- var finished = needFinish(stream, state);
+ var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
+ isRelAbs = (
+ relative.host ||
+ relative.pathname && relative.pathname.charAt(0) === '/'
+ ),
+ mustEndAbs = (isRelAbs || isSourceAbs ||
+ (result.host && relative.pathname)),
+ removeAllDots = mustEndAbs,
+ srcPath = result.pathname && result.pathname.split('/') || [],
+ relPath = relative.pathname && relative.pathname.split('/') || [],
+ psychotic = result.protocol && !slashedProtocol[result.protocol];
- if (!finished && !state.bufferProcessing && state.buffer.length)
- clearBuffer(stream, state);
+ // if the url is a non-slashed url, then relative
+ // links like ../.. should be able
+ // to crawl up to the hostname, as well. This is strange.
+ // result.protocol has already been set by now.
+ // Later on, put the first path part into the host field.
+ if (psychotic) {
+ result.hostname = '';
+ result.port = null;
+ if (result.host) {
+ if (srcPath[0] === '') srcPath[0] = result.host;
+ else srcPath.unshift(result.host);
+ }
+ result.host = '';
+ if (relative.protocol) {
+ relative.hostname = null;
+ relative.port = null;
+ if (relative.host) {
+ if (relPath[0] === '') relPath[0] = relative.host;
+ else relPath.unshift(relative.host);
+ }
+ relative.host = null;
+ }
+ mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
+ }
- if (sync) {
- process.nextTick(function() {
- afterWrite(stream, state, finished, cb);
- });
+ if (isRelAbs) {
+ // it's absolute.
+ result.host = (relative.host || relative.host === '') ?
+ relative.host : result.host;
+ result.hostname = (relative.hostname || relative.hostname === '') ?
+ relative.hostname : result.hostname;
+ result.search = relative.search;
+ result.query = relative.query;
+ srcPath = relPath;
+ // fall through to the dot-handling below.
+ } else if (relPath.length) {
+ // it's relative
+ // throw away the existing file, and take the new path instead.
+ if (!srcPath) srcPath = [];
+ srcPath.pop();
+ srcPath = srcPath.concat(relPath);
+ result.search = relative.search;
+ result.query = relative.query;
+ } else if (!isNullOrUndefined(relative.search)) {
+ // just pull out the search.
+ // like href='?foo'.
+ // Put this after the other two cases because it simplifies the booleans
+ if (psychotic) {
+ result.hostname = result.host = srcPath.shift();
+ //occationaly the auth can get stuck only in host
+ //this especialy happens in cases like
+ //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
+ var authInHost = result.host && result.host.indexOf('@') > 0 ?
+ result.host.split('@') : false;
+ if (authInHost) {
+ result.auth = authInHost.shift();
+ result.host = result.hostname = authInHost.shift();
+ }
+ }
+ result.search = relative.search;
+ result.query = relative.query;
+ //to support http.request
+ if (!isNull(result.pathname) || !isNull(result.search)) {
+ result.path = (result.pathname ? result.pathname : '') +
+ (result.search ? result.search : '');
+ }
+ result.href = result.format();
+ return result;
+ }
+
+ if (!srcPath.length) {
+ // no path at all. easy.
+ // we've already handled the other stuff above.
+ result.pathname = null;
+ //to support http.request
+ if (result.search) {
+ result.path = '/' + result.search;
} else {
- afterWrite(stream, state, finished, cb);
+ result.path = null;
+ }
+ result.href = result.format();
+ return result;
+ }
+
+ // if a url ENDs in . or .., then it must get a trailing slash.
+ // however, if it ends in anything else non-slashy,
+ // then it must NOT get a trailing slash.
+ var last = srcPath.slice(-1)[0];
+ var hasTrailingSlash = (
+ (result.host || relative.host) && (last === '.' || last === '..') ||
+ last === '');
+
+ // strip single dots, resolve double dots to parent dir
+ // if the path tries to go above the root, `up` ends up > 0
+ var up = 0;
+ for (var i = srcPath.length; i >= 0; i--) {
+ last = srcPath[i];
+ if (last == '.') {
+ srcPath.splice(i, 1);
+ } else if (last === '..') {
+ srcPath.splice(i, 1);
+ up++;
+ } else if (up) {
+ srcPath.splice(i, 1);
+ up--;
}
}
-}
-
-function afterWrite(stream, state, finished, cb) {
- if (!finished)
- onwriteDrain(stream, state);
- cb();
- if (finished)
- finishMaybe(stream, state);
-}
-// Must force callback to be called on nextTick, so that we don't
-// emit 'drain' before the write() consumer gets the 'false' return
-// value, and has a chance to attach a 'drain' listener.
-function onwriteDrain(stream, state) {
- if (state.length === 0 && state.needDrain) {
- state.needDrain = false;
- stream.emit('drain');
+ // if the path is allowed to go above the root, restore leading ..s
+ if (!mustEndAbs && !removeAllDots) {
+ for (; up--; up) {
+ srcPath.unshift('..');
+ }
}
-}
+ if (mustEndAbs && srcPath[0] !== '' &&
+ (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
+ srcPath.unshift('');
+ }
-// if there's something in the buffer waiting, then process it
-function clearBuffer(stream, state) {
- state.bufferProcessing = true;
-
- for (var c = 0; c < state.buffer.length; c++) {
- var entry = state.buffer[c];
- var chunk = entry.chunk;
- var encoding = entry.encoding;
- var cb = entry.callback;
- var len = state.objectMode ? 1 : chunk.length;
+ if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
+ srcPath.push('');
+ }
- doWrite(stream, state, len, chunk, encoding, cb);
+ var isAbsolute = srcPath[0] === '' ||
+ (srcPath[0] && srcPath[0].charAt(0) === '/');
- // if we didn't call the onwrite immediately, then
- // it means that we need to wait until it does.
- // also, that means that the chunk and cb are currently
- // being processed, so move the buffer counter past them.
- if (state.writing) {
- c++;
- break;
+ // put the host back
+ if (psychotic) {
+ result.hostname = result.host = isAbsolute ? '' :
+ srcPath.length ? srcPath.shift() : '';
+ //occationaly the auth can get stuck only in host
+ //this especialy happens in cases like
+ //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
+ var authInHost = result.host && result.host.indexOf('@') > 0 ?
+ result.host.split('@') : false;
+ if (authInHost) {
+ result.auth = authInHost.shift();
+ result.host = result.hostname = authInHost.shift();
}
}
- state.bufferProcessing = false;
- if (c < state.buffer.length)
- state.buffer = state.buffer.slice(c);
- else
- state.buffer.length = 0;
-}
-
-Writable.prototype._write = function(chunk, encoding, cb) {
- cb(new Error('not implemented'));
-};
-
-Writable.prototype.end = function(chunk, encoding, cb) {
- var state = this._writableState;
+ mustEndAbs = mustEndAbs || (result.host && srcPath.length);
- if (typeof chunk === 'function') {
- cb = chunk;
- chunk = null;
- encoding = null;
- } else if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
+ if (mustEndAbs && !isAbsolute) {
+ srcPath.unshift('');
}
- if (typeof chunk !== 'undefined' && chunk !== null)
- this.write(chunk, encoding);
-
- // ignore unnecessary end() calls.
- if (!state.ending && !state.finished)
- endWritable(this, state, cb);
-};
-
-
-function needFinish(stream, state) {
- return (state.ending &&
- state.length === 0 &&
- !state.finished &&
- !state.writing);
-}
-
-function finishMaybe(stream, state) {
- var need = needFinish(stream, state);
- if (need) {
- state.finished = true;
- stream.emit('finish');
+ if (!srcPath.length) {
+ result.pathname = null;
+ result.path = null;
+ } else {
+ result.pathname = srcPath.join('/');
}
- return need;
-}
-function endWritable(stream, state, cb) {
- state.ending = true;
- finishMaybe(stream, state);
- if (cb) {
- if (state.finished)
- process.nextTick(cb);
- else
- stream.once('finish', cb);
+ //to support request.http
+ if (!isNull(result.pathname) || !isNull(result.search)) {
+ result.path = (result.pathname ? result.pathname : '') +
+ (result.search ? result.search : '');
}
- state.ended = true;
-}
+ result.auth = relative.auth || result.auth;
+ result.slashes = result.slashes || relative.slashes;
+ result.href = result.format();
+ return result;
+};
-}).call(this,require('_process'))
-},{"./_stream_duplex":172,"_process":64,"buffer":6,"core-util-is":176,"inherits":177,"stream":81}],176:[function(require,module,exports){
-arguments[4][11][0].apply(exports,arguments)
-},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21,"dup":11}],177:[function(require,module,exports){
-arguments[4][18][0].apply(exports,arguments)
-},{"dup":18}],178:[function(require,module,exports){
-arguments[4][22][0].apply(exports,arguments)
-},{"dup":22}],179:[function(require,module,exports){
-arguments[4][86][0].apply(exports,arguments)
-},{"buffer":6,"dup":86}],180:[function(require,module,exports){
-arguments[4][77][0].apply(exports,arguments)
-},{"./lib/_stream_transform.js":174,"dup":77}],181:[function(require,module,exports){
-arguments[4][55][0].apply(exports,arguments)
-},{"dup":55}],182:[function(require,module,exports){
-(function (process){
-var Transform = require('readable-stream/transform')
- , inherits = require('util').inherits
- , xtend = require('xtend')
+Url.prototype.parseHost = function() {
+ var host = this.host;
+ var port = portPattern.exec(host);
+ if (port) {
+ port = port[0];
+ if (port !== ':') {
+ this.port = port.substr(1);
+ }
+ host = host.substr(0, host.length - port.length);
+ }
+ if (host) this.hostname = host;
+};
-function DestroyableTransform(opts) {
- Transform.call(this, opts)
- this._destroyed = false
+function isString(arg) {
+ return typeof arg === "string";
}
-inherits(DestroyableTransform, Transform)
-
-DestroyableTransform.prototype.destroy = function(err) {
- if (this._destroyed) return
- this._destroyed = true
-
- var self = this
- process.nextTick(function() {
- if (err)
- self.emit('error', err)
- self.emit('close')
- })
+function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
}
-// a noop _transform function
-function noop (chunk, enc, callback) {
- callback(null, chunk)
+function isNull(arg) {
+ return arg === null;
}
-
-
-// create a new export function, used by both the main export and
-// the .ctor export, contains common logic for dealing with arguments
-function through2 (construct) {
- return function (options, transform, flush) {
- if (typeof options == 'function') {
- flush = transform
- transform = options
- options = {}
- }
-
- if (typeof transform != 'function')
- transform = noop
-
- if (typeof flush != 'function')
- flush = null
-
- return construct(options, transform, flush)
- }
+function isNullOrUndefined(arg) {
+ return arg == null;
}
+},{"punycode":108,"querystring":111}],136:[function(require,module,exports){
+(function (global){
-// main export, just make me a transform stream!
-module.exports = through2(function (options, transform, flush) {
- var t2 = new DestroyableTransform(options)
-
- t2._transform = transform
-
- if (flush)
- t2._flush = flush
-
- return t2
-})
-
-
-// make me a reusable prototype that I can `new`, or implicitly `new`
-// with a constructor call
-module.exports.ctor = through2(function (options, transform, flush) {
- function Through2 (override) {
- if (!(this instanceof Through2))
- return new Through2(override)
-
- this.options = xtend(options, override)
-
- DestroyableTransform.call(this, this.options)
- }
-
- inherits(Through2, DestroyableTransform)
-
- Through2.prototype._transform = transform
-
- if (flush)
- Through2.prototype._flush = flush
-
- return Through2
-})
-
-
-module.exports.obj = through2(function (options, transform, flush) {
- var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options))
-
- t2._transform = transform
+/**
+ * Module exports.
+ */
- if (flush)
- t2._flush = flush
+module.exports = deprecate;
- return t2
-})
+/**
+ * Mark that a method should not be used.
+ * Returns a modified function which warns once by default.
+ *
+ * If `localStorage.noDeprecation = true` is set, then it is a no-op.
+ *
+ * If `localStorage.throwDeprecation = true` is set, then deprecated functions
+ * will throw an Error when invoked.
+ *
+ * If `localStorage.traceDeprecation = true` is set, then deprecated functions
+ * will invoke `console.trace()` instead of `console.error()`.
+ *
+ * @param {Function} fn - the function to deprecate
+ * @param {String} msg - the string to print to the console when `fn` is invoked
+ * @returns {Function} a new "deprecated" version of `fn`
+ * @api public
+ */
-}).call(this,require('_process'))
-},{"_process":64,"readable-stream/transform":180,"util":90,"xtend":181}],183:[function(require,module,exports){
-(function (global){
-'use strict';
+function deprecate (fn, msg) {
+ if (config('noDeprecation')) {
+ return fn;
+ }
-var filter = require('through2-filter').obj;
-var ES6Set;
-if (typeof global.Set === 'function') {
- ES6Set = global.Set;
-} else {
- ES6Set = function() {
- this.keys = [];
- this.has = function(val) {
- return this.keys.indexOf(val) !== -1;
- },
- this.add = function(val) {
- this.keys.push(val);
+ var warned = false;
+ function deprecated() {
+ if (!warned) {
+ if (config('throwDeprecation')) {
+ throw new Error(msg);
+ } else if (config('traceDeprecation')) {
+ console.trace(msg);
+ } else {
+ console.warn(msg);
+ }
+ warned = true;
}
+ return fn.apply(this, arguments);
}
-}
-function prop(propName) {
- return function (data) {
- return data[propName];
- };
+ return deprecated;
}
-module.exports = unique;
-function unique(propName, keyStore) {
- keyStore = keyStore || new ES6Set();
+/**
+ * Checks `localStorage` for boolean values for the given `name`.
+ *
+ * @param {String} name
+ * @returns {Boolean}
+ * @api private
+ */
- var keyfn = JSON.stringify;
- if (typeof propName === 'string') {
- keyfn = prop(propName);
- } else if (typeof propName === 'function') {
- keyfn = propName;
+function config (name) {
+ // accessing global.localStorage can trigger a DOMException in sandboxed iframes
+ try {
+ if (!global.localStorage) return false;
+ } catch (_) {
+ return false;
}
+ var val = global.localStorage[name];
+ if (null == val) return false;
+ return String(val).toLowerCase() === 'true';
+}
- return filter(function (data) {
- var key = keyfn(data);
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],137:[function(require,module,exports){
+module.exports = function isBuffer(arg) {
+ return arg && typeof arg === 'object'
+ && typeof arg.copy === 'function'
+ && typeof arg.fill === 'function'
+ && typeof arg.readUInt8 === 'function';
+}
+},{}],138:[function(require,module,exports){
+(function (process,global){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
- if (keyStore.has(key)) {
- return false;
+var formatRegExp = /%[sdj%]/g;
+exports.format = function(f) {
+ if (!isString(f)) {
+ var objects = [];
+ for (var i = 0; i < arguments.length; i++) {
+ objects.push(inspect(arguments[i]));
}
+ return objects.join(' ');
+ }
- keyStore.add(key);
- return true;
+ var i = 1;
+ var args = arguments;
+ var len = args.length;
+ var str = String(f).replace(formatRegExp, function(x) {
+ if (x === '%%') return '%';
+ if (i >= len) return x;
+ switch (x) {
+ case '%s': return String(args[i++]);
+ case '%d': return Number(args[i++]);
+ case '%j':
+ try {
+ return JSON.stringify(args[i++]);
+ } catch (_) {
+ return '[Circular]';
+ }
+ default:
+ return x;
+ }
});
-}
+ for (var x = args[i]; i < len; x = args[++i]) {
+ if (isNull(x) || !isObject(x)) {
+ str += ' ' + x;
+ } else {
+ str += ' ' + inspect(x);
+ }
+ }
+ return str;
+};
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"through2-filter":234}],184:[function(require,module,exports){
-'use strict'
-var fs = require('fs')
+// Mark that a method should not be used.
+// Returns a modified function which warns once by default.
+// If --no-deprecation is set, then it is a no-op.
+exports.deprecate = function(fn, msg) {
+ // Allow for deprecating things in the process of starting up.
+ if (isUndefined(global.process)) {
+ return function() {
+ return exports.deprecate(fn, msg).apply(this, arguments);
+ };
+ }
-module.exports = clone(fs)
+ if (process.noDeprecation === true) {
+ return fn;
+ }
-function clone (obj) {
- if (obj === null || typeof obj !== 'object')
- return obj
+ var warned = false;
+ function deprecated() {
+ if (!warned) {
+ if (process.throwDeprecation) {
+ throw new Error(msg);
+ } else if (process.traceDeprecation) {
+ console.trace(msg);
+ } else {
+ console.error(msg);
+ }
+ warned = true;
+ }
+ return fn.apply(this, arguments);
+ }
- if (obj instanceof Object)
- var copy = { __proto__: obj.__proto__ }
- else
- var copy = Object.create(null)
+ return deprecated;
+};
- Object.getOwnPropertyNames(obj).forEach(function (key) {
- Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))
- })
- return copy
+var debugs = {};
+var debugEnviron;
+exports.debuglog = function(set) {
+ if (isUndefined(debugEnviron))
+ debugEnviron = process.env.NODE_DEBUG || '';
+ set = set.toUpperCase();
+ if (!debugs[set]) {
+ if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
+ var pid = process.pid;
+ debugs[set] = function() {
+ var msg = exports.format.apply(exports, arguments);
+ console.error('%s %d: %s', set, pid, msg);
+ };
+ } else {
+ debugs[set] = function() {};
+ }
+ }
+ return debugs[set];
+};
+
+
+/**
+ * Echos the value of a value. Trys to print the value out
+ * in the best way possible given the different types.
+ *
+ * @param {Object} obj The object to print out.
+ * @param {Object} opts Optional options object that alters the output.
+ */
+/* legacy: obj, showHidden, depth, colors*/
+function inspect(obj, opts) {
+ // default options
+ var ctx = {
+ seen: [],
+ stylize: stylizeNoColor
+ };
+ // legacy...
+ if (arguments.length >= 3) ctx.depth = arguments[2];
+ if (arguments.length >= 4) ctx.colors = arguments[3];
+ if (isBoolean(opts)) {
+ // legacy...
+ ctx.showHidden = opts;
+ } else if (opts) {
+ // got an "options" object
+ exports._extend(ctx, opts);
+ }
+ // set default options
+ if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
+ if (isUndefined(ctx.depth)) ctx.depth = 2;
+ if (isUndefined(ctx.colors)) ctx.colors = false;
+ if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
+ if (ctx.colors) ctx.stylize = stylizeWithColor;
+ return formatValue(ctx, obj, ctx.depth);
}
+exports.inspect = inspect;
-},{"fs":4}],185:[function(require,module,exports){
-(function (process){
-var fs = require('fs')
-var polyfills = require('./polyfills.js')
-var legacy = require('./legacy-streams.js')
-var queue = []
-var util = require('util')
+// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
+inspect.colors = {
+ 'bold' : [1, 22],
+ 'italic' : [3, 23],
+ 'underline' : [4, 24],
+ 'inverse' : [7, 27],
+ 'white' : [37, 39],
+ 'grey' : [90, 39],
+ 'black' : [30, 39],
+ 'blue' : [34, 39],
+ 'cyan' : [36, 39],
+ 'green' : [32, 39],
+ 'magenta' : [35, 39],
+ 'red' : [31, 39],
+ 'yellow' : [33, 39]
+};
+
+// Don't use 'blue' not visible on cmd.exe
+inspect.styles = {
+ 'special': 'cyan',
+ 'number': 'yellow',
+ 'boolean': 'yellow',
+ 'undefined': 'grey',
+ 'null': 'bold',
+ 'string': 'green',
+ 'date': 'magenta',
+ // "name": intentionally not styling
+ 'regexp': 'red'
+};
+
-function noop () {}
+function stylizeWithColor(str, styleType) {
+ var style = inspect.styles[styleType];
-var debug = noop
-if (util.debuglog)
- debug = util.debuglog('gfs4')
-else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
- debug = function() {
- var m = util.format.apply(util, arguments)
- m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
- console.error(m)
+ if (style) {
+ return '\u001b[' + inspect.colors[style][0] + 'm' + str +
+ '\u001b[' + inspect.colors[style][1] + 'm';
+ } else {
+ return str;
}
-
-if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
- process.on('exit', function() {
- debug(queue)
- require('assert').equal(queue.length, 0)
- })
}
-module.exports = patch(require('./fs.js'))
-if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) {
- module.exports = patch(fs)
+
+function stylizeNoColor(str, styleType) {
+ return str;
}
-// Always patch fs.close/closeSync, because we want to
-// retry() whenever a close happens *anywhere* in the program.
-// This is essential when multiple graceful-fs instances are
-// in play at the same time.
-fs.close = (function (fs$close) { return function (fd, cb) {
- return fs$close.call(fs, fd, function (err) {
- if (!err)
- retry()
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- })
-}})(fs.close)
+function arrayToHash(array) {
+ var hash = {};
-fs.closeSync = (function (fs$closeSync) { return function (fd) {
- // Note that graceful-fs also retries when fs.closeSync() fails.
- // Looks like a bug to me, although it's probably a harmless one.
- var rval = fs$closeSync.apply(fs, arguments)
- retry()
- return rval
-}})(fs.closeSync)
+ array.forEach(function(val, idx) {
+ hash[val] = true;
+ });
-function patch (fs) {
- // Everything that references the open() function needs to be in here
- polyfills(fs)
- fs.gracefulify = patch
- fs.FileReadStream = ReadStream; // Legacy name.
- fs.FileWriteStream = WriteStream; // Legacy name.
- fs.createReadStream = createReadStream
- fs.createWriteStream = createWriteStream
- var fs$readFile = fs.readFile
- fs.readFile = readFile
- function readFile (path, options, cb) {
- if (typeof options === 'function')
- cb = options, options = null
+ return hash;
+}
- return go$readFile(path, options, cb)
- function go$readFile (path, options, cb) {
- return fs$readFile(path, options, function (err) {
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$readFile, [path, options, cb]])
- else {
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- retry()
- }
- })
+function formatValue(ctx, value, recurseTimes) {
+ // Provide a hook for user-specified inspect functions.
+ // Check that value is an object with an inspect function on it
+ if (ctx.customInspect &&
+ value &&
+ isFunction(value.inspect) &&
+ // Filter out the util module, it's inspect function is special
+ value.inspect !== exports.inspect &&
+ // Also filter out any prototype objects using the circular check.
+ !(value.constructor && value.constructor.prototype === value)) {
+ var ret = value.inspect(recurseTimes, ctx);
+ if (!isString(ret)) {
+ ret = formatValue(ctx, ret, recurseTimes);
}
+ return ret;
}
- var fs$writeFile = fs.writeFile
- fs.writeFile = writeFile
- function writeFile (path, data, options, cb) {
- if (typeof options === 'function')
- cb = options, options = null
+ // Primitive types cannot have properties
+ var primitive = formatPrimitive(ctx, value);
+ if (primitive) {
+ return primitive;
+ }
- return go$writeFile(path, data, options, cb)
+ // Look up the keys of the object.
+ var keys = Object.keys(value);
+ var visibleKeys = arrayToHash(keys);
- function go$writeFile (path, data, options, cb) {
- return fs$writeFile(path, data, options, function (err) {
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$writeFile, [path, data, options, cb]])
- else {
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- retry()
- }
- })
+ if (ctx.showHidden) {
+ keys = Object.getOwnPropertyNames(value);
+ }
+
+ // IE doesn't make error fields non-enumerable
+ // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
+ if (isError(value)
+ && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
+ return formatError(value);
+ }
+
+ // Some type of object without properties can be shortcutted.
+ if (keys.length === 0) {
+ if (isFunction(value)) {
+ var name = value.name ? ': ' + value.name : '';
+ return ctx.stylize('[Function' + name + ']', 'special');
+ }
+ if (isRegExp(value)) {
+ return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+ }
+ if (isDate(value)) {
+ return ctx.stylize(Date.prototype.toString.call(value), 'date');
+ }
+ if (isError(value)) {
+ return formatError(value);
}
}
- var fs$appendFile = fs.appendFile
- if (fs$appendFile)
- fs.appendFile = appendFile
- function appendFile (path, data, options, cb) {
- if (typeof options === 'function')
- cb = options, options = null
+ var base = '', array = false, braces = ['{', '}'];
- return go$appendFile(path, data, options, cb)
+ // Make Array say that they are Array
+ if (isArray(value)) {
+ array = true;
+ braces = ['[', ']'];
+ }
- function go$appendFile (path, data, options, cb) {
- return fs$appendFile(path, data, options, function (err) {
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$appendFile, [path, data, options, cb]])
- else {
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- retry()
- }
- })
- }
+ // Make functions say that they are functions
+ if (isFunction(value)) {
+ var n = value.name ? ': ' + value.name : '';
+ base = ' [Function' + n + ']';
}
- var fs$readdir = fs.readdir
- fs.readdir = readdir
- function readdir (path, cb) {
- return go$readdir(path, cb)
+ // Make RegExps say that they are RegExps
+ if (isRegExp(value)) {
+ base = ' ' + RegExp.prototype.toString.call(value);
+ }
- function go$readdir () {
- return fs$readdir(path, function (err, files) {
- if (files && files.sort)
- files.sort(); // Backwards compatibility with graceful-fs.
+ // Make dates with properties first say the date
+ if (isDate(value)) {
+ base = ' ' + Date.prototype.toUTCString.call(value);
+ }
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$readdir, [path, cb]])
- else {
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- retry()
- }
- })
+ // Make error with message first say the error
+ if (isError(value)) {
+ base = ' ' + formatError(value);
+ }
+
+ if (keys.length === 0 && (!array || value.length == 0)) {
+ return braces[0] + base + braces[1];
+ }
+
+ if (recurseTimes < 0) {
+ if (isRegExp(value)) {
+ return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+ } else {
+ return ctx.stylize('[Object]', 'special');
}
}
+ ctx.seen.push(value);
- if (process.version.substr(0, 4) === 'v0.8') {
- var legStreams = legacy(fs)
- ReadStream = legStreams.ReadStream
- WriteStream = legStreams.WriteStream
+ var output;
+ if (array) {
+ output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
+ } else {
+ output = keys.map(function(key) {
+ return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
+ });
}
- var fs$ReadStream = fs.ReadStream
- ReadStream.prototype = Object.create(fs$ReadStream.prototype)
- ReadStream.prototype.open = ReadStream$open
+ ctx.seen.pop();
+
+ return reduceToSingleString(output, base, braces);
+}
+
+
+function formatPrimitive(ctx, value) {
+ if (isUndefined(value))
+ return ctx.stylize('undefined', 'undefined');
+ if (isString(value)) {
+ var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
+ .replace(/'/g, "\\'")
+ .replace(/\\"/g, '"') + '\'';
+ return ctx.stylize(simple, 'string');
+ }
+ if (isNumber(value))
+ return ctx.stylize('' + value, 'number');
+ if (isBoolean(value))
+ return ctx.stylize('' + value, 'boolean');
+ // For some reason typeof null is "object", so special case here.
+ if (isNull(value))
+ return ctx.stylize('null', 'null');
+}
+
- var fs$WriteStream = fs.WriteStream
- WriteStream.prototype = Object.create(fs$WriteStream.prototype)
- WriteStream.prototype.open = WriteStream$open
+function formatError(value) {
+ return '[' + Error.prototype.toString.call(value) + ']';
+}
- fs.ReadStream = ReadStream
- fs.WriteStream = WriteStream
- function ReadStream (path, options) {
- if (this instanceof ReadStream)
- return fs$ReadStream.apply(this, arguments), this
- else
- return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
+function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
+ var output = [];
+ for (var i = 0, l = value.length; i < l; ++i) {
+ if (hasOwnProperty(value, String(i))) {
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
+ String(i), true));
+ } else {
+ output.push('');
+ }
}
+ keys.forEach(function(key) {
+ if (!key.match(/^\d+$/)) {
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
+ key, true));
+ }
+ });
+ return output;
+}
- function ReadStream$open () {
- var that = this
- open(that.path, that.flags, that.mode, function (err, fd) {
- if (err) {
- if (that.autoClose)
- that.destroy()
- that.emit('error', err)
- } else {
- that.fd = fd
- that.emit('open', fd)
- that.read()
- }
- })
+function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
+ var name, str, desc;
+ desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
+ if (desc.get) {
+ if (desc.set) {
+ str = ctx.stylize('[Getter/Setter]', 'special');
+ } else {
+ str = ctx.stylize('[Getter]', 'special');
+ }
+ } else {
+ if (desc.set) {
+ str = ctx.stylize('[Setter]', 'special');
+ }
}
-
- function WriteStream (path, options) {
- if (this instanceof WriteStream)
- return fs$WriteStream.apply(this, arguments), this
- else
- return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
+ if (!hasOwnProperty(visibleKeys, key)) {
+ name = '[' + key + ']';
}
-
- function WriteStream$open () {
- var that = this
- open(that.path, that.flags, that.mode, function (err, fd) {
- if (err) {
- that.destroy()
- that.emit('error', err)
+ if (!str) {
+ if (ctx.seen.indexOf(desc.value) < 0) {
+ if (isNull(recurseTimes)) {
+ str = formatValue(ctx, desc.value, null);
} else {
- that.fd = fd
- that.emit('open', fd)
+ str = formatValue(ctx, desc.value, recurseTimes - 1);
}
- })
+ if (str.indexOf('\n') > -1) {
+ if (array) {
+ str = str.split('\n').map(function(line) {
+ return ' ' + line;
+ }).join('\n').substr(2);
+ } else {
+ str = '\n' + str.split('\n').map(function(line) {
+ return ' ' + line;
+ }).join('\n');
+ }
+ }
+ } else {
+ str = ctx.stylize('[Circular]', 'special');
+ }
}
-
- function createReadStream (path, options) {
- return new ReadStream(path, options)
+ if (isUndefined(name)) {
+ if (array && key.match(/^\d+$/)) {
+ return str;
+ }
+ name = JSON.stringify('' + key);
+ if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
+ name = name.substr(1, name.length - 2);
+ name = ctx.stylize(name, 'name');
+ } else {
+ name = name.replace(/'/g, "\\'")
+ .replace(/\\"/g, '"')
+ .replace(/(^"|"$)/g, "'");
+ name = ctx.stylize(name, 'string');
+ }
}
- function createWriteStream (path, options) {
- return new WriteStream(path, options)
- }
+ return name + ': ' + str;
+}
- var fs$open = fs.open
- fs.open = open
- function open (path, flags, mode, cb) {
- if (typeof mode === 'function')
- cb = mode, mode = null
- return go$open(path, flags, mode, cb)
+function reduceToSingleString(output, base, braces) {
+ var numLinesEst = 0;
+ var length = output.reduce(function(prev, cur) {
+ numLinesEst++;
+ if (cur.indexOf('\n') >= 0) numLinesEst++;
+ return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
+ }, 0);
- function go$open (path, flags, mode, cb) {
- return fs$open(path, flags, mode, function (err, fd) {
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$open, [path, flags, mode, cb]])
- else {
- if (typeof cb === 'function')
- cb.apply(this, arguments)
- retry()
- }
- })
- }
+ if (length > 60) {
+ return braces[0] +
+ (base === '' ? '' : base + '\n ') +
+ ' ' +
+ output.join(',\n ') +
+ ' ' +
+ braces[1];
}
- return fs
+ return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
-function enqueue (elem) {
- debug('ENQUEUE', elem[0].name, elem[1])
- queue.push(elem)
-}
-function retry () {
- var elem = queue.shift()
- if (elem) {
- debug('RETRY', elem[0].name, elem[1])
- elem[0].apply(null, elem[1])
- }
+// NOTE: These type checking functions intentionally don't use `instanceof`
+// because it is fragile and can be easily faked with `Object.create()`.
+function isArray(ar) {
+ return Array.isArray(ar);
}
+exports.isArray = isArray;
-}).call(this,require('_process'))
-},{"./fs.js":184,"./legacy-streams.js":186,"./polyfills.js":187,"_process":64,"assert":1,"fs":4,"util":90}],186:[function(require,module,exports){
-(function (process){
-var Stream = require('stream').Stream
-
-module.exports = legacy
+function isBoolean(arg) {
+ return typeof arg === 'boolean';
+}
+exports.isBoolean = isBoolean;
-function legacy (fs) {
- return {
- ReadStream: ReadStream,
- WriteStream: WriteStream
- }
+function isNull(arg) {
+ return arg === null;
+}
+exports.isNull = isNull;
- function ReadStream (path, options) {
- if (!(this instanceof ReadStream)) return new ReadStream(path, options);
+function isNullOrUndefined(arg) {
+ return arg == null;
+}
+exports.isNullOrUndefined = isNullOrUndefined;
- Stream.call(this);
+function isNumber(arg) {
+ return typeof arg === 'number';
+}
+exports.isNumber = isNumber;
- var self = this;
+function isString(arg) {
+ return typeof arg === 'string';
+}
+exports.isString = isString;
- this.path = path;
- this.fd = null;
- this.readable = true;
- this.paused = false;
+function isSymbol(arg) {
+ return typeof arg === 'symbol';
+}
+exports.isSymbol = isSymbol;
- this.flags = 'r';
- this.mode = 438; /*=0666*/
- this.bufferSize = 64 * 1024;
+function isUndefined(arg) {
+ return arg === void 0;
+}
+exports.isUndefined = isUndefined;
- options = options || {};
+function isRegExp(re) {
+ return isObject(re) && objectToString(re) === '[object RegExp]';
+}
+exports.isRegExp = isRegExp;
- // Mixin options into this
- var keys = Object.keys(options);
- for (var index = 0, length = keys.length; index < length; index++) {
- var key = keys[index];
- this[key] = options[key];
- }
+function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
+}
+exports.isObject = isObject;
- if (this.encoding) this.setEncoding(this.encoding);
+function isDate(d) {
+ return isObject(d) && objectToString(d) === '[object Date]';
+}
+exports.isDate = isDate;
- if (this.start !== undefined) {
- if ('number' !== typeof this.start) {
- throw TypeError('start must be a Number');
- }
- if (this.end === undefined) {
- this.end = Infinity;
- } else if ('number' !== typeof this.end) {
- throw TypeError('end must be a Number');
- }
+function isError(e) {
+ return isObject(e) &&
+ (objectToString(e) === '[object Error]' || e instanceof Error);
+}
+exports.isError = isError;
- if (this.start > this.end) {
- throw new Error('start must be <= end');
- }
+function isFunction(arg) {
+ return typeof arg === 'function';
+}
+exports.isFunction = isFunction;
- this.pos = this.start;
- }
+function isPrimitive(arg) {
+ return arg === null ||
+ typeof arg === 'boolean' ||
+ typeof arg === 'number' ||
+ typeof arg === 'string' ||
+ typeof arg === 'symbol' || // ES6 symbol
+ typeof arg === 'undefined';
+}
+exports.isPrimitive = isPrimitive;
- if (this.fd !== null) {
- process.nextTick(function() {
- self._read();
- });
- return;
- }
+exports.isBuffer = require('./support/isBuffer');
- fs.open(this.path, this.flags, this.mode, function (err, fd) {
- if (err) {
- self.emit('error', err);
- self.readable = false;
- return;
- }
+function objectToString(o) {
+ return Object.prototype.toString.call(o);
+}
- self.fd = fd;
- self.emit('open', fd);
- self._read();
- })
- }
- function WriteStream (path, options) {
- if (!(this instanceof WriteStream)) return new WriteStream(path, options);
+function pad(n) {
+ return n < 10 ? '0' + n.toString(10) : n.toString(10);
+}
- Stream.call(this);
- this.path = path;
- this.fd = null;
- this.writable = true;
+var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
+ 'Oct', 'Nov', 'Dec'];
- this.flags = 'w';
- this.encoding = 'binary';
- this.mode = 438; /*=0666*/
- this.bytesWritten = 0;
+// 26 Feb 16:19:34
+function timestamp() {
+ var d = new Date();
+ var time = [pad(d.getHours()),
+ pad(d.getMinutes()),
+ pad(d.getSeconds())].join(':');
+ return [d.getDate(), months[d.getMonth()], time].join(' ');
+}
- options = options || {};
- // Mixin options into this
- var keys = Object.keys(options);
- for (var index = 0, length = keys.length; index < length; index++) {
- var key = keys[index];
- this[key] = options[key];
- }
+// log is just a thin wrapper to console.log that prepends a timestamp
+exports.log = function() {
+ console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
+};
- if (this.start !== undefined) {
- if ('number' !== typeof this.start) {
- throw TypeError('start must be a Number');
- }
- if (this.start < 0) {
- throw new Error('start must be >= zero');
- }
- this.pos = this.start;
- }
+/**
+ * Inherit the prototype methods from one constructor into another.
+ *
+ * The Function.prototype.inherits from lang.js rewritten as a standalone
+ * function (not on Function.prototype). NOTE: If this file is to be loaded
+ * during bootstrapping this function needs to be rewritten using some native
+ * functions as prototype setup using normal JavaScript does not work as
+ * expected during bootstrapping (see mirror.js in r114903).
+ *
+ * @param {function} ctor Constructor function which needs to inherit the
+ * prototype.
+ * @param {function} superCtor Constructor function to inherit prototype from.
+ */
+exports.inherits = require('inherits');
- this.busy = false;
- this._queue = [];
+exports._extend = function(origin, add) {
+ // Don't do anything if add isn't an object
+ if (!add || !isObject(add)) return origin;
- if (this.fd === null) {
- this._open = fs.open;
- this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
- this.flush();
- }
+ var keys = Object.keys(add);
+ var i = keys.length;
+ while (i--) {
+ origin[keys[i]] = add[keys[i]];
}
+ return origin;
+};
+
+function hasOwnProperty(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
}
-}).call(this,require('_process'))
-},{"_process":64,"stream":81}],187:[function(require,module,exports){
-(function (process){
-var fs = require('./fs.js')
-var constants = require('constants')
+}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./support/isBuffer":137,"_process":107,"inherits":47}],139:[function(require,module,exports){
+'use strict';
-var origCwd = process.cwd
-var cwd = null
-process.cwd = function() {
- if (!cwd)
- cwd = origCwd.call(process)
- return cwd
-}
-try {
- process.cwd()
-} catch (er) {}
+module.exports = {
+ src: require('./lib/src'),
+ dest: require('./lib/dest'),
+ symlink: require('./lib/symlink')
+};
-var chdir = process.chdir
-process.chdir = function(d) {
- cwd = null
- chdir.call(process, d)
-}
+},{"./lib/dest":140,"./lib/src":153,"./lib/symlink":155}],140:[function(require,module,exports){
+(function (process){
+'use strict';
-module.exports = patch
+var through2 = require('through2');
+var sourcemaps = process.browser ? null : require('gulp-sourcemaps');
+var duplexify = require('duplexify');
+var prepareWrite = require('../prepareWrite');
+var writeContents = require('./writeContents');
-function patch (fs) {
- // (re-)implement some things that are known busted or missing.
+function dest(outFolder, opt) {
+ if (!opt) {
+ opt = {};
+ }
- // lchmod, broken prior to 0.6.2
- // back-port the fix here.
- if (constants.hasOwnProperty('O_SYMLINK') &&
- process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
- patchLchmod(fs)
+ function saveFile(file, enc, cb) {
+ prepareWrite(outFolder, file, opt, function(err, writePath) {
+ if (err) {
+ return cb(err);
+ }
+ writeContents(writePath, file, cb);
+ });
}
- // lutimes implementation, or no-op
- if (!fs.lutimes) {
- patchLutimes(fs)
+ var saveStream = through2.obj(saveFile);
+ if (!opt.sourcemaps) {
+ return saveStream;
}
- // https://github.com/isaacs/node-graceful-fs/issues/4
- // Chown should not fail on einval or eperm if non-root.
- // It should not fail on enosys ever, as this just indicates
- // that a fs doesn't support the intended operation.
+ var mapStream = sourcemaps.write(opt.sourcemaps.path, opt.sourcemaps);
+ var outputStream = duplexify.obj(mapStream, saveStream);
+ mapStream.pipe(saveStream);
- fs.chown = chownFix(fs.chown)
- fs.fchown = chownFix(fs.fchown)
- fs.lchown = chownFix(fs.lchown)
+ return outputStream;
+}
- fs.chmod = chownFix(fs.chmod)
- fs.fchmod = chownFix(fs.fchmod)
- fs.lchmod = chownFix(fs.lchmod)
+module.exports = dest;
- fs.chownSync = chownFixSync(fs.chownSync)
- fs.fchownSync = chownFixSync(fs.fchownSync)
- fs.lchownSync = chownFixSync(fs.lchownSync)
+}).call(this,require('_process'))
+},{"../prepareWrite":147,"./writeContents":141,"_process":107,"duplexify":16,"gulp-sourcemaps":37,"through2":133}],141:[function(require,module,exports){
+'use strict';
- fs.chmodSync = chownFix(fs.chmodSync)
- fs.fchmodSync = chownFix(fs.fchmodSync)
- fs.lchmodSync = chownFix(fs.lchmodSync)
- // if lchmod/lchown do not exist, then make them no-ops
- if (!fs.lchmod) {
- fs.lchmod = function (path, mode, cb) {
- process.nextTick(cb)
- }
- fs.lchmodSync = function () {}
+var writeDir = require('./writeDir');
+var writeStream = require('./writeStream');
+var writeBuffer = require('./writeBuffer');
+var writeSymbolicLink = require('./writeSymbolicLink');
+
+function writeContents(writePath, file, cb) {
+ // if directory then mkdirp it
+ if (file.isDirectory()) {
+ return writeDir(writePath, file, written);
}
- if (!fs.lchown) {
- fs.lchown = function (path, uid, gid, cb) {
- process.nextTick(cb)
- }
- fs.lchownSync = function () {}
+
+ // stream it to disk yo
+ if (file.isStream()) {
+ return writeStream(writePath, file, written);
}
- // on Windows, A/V software can lock the directory, causing this
- // to fail with an EACCES or EPERM if the directory contains newly
- // created files. Try again on failure, for up to 1 second.
- if (process.platform === "win32") {
- fs.rename = (function (fs$rename) { return function (from, to, cb) {
- var start = Date.now()
- fs$rename(from, to, function CB (er) {
- if (er
- && (er.code === "EACCES" || er.code === "EPERM")
- && Date.now() - start < 1000) {
- return fs$rename(from, to, CB)
- }
- if (cb) cb(er)
- })
- }})(fs.rename)
+ // write it as a symlink
+ if (file.symlink) {
+ return writeSymbolicLink(writePath, file, written);
}
- // if read() returns EAGAIN, then just try it again.
- fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) {
- var callback
- if (callback_ && typeof callback_ === 'function') {
- var eagCounter = 0
- callback = function (er, _, __) {
- if (er && er.code === 'EAGAIN' && eagCounter < 10) {
- eagCounter ++
- return fs$read.call(fs, fd, buffer, offset, length, position, callback)
- }
- callback_.apply(this, arguments)
- }
+ // write it like normal
+ if (file.isBuffer()) {
+ return writeBuffer(writePath, file, written);
+ }
+
+ // if no contents then do nothing
+ if (file.isNull()) {
+ return complete();
+ }
+
+ function complete(err) {
+ cb(err, file);
+ }
+
+ function written(err) {
+
+ if (isErrorFatal(err)) {
+ return complete(err);
}
- return fs$read.call(fs, fd, buffer, offset, length, position, callback)
- }})(fs.read)
- fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
- var eagCounter = 0
- while (true) {
- try {
- return fs$readSync.call(fs, fd, buffer, offset, length, position)
- } catch (er) {
- if (er.code === 'EAGAIN' && eagCounter < 10) {
- eagCounter ++
- continue
- }
- throw er
- }
+ if (!file.stat || typeof file.stat.mode !== 'number' || file.symlink) {
+ return complete();
}
- }})(fs.readSync)
-}
-function patchLchmod (fs) {
- fs.lchmod = function (path, mode, callback) {
- callback = callback || noop
- fs.open( path
- , constants.O_WRONLY | constants.O_SYMLINK
- , mode
- , function (err, fd) {
+ fs.stat(writePath, function(err, st) {
if (err) {
- callback(err)
- return
+ return complete(err);
}
- // prefer to return the chmod error, if one occurs,
- // but still try to close, and report closing errors if they occur.
- fs.fchmod(fd, mode, function (err) {
- fs.close(fd, function(err2) {
- callback(err || err2)
- })
- })
- })
- }
-
- fs.lchmodSync = function (path, mode) {
- var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
-
- // prefer to return the chmod error, if one occurs,
- // but still try to close, and report closing errors if they occur.
- var threw = true
- var ret
- try {
- ret = fs.fchmodSync(fd, mode)
- threw = false
- } finally {
- if (threw) {
- try {
- fs.closeSync(fd)
- } catch (er) {}
- } else {
- fs.closeSync(fd)
+ var currentMode = (st.mode & parseInt('0777', 8));
+ var expectedMode = (file.stat.mode & parseInt('0777', 8));
+ if (currentMode === expectedMode) {
+ return complete();
}
- }
- return ret
+ fs.chmod(writePath, expectedMode, complete);
+ });
}
-}
-function patchLutimes (fs) {
- if (constants.hasOwnProperty("O_SYMLINK")) {
- fs.lutimes = function (path, at, mt, cb) {
- fs.open(path, constants.O_SYMLINK, function (er, fd) {
- cb = cb || noop
- if (er) return cb(er)
- fs.futimes(fd, at, mt, function (er) {
- fs.close(fd, function (er2) {
- return cb(er || er2)
- })
- })
- })
+ function isErrorFatal(err) {
+ if (!err) {
+ return false;
}
- fs.lutimesSync = function (path, at, mt) {
- var fd = fs.openSync(path, constants.O_SYMLINK)
- var ret
- var threw = true
- try {
- ret = fs.futimesSync(fd, at, mt)
- threw = false
- } finally {
- if (threw) {
- try {
- fs.closeSync(fd)
- } catch (er) {}
- } else {
- fs.closeSync(fd)
- }
- }
- return ret
+ // Handle scenario for file overwrite failures.
+ else if (err.code === 'EEXIST' && file.flag === 'wx') {
+ return false; // "These aren't the droids you're looking for"
}
- } else {
- fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) }
- fs.lutimesSync = function () {}
+ // Otherwise, this is a fatal error
+ return true;
}
}
-function chownFix (orig) {
- if (!orig) return orig
- return function (target, uid, gid, cb) {
- return orig.call(fs, target, uid, gid, function (er, res) {
- if (chownErOk(er)) er = null
- cb(er, res)
- })
- }
-}
+module.exports = writeContents;
-function chownFixSync (orig) {
- if (!orig) return orig
- return function (target, uid, gid) {
- try {
- return orig.call(fs, target, uid, gid)
- } catch (er) {
- if (!chownErOk(er)) throw er
- }
- }
+},{"./writeBuffer":142,"./writeDir":143,"./writeStream":144,"./writeSymbolicLink":145}],142:[function(require,module,exports){
+(function (process){
+'use strict';
+
+var fs = process.browser ? require('fs') : require('graceful-fs');
+
+function writeBuffer(writePath, file, cb) {
+ var opt = {
+ mode: file.stat.mode,
+ flag: file.flag
+ };
+
+ fs.writeFile(writePath, file.contents, opt, cb);
}
-// ENOSYS means that the fs doesn't support the op. Just ignore
-// that, because it doesn't matter.
-//
-// if there's no getuid, or if getuid() is something other
-// than 0, and the error is EINVAL or EPERM, then just ignore
-// it.
-//
-// This specific case is a silent failure in cp, install, tar,
-// and most other unix tools that manage permissions.
-//
-// When running as root, or if other types of errors are
-// encountered, then it's strict.
-function chownErOk (er) {
- if (!er)
- return true
+module.exports = writeBuffer;
- if (er.code === "ENOSYS")
- return true
+}).call(this,require('_process'))
+},{"_process":107,"fs":6,"graceful-fs":34}],143:[function(require,module,exports){
+'use strict';
- var nonroot = !process.getuid || process.getuid() !== 0
- if (nonroot) {
- if (er.code === "EINVAL" || er.code === "EPERM")
- return true
- }
+var mkdirp = require('mkdirp');
- return false
+function writeDir(writePath, file, cb) {
+ mkdirp(writePath, file.stat.mode, cb);
}
-}).call(this,require('_process'))
-},{"./fs.js":184,"_process":64,"constants":10}],188:[function(require,module,exports){
-(function (Buffer){
+module.exports = writeDir;
+
+},{"mkdirp":85}],144:[function(require,module,exports){
+(function (process){
'use strict';
-var through = require('through2');
-var fs = require('graceful-fs');
-var path = require('path');
-var File = require('vinyl');
-var convert = require('convert-source-map');
-var stripBom = require('strip-bom');
-var PLUGIN_NAME = 'gulp-sourcemap';
-var urlRegex = /^https?:\/\//;
+var streamFile = require('../../src/getContents/streamFile');
+var fs = process.browser ? require('fs') : require('graceful-fs');
-/**
- * Initialize source mapping chain
- */
-module.exports.init = function init(options) {
- function sourceMapInit(file, encoding, callback) {
- /*jshint validthis:true */
+function writeStream(writePath, file, cb) {
+ var opt = {
+ mode: file.stat.mode,
+ flag: file.flag
+ };
- if (file.isNull()) {
- this.push(file);
- return callback();
- }
+ var outStream = fs.createWriteStream(writePath, opt);
- if (file.isStream()) {
- return callback(new Error(PLUGIN_NAME + '-init: Streaming not supported'));
- }
+ file.contents.once('error', complete);
+ outStream.once('error', complete);
+ outStream.once('finish', success);
- var fileContent = file.contents.toString();
- var sourceMap;
+ file.contents.pipe(outStream);
- if (options && options.loadMaps) {
- var sourcePath = ''; //root path for the sources in the map
+ function success() {
+ streamFile(file, {}, complete);
+ }
- // Try to read inline source map
- sourceMap = convert.fromSource(fileContent);
- if (sourceMap) {
- sourceMap = sourceMap.toObject();
- // sources in map are relative to the source file
- sourcePath = path.dirname(file.path);
- fileContent = convert.removeComments(fileContent);
- } else {
- // look for source map comment referencing a source map file
- var mapComment = convert.mapFileCommentRegex.exec(fileContent);
+ // cleanup
+ function complete(err) {
+ file.contents.removeListener('error', cb);
+ outStream.removeListener('error', cb);
+ outStream.removeListener('finish', success);
+ cb(err);
+ }
+}
- var mapFile;
- if (mapComment) {
- mapFile = path.resolve(path.dirname(file.path), mapComment[1] || mapComment[2]);
- fileContent = convert.removeMapFileComments(fileContent);
- // if no comment try map file with same name as source file
- } else {
- mapFile = file.path + '.map';
- }
+module.exports = writeStream;
- // sources in external map are relative to map file
- sourcePath = path.dirname(mapFile);
+}).call(this,require('_process'))
+},{"../../src/getContents/streamFile":152,"_process":107,"fs":6,"graceful-fs":34}],145:[function(require,module,exports){
+(function (process){
+'use strict';
- try {
- sourceMap = JSON.parse(stripBom(fs.readFileSync(mapFile, 'utf8')));
- } catch(e) {}
- }
+var fs = process.browser ? require('fs') : require('graceful-fs');
+
+function writeSymbolicLink(writePath, file, cb) {
+ fs.symlink(file.symlink, writePath, function (err) {
+ if (err && err.code !== 'EEXIST') {
+ return cb(err);
+ }
+
+ cb(null, file);
+ });
+}
- // fix source paths and sourceContent for imported source map
- if (sourceMap) {
- sourceMap.sourcesContent = sourceMap.sourcesContent || [];
- sourceMap.sources.forEach(function(source, i) {
- if (source.match(urlRegex)) {
- sourceMap.sourcesContent[i] = sourceMap.sourcesContent[i] || null;
- return;
- }
- var absPath = path.resolve(sourcePath, source);
- sourceMap.sources[i] = unixStylePath(path.relative(file.base, absPath));
+module.exports = writeSymbolicLink;
- if (!sourceMap.sourcesContent[i]) {
- var sourceContent = null;
- if (sourceMap.sourceRoot) {
- if (sourceMap.sourceRoot.match(urlRegex)) {
- sourceMap.sourcesContent[i] = null;
- return;
- }
- absPath = path.resolve(sourcePath, sourceMap.sourceRoot, source);
- }
+}).call(this,require('_process'))
+},{"_process":107,"fs":6,"graceful-fs":34}],146:[function(require,module,exports){
+'use strict';
- // if current file: use content
- if (absPath === file.path) {
- sourceContent = fileContent;
+var filter = require('through2-filter');
- // else load content from file
- } else {
- try {
- if (options.debug)
- console.log(PLUGIN_NAME + '-init: No source content for "' + source + '". Loading from file.');
- sourceContent = stripBom(fs.readFileSync(absPath, 'utf8'));
- } catch (e) {
- if (options.debug)
- console.warn(PLUGIN_NAME + '-init: source file not found: ' + absPath);
- }
- }
- sourceMap.sourcesContent[i] = sourceContent;
- }
- });
+module.exports = function(d) {
+ var isValid = typeof d === 'number' ||
+ d instanceof Number ||
+ d instanceof Date;
- // remove source map comment from source
- file.contents = new Buffer(fileContent, 'utf8');
- }
- }
+ if (!isValid) {
+ throw new Error('expected since option to be a date or a number');
+ }
+ return filter.obj(function(file){
+ return file.stat && file.stat.mtime > d;
+ });
+};
+},{"through2-filter":132}],147:[function(require,module,exports){
+(function (process){
+'use strict';
- if (!sourceMap) {
- // Make an empty source map
- sourceMap = {
- version : 3,
- names: [],
- mappings: '',
- sources: [unixStylePath(file.relative)],
- sourcesContent: [fileContent]
- };
- }
+var assign = require('object-assign');
+var path = require('path');
+var mkdirp = require('mkdirp');
+var fs = process.browser ? require('fs') : require('graceful-fs');
- sourceMap.file = unixStylePath(file.relative);
- file.sourceMap = sourceMap;
+function booleanOrFunc(v, file) {
+ if (typeof v !== 'boolean' && typeof v !== 'function') {
+ return null;
+ }
- this.push(file);
- callback();
+ return typeof v === 'boolean' ? v : v(file);
+}
+
+function stringOrFunc(v, file) {
+ if (typeof v !== 'string' && typeof v !== 'function') {
+ return null;
}
- return through.obj(sourceMapInit);
-};
+ return typeof v === 'string' ? v : v(file);
+}
-/**
- * Write the source map
- *
- * @param options options to change the way the source map is written
- *
- */
-module.exports.write = function write(destPath, options) {
- if (options === undefined && Object.prototype.toString.call(destPath) === '[object Object]') {
- options = destPath;
- destPath = undefined;
+function prepareWrite(outFolder, file, opt, cb) {
+ var options = assign({
+ cwd: process.cwd(),
+ mode: (file.stat ? file.stat.mode : null),
+ dirMode: null,
+ overwrite: true
+ }, opt);
+ var overwrite = booleanOrFunc(options.overwrite, file);
+ options.flag = (overwrite ? 'w' : 'wx');
+
+ var cwd = path.resolve(options.cwd);
+ var outFolderPath = stringOrFunc(outFolder, file);
+ if (!outFolderPath) {
+ throw new Error('Invalid output folder');
+ }
+ var basePath = options.base ?
+ stringOrFunc(options.base, file) : path.resolve(cwd, outFolderPath);
+ if (!basePath) {
+ throw new Error('Invalid base option');
}
- options = options || {};
- // set defaults for options if unset
- if (options.includeContent === undefined)
- options.includeContent = true;
- if (options.addComment === undefined)
- options.addComment = true;
+ var writePath = path.resolve(basePath, file.relative);
+ var writeFolder = path.dirname(writePath);
- function sourceMapWrite(file, encoding, callback) {
- /*jshint validthis:true */
+ // wire up new properties
+ file.stat = (file.stat || new fs.Stats());
+ file.stat.mode = options.mode;
+ file.flag = options.flag;
+ file.cwd = cwd;
+ file.base = basePath;
+ file.path = writePath;
- if (file.isNull() || !file.sourceMap) {
- this.push(file);
- return callback();
+ // mkdirp the folder the file is going in
+ mkdirp(writeFolder, options.dirMode, function(err){
+ if (err) {
+ return cb(err);
}
+ cb(null, writePath);
+ });
+}
- if (file.isStream()) {
- return callback(new Error(PLUGIN_NAME + '-write: Streaming not supported'));
- }
+module.exports = prepareWrite;
- var sourceMap = file.sourceMap;
- // fix paths if Windows style paths
- sourceMap.file = unixStylePath(file.relative);
- sourceMap.sources = sourceMap.sources.map(function(filePath) {
- return unixStylePath(filePath);
- });
+}).call(this,require('_process'))
+},{"_process":107,"fs":6,"graceful-fs":34,"mkdirp":85,"object-assign":92,"path":104}],148:[function(require,module,exports){
+(function (process){
+'use strict';
- if (options.sourceRoot) {
- if (typeof options.sourceRoot === 'function') {
- sourceMap.sourceRoot = options.sourceRoot(file);
- } else {
- sourceMap.sourceRoot = options.sourceRoot;
- }
- }
+var fs = process.browser ? require('fs') : require('graceful-fs');
+var stripBom = require('strip-bom');
- if (options.includeContent) {
- sourceMap.sourcesContent = sourceMap.sourcesContent || [];
+function bufferFile(file, opt, cb) {
+ fs.readFile(file.path, function(err, data) {
+ if (err) {
+ return cb(err);
+ }
- // load missing source content
- for (var i = 0; i < file.sourceMap.sources.length; i++) {
- if (!sourceMap.sourcesContent[i]) {
- var sourcePath = path.resolve(sourceMap.sourceRoot || file.base, sourceMap.sources[i]);
- try {
- if (options.debug)
- console.log(PLUGIN_NAME + '-write: No source content for "' + sourceMap.sources[i] + '". Loading from file.');
- sourceMap.sourcesContent[i] = stripBom(fs.readFileSync(sourcePath, 'utf8'));
- } catch (e) {
- if (options.debug)
- console.warn(PLUGIN_NAME + '-write: source file not found: ' + sourcePath);
- }
- }
- }
- sourceMap.sourceRoot = sourceMap.sourceRoot || '/source/';
+ if (opt.stripBOM){
+ file.contents = stripBom(data);
} else {
- delete sourceMap.sourcesContent;
+ file.contents = data;
}
- var extension = file.relative.split('.').pop();
- var commentFormatter;
+ cb(null, file);
+ });
+}
- switch (extension) {
- case 'css':
- commentFormatter = function(url) { return "\n/*# sourceMappingURL=" + url + " */"; };
- break;
- case 'js':
- commentFormatter = function(url) { return "\n//# sourceMappingURL=" + url; };
- break;
- default:
- commentFormatter = function(url) { return ""; };
- }
+module.exports = bufferFile;
- var comment, sourceMappingURLPrefix;
- if (!destPath) {
- // encode source map into comment
- var base64Map = new Buffer(JSON.stringify(sourceMap)).toString('base64');
- comment = commentFormatter('data:application/json;base64,' + base64Map);
- } else {
- // add new source map file to stream
- var sourceMapFile = new File({
- cwd: file.cwd,
- base: file.base,
- path: path.join(file.base, destPath, file.relative) + '.map',
- contents: new Buffer(JSON.stringify(sourceMap))
- });
- this.push(sourceMapFile);
+}).call(this,require('_process'))
+},{"_process":107,"fs":6,"graceful-fs":34,"strip-bom":131}],149:[function(require,module,exports){
+'use strict';
- comment = commentFormatter(unixStylePath(path.join(path.relative(path.dirname(file.path), file.base), destPath, file.relative) + '.map'));
+var through2 = require('through2');
+var readDir = require('./readDir');
+var readSymbolicLink = require('./readSymbolicLink');
+var bufferFile = require('./bufferFile');
+var streamFile = require('./streamFile');
- if (options.sourceMappingURLPrefix) {
- if (typeof options.sourceMappingURLPrefix === 'function') {
- sourceMappingURLPrefix = options.sourceMappingURLPrefix(file);
- } else {
- sourceMappingURLPrefix = options.sourceMappingURLPrefix;
- }
- comment = comment.replace(/sourceMappingURL=\.*/, 'sourceMappingURL=' + sourceMappingURLPrefix);
- }
+function getContents(opt) {
+ return through2.obj(function(file, enc, cb) {
+ // don't fail to read a directory
+ if (file.isDirectory()) {
+ return readDir(file, opt, cb);
}
- // append source map comment
- if (options.addComment)
- file.contents = Buffer.concat([file.contents, new Buffer(comment)]);
+ // process symbolic links included with `followSymlinks` option
+ if (file.stat && file.stat.isSymbolicLink()) {
+ return readSymbolicLink(file, opt, cb);
+ }
- this.push(file);
- callback();
- }
+ // read and pass full contents
+ if (opt.buffer !== false) {
+ return bufferFile(file, opt, cb);
+ }
- return through.obj(sourceMapWrite);
-};
+ // dont buffer anything - just pass streams
+ return streamFile(file, opt, cb);
+ });
+}
+
+module.exports = getContents;
+
+},{"./bufferFile":148,"./readDir":150,"./readSymbolicLink":151,"./streamFile":152,"through2":133}],150:[function(require,module,exports){
+'use strict';
-function unixStylePath(filePath) {
- return filePath.split(path.sep).join('/');
+function readDir(file, opt, cb) {
+ // do nothing for now
+ cb(null, file);
}
-}).call(this,require("buffer").Buffer)
-},{"buffer":6,"convert-source-map":189,"graceful-fs":191,"path":62,"strip-bom":193,"through2":206,"vinyl":207}],189:[function(require,module,exports){
-(function (Buffer){
+module.exports = readDir;
+
+},{}],151:[function(require,module,exports){
+(function (process){
'use strict';
-var fs = require('fs');
-var path = require('path');
-var commentRx = /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+;)?base64,(.*)$/mg;
-var mapFileCommentRx =
- // //# sourceMappingURL=foo.js.map
- /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg
+var fs = process.browser ? require('fs') : require('graceful-fs');
-function decodeBase64(base64) {
- return new Buffer(base64, 'base64').toString();
-}
+function readLink(file, opt, cb) {
+ fs.readlink(file.path, function (err, target) {
+ if (err) {
+ return cb(err);
+ }
-function stripComment(sm) {
- return sm.split(',').pop();
+ // store the link target path
+ file.symlink = target;
+
+ return cb(null, file);
+ });
}
-function readFromFileMap(sm, dir) {
- // NOTE: this will only work on the server since it attempts to read the map file
+module.exports = readLink;
- var r = mapFileCommentRx.exec(sm);
- mapFileCommentRx.lastIndex = 0;
-
- // for some odd reason //# .. captures in 1 and /* .. */ in 2
- var filename = r[1] || r[2];
- var filepath = path.join(dir, filename);
+}).call(this,require('_process'))
+},{"_process":107,"fs":6,"graceful-fs":34}],152:[function(require,module,exports){
+(function (process){
+'use strict';
- try {
- return fs.readFileSync(filepath, 'utf8');
- } catch (e) {
- throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e);
+var fs = process.browser ? require('fs') : require('graceful-fs');
+var stripBom = require('strip-bom-stream');
+
+function streamFile(file, opt, cb) {
+ file.contents = fs.createReadStream(file.path);
+
+ if (opt.stripBOM) {
+ file.contents = file.contents.pipe(stripBom());
}
+
+ cb(null, file);
}
-function Converter (sm, opts) {
- opts = opts || {};
+module.exports = streamFile;
- if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir);
- if (opts.hasComment) sm = stripComment(sm);
- if (opts.isEncoded) sm = decodeBase64(sm);
- if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm);
+}).call(this,require('_process'))
+},{"_process":107,"fs":6,"graceful-fs":34,"strip-bom-stream":130}],153:[function(require,module,exports){
+(function (process){
+'use strict';
- this.sourcemap = sm;
+var assign = require('object-assign');
+var through = require('through2');
+var gs = require('glob-stream');
+var File = require('vinyl');
+var duplexify = require('duplexify');
+var merge = require('merge-stream');
+var sourcemaps = process.browser ? null : require('gulp-sourcemaps');
+var filterSince = require('../filterSince');
+var isValidGlob = require('is-valid-glob');
+
+var getContents = require('./getContents');
+var resolveSymlinks = require('./resolveSymlinks');
+
+function createFile(globFile, enc, cb) {
+ cb(null, new File(globFile));
}
-function convertFromLargeSource(content){
- var lines = content.split('\n');
- var line;
- // find first line which contains a source map starting at end of content
- for (var i = lines.length - 1; i > 0; i--) {
- line = lines[i]
- if (~line.indexOf('sourceMappingURL=data:')) return exports.fromComment(line);
+function src(glob, opt) {
+ var options = assign({
+ read: true,
+ buffer: true,
+ stripBOM: true,
+ sourcemaps: false,
+ passthrough: false,
+ followSymlinks: true
+ }, opt);
+
+ var inputPass;
+
+ if (!isValidGlob(glob)) {
+ throw new Error('Invalid glob argument: ' + glob);
}
-}
-Converter.prototype.toJSON = function (space) {
- return JSON.stringify(this.sourcemap, null, space);
-};
+ var globStream = gs.create(glob, options);
-Converter.prototype.toBase64 = function () {
- var json = this.toJSON();
- return new Buffer(json).toString('base64');
-};
+ var outputStream = globStream
+ .pipe(resolveSymlinks(options))
+ .pipe(through.obj(createFile));
-Converter.prototype.toComment = function (options) {
- var base64 = this.toBase64();
- var data = 'sourceMappingURL=data:application/json;base64,' + base64;
- return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
-};
+ if (options.since != null) {
+ outputStream = outputStream
+ .pipe(filterSince(options.since));
+ }
-// returns copy instead of original
-Converter.prototype.toObject = function () {
- return JSON.parse(this.toJSON());
-};
+ if (options.read !== false) {
+ outputStream = outputStream
+ .pipe(getContents(options));
+ }
-Converter.prototype.addProperty = function (key, value) {
- if (this.sourcemap.hasOwnProperty(key)) throw new Error('property %s already exists on the sourcemap, use set property instead');
- return this.setProperty(key, value);
-};
+ if (options.passthrough === true) {
+ inputPass = through.obj();
+ outputStream = duplexify.obj(inputPass, merge(outputStream, inputPass));
+ }
+ if (options.sourcemaps === true) {
+ outputStream = outputStream
+ .pipe(sourcemaps.init({loadMaps: true}));
+ }
+ globStream.on('error', outputStream.emit.bind(outputStream, 'error'));
+ return outputStream;
+}
-Converter.prototype.setProperty = function (key, value) {
- this.sourcemap[key] = value;
- return this;
-};
+module.exports = src;
-Converter.prototype.getProperty = function (key) {
- return this.sourcemap[key];
-};
+}).call(this,require('_process'))
+},{"../filterSince":146,"./getContents":149,"./resolveSymlinks":154,"_process":107,"duplexify":16,"glob-stream":22,"gulp-sourcemaps":37,"is-valid-glob":52,"merge-stream":83,"object-assign":92,"through2":133,"vinyl":156}],154:[function(require,module,exports){
+(function (process){
+'use strict';
-exports.fromObject = function (obj) {
- return new Converter(obj);
-};
+var through2 = require('through2');
+var fs = process.browser ? require('fs') : require('graceful-fs');
+var path = require('path');
-exports.fromJSON = function (json) {
- return new Converter(json, { isJSON: true });
-};
+function resolveSymlinks(options) {
-exports.fromBase64 = function (base64) {
- return new Converter(base64, { isEncoded: true });
-};
+ // a stat property is exposed on file objects as a (wanted) side effect
+ function resolveFile(globFile, enc, cb) {
+ fs.lstat(globFile.path, function (err, stat) {
+ if (err) {
+ return cb(err);
+ }
-exports.fromComment = function (comment) {
- comment = comment
- .replace(/^\/\*/g, '//')
- .replace(/\*\/$/g, '');
+ globFile.stat = stat;
- return new Converter(comment, { isEncoded: true, hasComment: true });
-};
+ if (!stat.isSymbolicLink() || !options.followSymlinks) {
+ return cb(null, globFile);
+ }
-exports.fromMapFileComment = function (comment, dir) {
- return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true });
-};
+ fs.realpath(globFile.path, function (err, filePath) {
+ if (err) {
+ return cb(err);
+ }
-// Finds last sourcemap comment in file or returns null if none was found
-exports.fromSource = function (content, largeSource) {
- if (largeSource) return convertFromLargeSource(content);
+ globFile.base = path.dirname(filePath);
+ globFile.path = filePath;
- var m = content.match(commentRx);
- commentRx.lastIndex = 0;
- return m ? exports.fromComment(m.pop()) : null;
-};
+ // recurse to get real file stat
+ resolveFile(globFile, enc, cb);
+ });
+ });
+ }
-// Finds last sourcemap comment in file or returns null if none was found
-exports.fromMapFileSource = function (content, dir) {
- var m = content.match(mapFileCommentRx);
- mapFileCommentRx.lastIndex = 0;
- return m ? exports.fromMapFileComment(m.pop(), dir) : null;
-};
+ return through2.obj(resolveFile);
+}
-exports.removeComments = function (src) {
- commentRx.lastIndex = 0;
- return src.replace(commentRx, '');
-};
+module.exports = resolveSymlinks;
-exports.removeMapFileComments = function (src) {
- mapFileCommentRx.lastIndex = 0;
- return src.replace(mapFileCommentRx, '');
-};
+}).call(this,require('_process'))
+},{"_process":107,"fs":6,"graceful-fs":34,"path":104,"through2":133}],155:[function(require,module,exports){
+(function (process){
+'use strict';
-Object.defineProperty(exports, 'commentRegex', {
- get: function getCommentRegex () {
- commentRx.lastIndex = 0;
- return commentRx;
- }
-});
+var through2 = require('through2');
+var fs = process.browser ? require('fs') : require('graceful-fs');
+var prepareWrite = require('../prepareWrite');
-Object.defineProperty(exports, 'mapFileCommentRegex', {
- get: function getMapFileCommentRegex () {
- mapFileCommentRx.lastIndex = 0;
- return mapFileCommentRx;
+function symlink(outFolder, opt) {
+ function linkFile(file, enc, cb) {
+ var srcPath = file.path;
+ var symType = (file.isDirectory() ? 'dir' : 'file');
+ prepareWrite(outFolder, file, opt, function(err, writePath) {
+ if (err) {
+ return cb(err);
+ }
+ fs.symlink(srcPath, writePath, symType, function(err) {
+ if (err && err.code !== 'EEXIST') {
+ return cb(err);
+ }
+ cb(null, file);
+ });
+ });
}
-});
-}).call(this,require("buffer").Buffer)
-},{"buffer":6,"fs":4,"path":62}],190:[function(require,module,exports){
-(function (process,__filename,__dirname){
-// eeeeeevvvvviiiiiiillllll
-// more evil than monkey-patching the native builtin?
-// Not sure.
-
-var mod = require("module")
-var pre = '(function (exports, require, module, __filename, __dirname) { '
-var post = '});'
-var src = pre + process.binding('natives').fs + post
-var vm = require('vm')
-var fn = vm.runInThisContext(src)
-fn(exports, require, module, __filename, __dirname)
-
-}).call(this,require('_process'),"/../vinyl-fs/node_modules/gulp-sourcemaps/node_modules/graceful-fs/fs.js","/../vinyl-fs/node_modules/gulp-sourcemaps/node_modules/graceful-fs")
-},{"_process":64,"module":4,"vm":102}],191:[function(require,module,exports){
-(function (process){
-// Monkey-patching the fs module.
-// It's ugly, but there is simply no other way to do this.
-var fs = module.exports = require('./fs.js')
+ var stream = through2.obj(linkFile);
+ // TODO: option for either backpressure or lossy
+ stream.resume();
+ return stream;
+}
-var assert = require('assert')
+module.exports = symlink;
-// fix up some busted stuff, mostly on windows and old nodes
-require('./polyfills.js')
+}).call(this,require('_process'))
+},{"../prepareWrite":147,"_process":107,"fs":6,"graceful-fs":34,"through2":133}],156:[function(require,module,exports){
+arguments[4][38][0].apply(exports,arguments)
+},{"./lib/cloneBuffer":157,"./lib/inspectStream":158,"./lib/isBuffer":159,"./lib/isNull":160,"./lib/isStream":161,"_process":107,"clone":11,"clone-stats":10,"dup":38,"path":104,"replace-ext":122,"stream":124}],157:[function(require,module,exports){
+arguments[4][39][0].apply(exports,arguments)
+},{"buffer":8,"dup":39}],158:[function(require,module,exports){
+arguments[4][40][0].apply(exports,arguments)
+},{"./isStream":161,"dup":40}],159:[function(require,module,exports){
+arguments[4][41][0].apply(exports,arguments)
+},{"buffer":8,"dup":41}],160:[function(require,module,exports){
+arguments[4][42][0].apply(exports,arguments)
+},{"dup":42}],161:[function(require,module,exports){
+arguments[4][43][0].apply(exports,arguments)
+},{"dup":43,"stream":124}],162:[function(require,module,exports){
+var Path = require('path')
-var util = require('util')
+module.exports = collect
-function noop () {}
+function collect(stream, cb) {
-var debug = noop
-if (util.debuglog)
- debug = util.debuglog('gfs')
-else if (/\bgfs\b/i.test(process.env.NODE_DEBUG || ''))
- debug = function() {
- var m = util.format.apply(util, arguments)
- m = 'GFS: ' + m.split(/\n/).join('\nGFS: ')
- console.error(m)
+ // we create a collection of objects, where
+ // - names is a list of all paths
+ // - there are per-file objects: { file: , children [ paths ] }
+ // - named is a map { path: fo }
+ var files = {
+ paths: [],
+ named: {}, // wrapped files.
+ unnamed: [], // wrapped files.
}
-if (/\bgfs\b/i.test(process.env.NODE_DEBUG || '')) {
- process.on('exit', function() {
- debug('fds', fds)
- debug(queue)
- assert.equal(queue.length, 0)
- })
-}
-
+ function get(name) {
+ if (!files.named[name]) {
+ files.named[name] = {
+ children: [],
+ }
+ }
+ return files.named[name]
+ }
-var originalOpen = fs.open
-fs.open = open
+ stream.on('data', function(file) {
+ if (cb === null) {
+ // already errored, or no way to externalize result
+ stream.on('data', function() {}) // de-register
+ return // do nothing.
+ }
-function open(path, flags, mode, cb) {
- if (typeof mode === "function") cb = mode, mode = null
- if (typeof cb !== "function") cb = noop
- new OpenReq(path, flags, mode, cb)
-}
+ if (file.path) {
+ // add file to named
+ var fo = get(file.path)
+ fo.file = file
-function OpenReq(path, flags, mode, cb) {
- this.path = path
- this.flags = flags
- this.mode = mode
- this.cb = cb
- Req.call(this)
-}
+ // add reference to file at parent
+ var po = get(Path.dirname(file.path))
+ if (fo !== po) po.children.push(fo)
-util.inherits(OpenReq, Req)
+ // add name to names list.
+ files.paths.push(file.path)
+ } else {
+ files.unnamed.push({ file: file, children: [] })
+ }
+ })
-OpenReq.prototype.process = function() {
- originalOpen.call(fs, this.path, this.flags, this.mode, this.done)
-}
+ stream.on('error', function(err) {
+ cb && cb(err)
+ cb = null
+ })
-var fds = {}
-OpenReq.prototype.done = function(er, fd) {
- debug('open done', er, fd)
- if (fd)
- fds['fd' + fd] = this.path
- Req.prototype.done.call(this, er, fd)
+ stream.on('end', function() {
+ cb && cb(null, files)
+ cb = null
+ })
}
+},{"path":104}],163:[function(require,module,exports){
+var x = module.exports = {}
+x.randomString = randomString
+x.cleanPath = cleanPath
-var originalReaddir = fs.readdir
-fs.readdir = readdir
-
-function readdir(path, cb) {
- if (typeof cb !== "function") cb = noop
- new ReaddirReq(path, cb)
+function randomString () {
+ return Math.random().toString(36).slice(2) +
+ Math.random().toString(36).slice(2) +
+ Math.random().toString(36).slice(2) +
+ Math.random().toString(36).slice(2)
}
-function ReaddirReq(path, cb) {
- this.path = path
- this.cb = cb
- Req.call(this)
-}
+function cleanPath(path, base) {
+ if (!path) return ''
+ if (!base) return path
-util.inherits(ReaddirReq, Req)
+ if (base[base.length-1] != '/') {
+ base += "/"
+ }
-ReaddirReq.prototype.process = function() {
- originalReaddir.call(fs, this.path, this.done)
+ // remove base from path
+ path = path.replace(base, '')
+ path = path.replace(/[\/]+/g, '/')
+ return path
}
-ReaddirReq.prototype.done = function(er, files) {
- if (files && files.sort)
- files = files.sort()
- Req.prototype.done.call(this, er, files)
- onclose()
-}
+},{}],164:[function(require,module,exports){
+var flat = require('./mp2v_flat')
+var tree = require('./mp2v_tree')
+var x = module.exports = tree
+x.flat = flat
+x.tree = tree
-var originalClose = fs.close
-fs.close = close
+},{"./mp2v_flat":165,"./mp2v_tree":166}],165:[function(require,module,exports){
+var Multipart = require('multipart-stream')
+var duplexify = require('duplexify')
+var stream = require('stream')
+var common = require('./common')
+randomString = common.randomString
-function close (fd, cb) {
- debug('close', fd)
- if (typeof cb !== "function") cb = noop
- delete fds['fd' + fd]
- originalClose.call(fs, fd, function(er) {
- onclose()
- cb(er)
- })
-}
+module.exports = v2mpFlat
+// we'll create three streams:
+// - w: a writable stream. it receives vinyl files
+// - mp: a multipart stream
+// - r: a readable stream. it outputs multipart data
+function v2mpFlat(opts) {
+ opts = opts || {}
+ opts.boundary = opts.boundary || randomString()
-var originalCloseSync = fs.closeSync
-fs.closeSync = closeSync
+ var w = new stream.Writable({objectMode: true})
+ var r = new stream.PassThrough({objectMode: true})
+ var mp = new Multipart(opts.boundary)
-function closeSync (fd) {
- try {
- return originalCloseSync(fd)
- } finally {
- onclose()
+ // connect w -> mp
+ w._write = function(file, enc, cb) {
+ writePart(mp, file, cb)
}
-}
+ // connect mp -> r
+ w.on('finish', function() {
+ // apparently cannot add parts while streaming :(
+ mp.pipe(r)
+ })
-// Req class
-function Req () {
- // start processing
- this.done = this.done.bind(this)
- this.failures = 0
- this.process()
+ var out = duplexify.obj(w, r)
+ out.boundary = opts.boundary
+ return out
}
-Req.prototype.done = function (er, result) {
- var tryAgain = false
- if (er) {
- var code = er.code
- var tryAgain = code === "EMFILE" || code === "ENFILE"
- if (process.platform === "win32")
- tryAgain = tryAgain || code === "OK"
- }
+function writePart(mp, file, cb) {
+ var c = file.contents
+ if (c === null)
+ c = emptyStream()
- if (tryAgain) {
- this.failures ++
- enqueue(this)
- } else {
- var cb = this.cb
- cb(er, result)
- }
+ mp.addPart({
+ body: file.contents,
+ headers: headersForFile(file),
+ })
+ cb(null)
+ // TODO: call cb when file.contents ends instead.
}
-var queue = []
-
-function enqueue(req) {
- queue.push(req)
- debug('enqueue %d %s', queue.length, req.constructor.name, req)
+function emptyStream() {
+ var s = new stream.PassThrough({objectMode: true})
+ s.write(null)
+ return s
}
-function onclose() {
- var req = queue.shift()
- if (req) {
- debug('process', req.constructor.name, req)
- req.process()
- }
-}
+function headersForFile(file) {
+ var fpath = common.cleanPath(file.path, file.base)
-}).call(this,require('_process'))
-},{"./fs.js":190,"./polyfills.js":192,"_process":64,"assert":1,"util":90}],192:[function(require,module,exports){
-(function (process){
-var fs = require('./fs.js')
-var constants = require('constants')
+ var h = {}
+ h['Content-Disposition'] = 'file; filename="' +fpath+ '"'
-var origCwd = process.cwd
-var cwd = null
-process.cwd = function() {
- if (!cwd)
- cwd = origCwd.call(process)
- return cwd
-}
-var chdir = process.chdir
-process.chdir = function(d) {
- cwd = null
- chdir.call(process, d)
+ if (file.isDirectory()) {
+ h['Content-Type'] = 'text/directory'
+ } else {
+ h['Content-Type'] = 'application/octet-stream'
+ }
+
+ return h
}
-// (re-)implement some things that are known busted or missing.
+function randomString () {
+ return Math.random().toString(36).slice(2) +
+ Math.random().toString(36).slice(2) +
+ Math.random().toString(36).slice(2) +
+ Math.random().toString(36).slice(2)
+}
-// lchmod, broken prior to 0.6.2
-// back-port the fix here.
-if (constants.hasOwnProperty('O_SYMLINK') &&
- process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
- fs.lchmod = function (path, mode, callback) {
- callback = callback || noop
- fs.open( path
- , constants.O_WRONLY | constants.O_SYMLINK
- , mode
- , function (err, fd) {
- if (err) {
- callback(err)
- return
- }
- // prefer to return the chmod error, if one occurs,
- // but still try to close, and report closing errors if they occur.
- fs.fchmod(fd, mode, function (err) {
- fs.close(fd, function(err2) {
- callback(err || err2)
- })
- })
- })
- }
+},{"./common":163,"duplexify":16,"multipart-stream":91,"stream":124}],166:[function(require,module,exports){
+var Multipart = require('multipart-stream')
+var duplexify = require('duplexify')
+var stream = require('stream')
+var Path = require('path')
+var collect = require('./collect')
+var common = require('./common')
+var randomString = common.randomString
- fs.lchmodSync = function (path, mode) {
- var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
+module.exports = v2mpTree
- // prefer to return the chmod error, if one occurs,
- // but still try to close, and report closing errors if they occur.
- var err, err2
- try {
- var ret = fs.fchmodSync(fd, mode)
- } catch (er) {
- err = er
- }
- try {
- fs.closeSync(fd)
- } catch (er) {
- err2 = er
- }
- if (err || err2) throw (err || err2)
- return ret
- }
-}
+// we'll create three streams:
+// - w: a writable stream. it receives vinyl files
+// - mps: a multipart stream in between.
+// - r: a readable stream. it outputs text. needed to
+// give the caller something, while w finishes.
+//
+// we do all processing on the incoming vinyl metadata
+// before we transform to multipart, that's becasue we
+// need a complete view of the filesystem. (/ the code
+// i lifted did that and it's convoluted enough not to
+// want to change it...)
+function v2mpTree(opts) {
+ opts = opts || {}
+ opts.boundary = opts.boundary || randomString()
+ var r = new stream.PassThrough({objectMode: true})
+ var w = new stream.PassThrough({objectMode: true})
+ var out = duplexify.obj(w, r)
+ out.boundary = opts.boundary
-// lutimes implementation, or no-op
-if (!fs.lutimes) {
- if (constants.hasOwnProperty("O_SYMLINK")) {
- fs.lutimes = function (path, at, mt, cb) {
- fs.open(path, constants.O_SYMLINK, function (er, fd) {
- cb = cb || noop
- if (er) return cb(er)
- fs.futimes(fd, at, mt, function (er) {
- fs.close(fd, function (er2) {
- return cb(er || er2)
- })
- })
- })
+ collect(w, function(err, files) {
+ if (err) {
+ r.emit('error', err)
+ return
}
- fs.lutimesSync = function (path, at, mt) {
- var fd = fs.openSync(path, constants.O_SYMLINK)
- , err
- , err2
- , ret
+ try {
+ // construct the multipart streams from these files
+ var mp = streamForCollection(opts.boundary, files)
- try {
- var ret = fs.futimesSync(fd, at, mt)
- } catch (er) {
- err = er
- }
- try {
- fs.closeSync(fd)
- } catch (er) {
- err2 = er
+ // let the user know what the content-type header is.
+ // this is because multipart is such a grossly defined protocol :(
+ out.multipartHdr = "Content-Type: multipart/mixed; boundary=" + mp.boundary
+ if (opts.writeHeader) {
+ r.write(out.multipartHdr + "\r\n")
+ r.write("\r\n")
}
- if (err || err2) throw (err || err2)
- return ret
- }
-
- } else if (fs.utimensat && constants.hasOwnProperty("AT_SYMLINK_NOFOLLOW")) {
- // maybe utimensat will be bound soonish?
- fs.lutimes = function (path, at, mt, cb) {
- fs.utimensat(path, at, mt, constants.AT_SYMLINK_NOFOLLOW, cb)
- }
- fs.lutimesSync = function (path, at, mt) {
- return fs.utimensatSync(path, at, mt, constants.AT_SYMLINK_NOFOLLOW)
+ // now we pipe the multipart stream to
+ // the readable thing we returned.
+ // now the user will start receiving data.
+ mp.pipe(r)
+ } catch (e) {
+ r.emit('error', e)
}
+ })
- } else {
- fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) }
- fs.lutimesSync = function () {}
- }
+ return out
}
+function streamForCollection(boundary, files) {
+ var parts = []
-// https://github.com/isaacs/node-graceful-fs/issues/4
-// Chown should not fail on einval or eperm if non-root.
-// It should not fail on enosys ever, as this just indicates
-// that a fs doesn't support the intended operation.
-
-fs.chown = chownFix(fs.chown)
-fs.fchown = chownFix(fs.fchown)
-fs.lchown = chownFix(fs.lchown)
-
-fs.chmod = chownFix(fs.chmod)
-fs.fchmod = chownFix(fs.fchmod)
-fs.lchmod = chownFix(fs.lchmod)
-
-fs.chownSync = chownFixSync(fs.chownSync)
-fs.fchownSync = chownFixSync(fs.fchownSync)
-fs.lchownSync = chownFixSync(fs.lchownSync)
-
-fs.chmodSync = chownFix(fs.chmodSync)
-fs.fchmodSync = chownFix(fs.fchmodSync)
-fs.lchmodSync = chownFix(fs.lchmodSync)
-
-function chownFix (orig) {
- if (!orig) return orig
- return function (target, uid, gid, cb) {
- return orig.call(fs, target, uid, gid, function (er, res) {
- if (chownErOk(er)) er = null
- cb(er, res)
- })
+ // walk through all the named files in order.
+ files.paths.sort()
+ for (var i = 0; i < files.paths.length; i++) {
+ var n = files.paths[i]
+ var s = streamForPath(files, n)
+ if (!s) continue // already processed.
+ parts.push({ body: s, headers: headersForFile(files.named[n])})
}
-}
-function chownFixSync (orig) {
- if (!orig) return orig
- return function (target, uid, gid) {
- try {
- return orig.call(fs, target, uid, gid)
- } catch (er) {
- if (!chownErOk(er)) throw er
- }
+ // then add all the unnamed files.
+ for (var i = 0; i < files.unnamed.length; i++) {
+ var f = files.unnamed[i] // raw vinyl files.
+ var s = streamForWrapped(files, f)
+ if (!s) continue // already processed.
+ parts.push({ body: s, headers: headersForFile(f)})
}
-}
-
-// ENOSYS means that the fs doesn't support the op. Just ignore
-// that, because it doesn't matter.
-//
-// if there's no getuid, or if getuid() is something other
-// than 0, and the error is EINVAL or EPERM, then just ignore
-// it.
-//
-// This specific case is a silent failure in cp, install, tar,
-// and most other unix tools that manage permissions.
-//
-// When running as root, or if other types of errors are
-// encountered, then it's strict.
-function chownErOk (er) {
- if (!er)
- return true
-
- if (er.code === "ENOSYS")
- return true
- var nonroot = !process.getuid || process.getuid() !== 0
- if (nonroot) {
- if (er.code === "EINVAL" || er.code === "EPERM")
- return true
+ if (parts.length == 0) { // avoid multipart bug.
+ var s = streamForString("--" + boundary + "--\r\n") // close multipart.
+ s.boundary = boundary
+ return s
}
- return false
+ // write out multipart.
+ var mp = new Multipart(boundary)
+ for (var i = 0; i < parts.length; i++) {
+ mp.addPart(parts[i])
+ }
+ return mp
}
+function streamForString(str) {
+ var s = new stream.PassThrough()
+ s.end(str)
+ return s
+}
-// if lchmod/lchown do not exist, then make them no-ops
-if (!fs.lchmod) {
- fs.lchmod = function (path, mode, cb) {
- process.nextTick(cb)
+function streamForPath(files, path) {
+ var o = files.named[path]
+ if (!o) {
+ throw new Error("no object for path. lib error.")
}
- fs.lchmodSync = function () {}
-}
-if (!fs.lchown) {
- fs.lchown = function (path, uid, gid, cb) {
- process.nextTick(cb)
+
+ if (!o.file) { // no vinyl file, so no need to process this one.
+ return
}
- fs.lchownSync = function () {}
-}
+ // avoid processing twice.
+ if (o.done) return null // already processed it
+ o.done = true // mark it as already processed.
+ return streamForWrapped(files, o)
+}
-// on Windows, A/V software can lock the directory, causing this
-// to fail with an EACCES or EPERM if the directory contains newly
-// created files. Try again on failure, for up to 1 second.
-if (process.platform === "win32") {
- var rename_ = fs.rename
- fs.rename = function rename (from, to, cb) {
- var start = Date.now()
- rename_(from, to, function CB (er) {
- if (er
- && (er.code === "EACCES" || er.code === "EPERM")
- && Date.now() - start < 1000) {
- return rename_(from, to, CB)
- }
- if(cb) cb(er)
- })
+function streamForWrapped(files, f) {
+ if (f.file.isDirectory()) {
+ return multipartForDir(files, f)
}
+
+ // stream for a file
+ return f.file.contents
}
+function multipartForDir(files, dir) {
+ // we still write the boundary for the headers
+ dir.boundary = randomString()
-// if read() returns EAGAIN, then just try it again.
-var read = fs.read
-fs.read = function (fd, buffer, offset, length, position, callback_) {
- var callback
- if (callback_ && typeof callback_ === 'function') {
- var eagCounter = 0
- callback = function (er, _, __) {
- if (er && er.code === 'EAGAIN' && eagCounter < 10) {
- eagCounter ++
- return read.call(fs, fd, buffer, offset, length, position, callback)
- }
- callback_.apply(this, arguments)
- }
+ if (!dir.children || dir.children.length < 1) {
+ // we have to intercept this here and return an empty stream.
+ // because multipart lib fails if there are no parts. see
+ // https://github.com/hendrikcech/multipart-stream/issues/1
+ return streamForString("--" + dir.boundary + "--\r\n") // close multipart.
}
- return read.call(fs, fd, buffer, offset, length, position, callback)
-}
-var readSync = fs.readSync
-fs.readSync = function (fd, buffer, offset, length, position) {
- var eagCounter = 0
- while (true) {
- try {
- return readSync.call(fs, fd, buffer, offset, length, position)
- } catch (er) {
- if (er.code === 'EAGAIN' && eagCounter < 10) {
- eagCounter ++
- continue
- }
- throw er
+ var mp = new Multipart(dir.boundary)
+ for (var i = 0; i < dir.children.length; i++) {
+ var child = dir.children[i]
+ if (!child.file) {
+ throw new Error("child has no file. lib error")
}
+
+ var s = streamForPath(files, child.file.path)
+ mp.addPart({ body: s, headers: headersForFile(child) })
}
+ return mp
}
+function headersForFile(o) {
+ var fpath = common.cleanPath(o.file.path, o.file.base)
-}).call(this,require('_process'))
-},{"./fs.js":190,"_process":64,"constants":10}],193:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-var isUtf8 = require('is-utf8');
-
-var stripBom = module.exports = function (arg) {
- if (typeof arg === 'string') {
- return arg.replace(/^\ufeff/g, '');
- }
-
- if (Buffer.isBuffer(arg) && isUtf8(arg) &&
- arg[0] === 0xef && arg[1] === 0xbb && arg[2] === 0xbf) {
- return arg.slice(3);
- }
-
- return arg;
-};
-
-stripBom.stream = function () {
- var firstChunk = require('first-chunk-stream');
-
- return firstChunk({minSize: 3}, function (chunk, enc, cb) {
- this.push(stripBom(chunk));
- cb();
- });
-};
-
-}).call(this,{"isBuffer":require("/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js")})
-},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21,"first-chunk-stream":194,"is-utf8":195}],194:[function(require,module,exports){
-arguments[4][143][0].apply(exports,arguments)
-},{"buffer":6,"dup":143,"stream":81,"util":90}],195:[function(require,module,exports){
-
-exports = module.exports = function(bytes)
-{
- var i = 0;
- while(i < bytes.length)
- {
- if( (// ASCII
- bytes[i] == 0x09 ||
- bytes[i] == 0x0A ||
- bytes[i] == 0x0D ||
- (0x20 <= bytes[i] && bytes[i] <= 0x7E)
- )
- ) {
- i += 1;
- continue;
- }
-
- if( (// non-overlong 2-byte
- (0xC2 <= bytes[i] && bytes[i] <= 0xDF) &&
- (0x80 <= bytes[i+1] && bytes[i+1] <= 0xBF)
- )
- ) {
- i += 2;
- continue;
- }
-
- if( (// excluding overlongs
- bytes[i] == 0xE0 &&
- (0xA0 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
- (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
- ) ||
- (// straight 3-byte
- ((0xE1 <= bytes[i] && bytes[i] <= 0xEC) ||
- bytes[i] == 0xEE ||
- bytes[i] == 0xEF) &&
- (0x80 <= bytes[i + 1] && bytes[i+1] <= 0xBF) &&
- (0x80 <= bytes[i+2] && bytes[i+2] <= 0xBF)
- ) ||
- (// excluding surrogates
- bytes[i] == 0xED &&
- (0x80 <= bytes[i+1] && bytes[i+1] <= 0x9F) &&
- (0x80 <= bytes[i+2] && bytes[i+2] <= 0xBF)
- )
- ) {
- i += 3;
- continue;
- }
-
- if( (// planes 1-3
- bytes[i] == 0xF0 &&
- (0x90 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
- (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
- (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
- ) ||
- (// planes 4-15
- (0xF1 <= bytes[i] && bytes[i] <= 0xF3) &&
- (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
- (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
- (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
- ) ||
- (// plane 16
- bytes[i] == 0xF4 &&
- (0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x8F) &&
- (0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
- (0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
- )
- ) {
- i += 4;
- continue;
- }
+ var h = {}
+ h['Content-Disposition'] = 'file; filename="' + fpath + '"'
- return false;
- }
+ if (o.file.isDirectory()) {
+ h['Content-Type'] = 'multipart/mixed; boundary=' + o.boundary
+ } else {
+ h['Content-Type'] = 'application/octet-stream'
+ }
- return true;
+ return h
}
-},{}],196:[function(require,module,exports){
-arguments[4][162][0].apply(exports,arguments)
-},{"./_stream_readable":197,"./_stream_writable":199,"_process":64,"core-util-is":200,"dup":162,"inherits":201}],197:[function(require,module,exports){
-arguments[4][173][0].apply(exports,arguments)
-},{"_process":64,"buffer":6,"core-util-is":200,"dup":173,"events":14,"inherits":201,"isarray":202,"stream":81,"string_decoder/":203}],198:[function(require,module,exports){
-arguments[4][174][0].apply(exports,arguments)
-},{"./_stream_duplex":196,"core-util-is":200,"dup":174,"inherits":201}],199:[function(require,module,exports){
-arguments[4][175][0].apply(exports,arguments)
-},{"./_stream_duplex":196,"_process":64,"buffer":6,"core-util-is":200,"dup":175,"inherits":201,"stream":81}],200:[function(require,module,exports){
-arguments[4][11][0].apply(exports,arguments)
-},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21,"dup":11}],201:[function(require,module,exports){
-arguments[4][18][0].apply(exports,arguments)
-},{"dup":18}],202:[function(require,module,exports){
-arguments[4][22][0].apply(exports,arguments)
-},{"dup":22}],203:[function(require,module,exports){
-arguments[4][86][0].apply(exports,arguments)
-},{"buffer":6,"dup":86}],204:[function(require,module,exports){
-arguments[4][77][0].apply(exports,arguments)
-},{"./lib/_stream_transform.js":198,"dup":77}],205:[function(require,module,exports){
-arguments[4][55][0].apply(exports,arguments)
-},{"dup":55}],206:[function(require,module,exports){
-arguments[4][182][0].apply(exports,arguments)
-},{"_process":64,"dup":182,"readable-stream/transform":204,"util":90,"xtend":205}],207:[function(require,module,exports){
+},{"./collect":162,"./common":163,"duplexify":16,"multipart-stream":91,"path":104,"stream":124}],167:[function(require,module,exports){
(function (process){
var path = require('path');
var clone = require('clone');
@@ -21591,6 +20700,7 @@ var isStream = require('./lib/isStream');
var isNull = require('./lib/isNull');
var inspectStream = require('./lib/inspectStream');
var Stream = require('stream');
+var replaceExt = require('replace-ext');
function File(file) {
if (!file) file = {};
@@ -21599,16 +20709,16 @@ function File(file) {
var history = file.path ? [file.path] : file.history;
this.history = history || [];
- // TODO: should this be moved to vinyl-fs?
this.cwd = file.cwd || process.cwd();
this.base = file.base || this.cwd;
- // stat = fs stats object
- // TODO: should this be moved to vinyl-fs?
+ // stat = files stats object
this.stat = file.stat || null;
// contents = stream, buffer, or null if not read
this.contents = file.contents || null;
+
+ this._isVinyl = true;
}
File.prototype.isBuffer = function() {
@@ -21636,7 +20746,7 @@ File.prototype.clone = function(opt) {
};
} else if (!opt) {
opt = {
- deep: false,
+ deep: true,
contents: true
};
} else {
@@ -21716,6 +20826,10 @@ File.prototype.inspect = function() {
return '';
};
+File.isVinyl = function(file) {
+ return file && file._isVinyl === true;
+};
+
// virtual attributes
// or stuff with extra logic
Object.defineProperty(File.prototype, 'contents', {
@@ -21742,6 +20856,39 @@ Object.defineProperty(File.prototype, 'relative', {
}
});
+Object.defineProperty(File.prototype, 'dirname', {
+ get: function() {
+ if (!this.path) throw new Error('No path specified! Can not get dirname.');
+ return path.dirname(this.path);
+ },
+ set: function(dirname) {
+ if (!this.path) throw new Error('No path specified! Can not set dirname.');
+ this.path = path.join(dirname, path.basename(this.path));
+ }
+});
+
+Object.defineProperty(File.prototype, 'basename', {
+ get: function() {
+ if (!this.path) throw new Error('No path specified! Can not get basename.');
+ return path.basename(this.path);
+ },
+ set: function(basename) {
+ if (!this.path) throw new Error('No path specified! Can not set basename.');
+ this.path = path.join(path.dirname(this.path), basename);
+ }
+});
+
+Object.defineProperty(File.prototype, 'extname', {
+ get: function() {
+ if (!this.path) throw new Error('No path specified! Can not get extname.');
+ return path.extname(this.path);
+ },
+ set: function(extname) {
+ if (!this.path) throw new Error('No path specified! Can not set extname.');
+ this.path = replaceExt(this.path, extname);
+ }
+});
+
Object.defineProperty(File.prototype, 'path', {
get: function() {
return this.history[this.history.length - 1];
@@ -21756,495 +20903,603 @@ Object.defineProperty(File.prototype, 'path', {
}
});
-module.exports = File;
+module.exports = File;
+
+}).call(this,require('_process'))
+},{"./lib/cloneBuffer":168,"./lib/inspectStream":169,"./lib/isBuffer":170,"./lib/isNull":171,"./lib/isStream":172,"_process":107,"clone":11,"clone-stats":10,"path":104,"replace-ext":122,"stream":124}],168:[function(require,module,exports){
+arguments[4][39][0].apply(exports,arguments)
+},{"buffer":8,"dup":39}],169:[function(require,module,exports){
+var isStream = require('./isStream');
+
+module.exports = function(stream) {
+ if (!isStream(stream)) return;
+
+ var streamType = stream.constructor.name;
+ // avoid StreamStream
+ if (streamType === 'Stream') streamType = '';
+
+ return '<'+streamType+'Stream>';
+};
+
+},{"./isStream":172}],170:[function(require,module,exports){
+arguments[4][41][0].apply(exports,arguments)
+},{"buffer":8,"dup":41}],171:[function(require,module,exports){
+arguments[4][42][0].apply(exports,arguments)
+},{"dup":42}],172:[function(require,module,exports){
+var Stream = require('stream').Stream;
+
+module.exports = function(o) {
+ return !!o && o instanceof Stream;
+};
+},{"stream":124}],173:[function(require,module,exports){
+// Returns a wrapper function that returns a wrapped callback
+// The wrapper function should do some stuff, and return a
+// presumably different callback function.
+// This makes sure that own properties are retained, so that
+// decorations and such are not lost along the way.
+module.exports = wrappy
+function wrappy (fn, cb) {
+ if (fn && cb) return wrappy(fn)(cb)
+
+ if (typeof fn !== 'function')
+ throw new TypeError('need wrapper function')
+
+ Object.keys(fn).forEach(function (k) {
+ wrapper[k] = fn[k]
+ })
+
+ return wrapper
+
+ function wrapper() {
+ var args = new Array(arguments.length)
+ for (var i = 0; i < args.length; i++) {
+ args[i] = arguments[i]
+ }
+ var ret = fn.apply(this, args)
+ var cb = args[args.length-1]
+ if (typeof ret === 'function' && ret !== cb) {
+ Object.keys(cb).forEach(function (k) {
+ ret[k] = cb[k]
+ })
+ }
+ return ret
+ }
+}
+
+},{}],174:[function(require,module,exports){
+arguments[4][89][0].apply(exports,arguments)
+},{"dup":89}],175:[function(require,module,exports){
+module.exports={
+ "name": "ipfs-api",
+ "version": "2.4.1",
+ "description": "A client library for the IPFS API",
+ "main": "src/index.js",
+ "dependencies": {
+ "brfs": "^1.4.0",
+ "merge-stream": "^1.0.0",
+ "multiaddr": "^1.0.0",
+ "multipart-stream": "^2.0.0",
+ "vinyl": "^0.5.1",
+ "vinyl-fs-browser": "^2.1.1-1",
+ "vinyl-multipart-stream": "^1.2.6"
+ },
+ "browserify": {
+ "transform": [
+ "brfs"
+ ]
+ },
+ "engines": {
+ "node": "^4.0.0"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/ipfs/node-ipfs-api"
+ },
+ "devDependencies": {
+ "brfs": "^1.4.1",
+ "browserify": "^11.0.0",
+ "concurrently": "^0.1.1",
+ "gulp": "^3.9.0",
+ "gulp-mocha": "^2.1.3",
+ "ipfsd-ctl": "^0.5.5",
+ "karma": "^0.13.11",
+ "karma-browserify": "^4.4.0",
+ "karma-chrome-launcher": "^0.2.1",
+ "karma-mocha": "^0.2.0",
+ "karma-sauce-launcher": "^0.3.0",
+ "mocha": "^2.3.3",
+ "pre-commit": "^1.0.6",
+ "run-sequence": "^1.1.4",
+ "standard": "^5.2.2",
+ "uglify-js": "^2.4.24"
+ },
+ "scripts": {
+ "test": "./node_modules/.bin/gulp",
+ "test:node": "./node_modules/.bin/gulp test:node",
+ "test:browser": "./node_modules/.bin/gulp test:browser",
+ "lint": "./node_modules/.bin/standard",
+ "build": "./node_modules/.bin/browserify -t brfs -s ipfsAPI -e ./src/index.js | tee dist/ipfsapi.js | ./node_modules/.bin/uglifyjs -m > dist/ipfsapi.min.js"
+ },
+ "standard": {
+ "ignore": [
+ "dist/*"
+ ]
+ },
+ "pre-commit": [
+ "lint"
+ ],
+ "keywords": [
+ "ipfs"
+ ],
+ "author": "Matt Bell ",
+ "contributors": [
+ "Travis Person ",
+ "Jeromy Jonson ",
+ "David Dias ",
+ "Juan Benet "
+ ],
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/ipfs/node-ipfs-api/issues"
+ },
+ "homepage": "https://github.com/ipfs/node-ipfs-api"
+}
+
+},{}],176:[function(require,module,exports){
+var pkg = require('../package.json')
+
+exports = module.exports = function getConfig () {
+ return {
+ 'api-path': '/api/v0/',
+ 'user-agent': '/node-' + pkg.name + '/' + pkg.version + '/',
+ 'host': 'localhost',
+ 'port': '5001'
+ }
+}
+
+},{"../package.json":175}],177:[function(require,module,exports){
+(function (Buffer){
+var File = require('vinyl')
+var vinylfs = require('vinyl-fs-browser')
+var vmps = require('vinyl-multipart-stream')
+var stream = require('stream')
+var Merge = require('merge-stream')
+
+exports = module.exports = getFilesStream
+
+function getFilesStream (files, opts) {
+ if (!files) return null
+ if (!Array.isArray(files)) files = [files]
+
+ // merge all inputs into one stream
+ var adder = new Merge()
+
+ // single stream for pushing directly
+ var single = new stream.PassThrough({objectMode: true})
+ adder.add(single)
+
+ for (var i = 0; i < files.length; i++) {
+ var file = files[i]
+
+ if (typeof (file) === 'string') {
+ var srcOpts = {
+ buffer: false,
+ stripBOM: false,
+ followSymlinks: opts.followSymlinks != null ? opts.followSymlinks : true
+ }
+
+ // add the file or dir itself
+ adder.add(vinylfs.src(file, srcOpts))
+
+ // if recursive, glob the contents
+ if (opts.r || opts.recursive) {
+ adder.add(vinylfs.src(file + '/**/*', srcOpts))
+ }
+ } else {
+ // try to create a single vinyl file, and push it.
+ // throws if cannot use the file.
+ single.push(vinylFile(file))
+ }
+ }
+
+ single.end()
+ return adder.pipe(vmps())
+}
+
+// vinylFile tries to cast a file object to a vinyl file.
+// it's agressive. If it _cannot_ be converted to a file,
+// it returns null.
+function vinylFile (file) {
+ if (file instanceof File) {
+ return file // it's a vinyl file.
+ }
+
+ // let's try to make a vinyl file?
+ var f = {cwd: '/', base: '/', path: ''}
+ if (file.contents && file.path) {
+ // set the cwd + base, if there.
+ f.path = file.path
+ f.cwd = file.cwd || f.cwd
+ f.base = file.base || f.base
+ f.contents = file.contents
+ } else {
+ // ok maybe we just have contents?
+ f.contents = file
+ }
+
+ // ensure the contents are safe to pass.
+ // throws if vinyl cannot use the contents
+ f.contents = vinylContentsSafe(f.contents)
+ return new File(f)
+}
+
+function vinylContentsSafe (c) {
+ if (Buffer.isBuffer(c)) return c
+ if (typeof (c) === 'string') return c
+ if (c instanceof stream.Stream) return c
+ if (typeof (c.pipe) === 'function') {
+ // hey, looks like a stream. but vinyl won't detect it.
+ // pipe it to a PassThrough, and use that
+ var s = new stream.PassThrough()
+ return c.pipe(s)
+ }
+
+ throw new Error('vinyl will not accept: ' + c)
+}
+
+}).call(this,{"isBuffer":require("../node_modules/is-buffer/index.js")})
+},{"../node_modules/is-buffer/index.js":50,"merge-stream":83,"stream":124,"vinyl":167,"vinyl-fs-browser":139,"vinyl-multipart-stream":164}],178:[function(require,module,exports){
+(function (Buffer){
+var multiaddr = require('multiaddr')
+var getConfig = require('./config')
+var getRequestAPI = require('./request-api')
+
+exports = module.exports = IpfsAPI
-}).call(this,require('_process'))
-},{"./lib/cloneBuffer":208,"./lib/inspectStream":209,"./lib/isBuffer":210,"./lib/isNull":211,"./lib/isStream":212,"_process":64,"clone":214,"clone-stats":213,"path":62,"stream":81}],208:[function(require,module,exports){
-arguments[4][97][0].apply(exports,arguments)
-},{"buffer":6,"dup":97}],209:[function(require,module,exports){
-arguments[4][98][0].apply(exports,arguments)
-},{"./isStream":212,"dup":98}],210:[function(require,module,exports){
-var buf = require('buffer');
-var Buffer = buf.Buffer;
-
-// could use Buffer.isBuffer but this is the same exact thing...
-module.exports = function(o) {
- return typeof o === 'object' && o instanceof Buffer;
-};
-},{"buffer":6}],211:[function(require,module,exports){
-arguments[4][100][0].apply(exports,arguments)
-},{"dup":100}],212:[function(require,module,exports){
-arguments[4][101][0].apply(exports,arguments)
-},{"dup":101,"stream":81}],213:[function(require,module,exports){
-arguments[4][8][0].apply(exports,arguments)
-},{"dup":8,"fs":4}],214:[function(require,module,exports){
-(function (Buffer){
-'use strict';
+function IpfsAPI (host_or_multiaddr, port) {
+ var self = this
+ var config = getConfig()
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
+ if (!(self instanceof IpfsAPI)) {
+ return new IpfsAPI(host_or_multiaddr, port)
+ }
-// shim for Node's 'util' package
-// DO NOT REMOVE THIS! It is required for compatibility with EnderJS (http://enderjs.com/).
-var util = {
- isArray: function (ar) {
- return Array.isArray(ar) || (typeof ar === 'object' && objectToString(ar) === '[object Array]');
- },
- isDate: function (d) {
- return typeof d === 'object' && objectToString(d) === '[object Date]';
- },
- isRegExp: function (re) {
- return typeof re === 'object' && objectToString(re) === '[object RegExp]';
- },
- getRegExpFlags: function (re) {
- var flags = '';
- re.global && (flags += 'g');
- re.ignoreCase && (flags += 'i');
- re.multiline && (flags += 'm');
- return flags;
+ try {
+ var maddr = multiaddr(host_or_multiaddr).nodeAddress()
+ config.host = maddr.address
+ config.port = maddr.port
+ } catch (e) {
+ config.host = host_or_multiaddr
+ config.port = port || config.port
}
-};
+ // autoconfigure in browser
+ if (!config.host &&
+ typeof window !== 'undefined') {
+ var split = window.location.host.split(':')
+ config.host = split[0]
+ config.port = split[1]
+ }
-if (typeof module === 'object')
- module.exports = clone;
+ var requestAPI = getRequestAPI(config)
-/**
- * Clones (copies) an Object using deep copying.
- *
- * This function supports circular references by default, but if you are certain
- * there are no circular references in your object, you can save some CPU time
- * by calling clone(obj, false).
- *
- * Caution: if `circular` is false and `parent` contains circular references,
- * your program may enter an infinite loop and crash.
- *
- * @param `parent` - the object to be cloned
- * @param `circular` - set to true if the object to be cloned may contain
- * circular references. (optional - true by default)
- * @param `depth` - set to a number if the object is only to be cloned to
- * a particular depth. (optional - defaults to Infinity)
- * @param `prototype` - sets the prototype to be used when cloning an object.
- * (optional - defaults to parent prototype).
-*/
+ // -- Internal
-function clone(parent, circular, depth, prototype) {
- // maintain two arrays for circular references, where corresponding parents
- // and children have the same index
- var allParents = [];
- var allChildren = [];
+ function command (name) {
+ return function (opts, cb) {
+ if (typeof (opts) === 'function') {
+ cb = opts
+ opts = {}
+ }
+ return requestAPI(name, null, opts, null, cb)
+ }
+ }
- var useBuffer = typeof Buffer != 'undefined';
+ function argCommand (name) {
+ return function (arg, opts, cb) {
+ if (typeof (opts) === 'function') {
+ cb = opts
+ opts = {}
+ }
+ return requestAPI(name, arg, opts, null, cb)
+ }
+ }
- if (typeof circular == 'undefined')
- circular = true;
+ // -- Interface
- if (typeof depth == 'undefined')
- depth = Infinity;
+ self.send = requestAPI
- // recurse this function so we don't reset allParents and allChildren
- function _clone(parent, depth) {
- // cloning null always returns null
- if (parent === null)
- return null;
+ self.add = function (files, opts, cb) {
+ if (typeof (opts) === 'function' && cb === undefined) {
+ cb = opts
+ opts = {}
+ }
- if (depth == 0)
- return parent;
+ return requestAPI('add', null, opts, files, cb)
+ }
- var child;
- var proto;
- if (typeof parent != 'object') {
- return parent;
- }
+ self.cat = argCommand('cat')
+ self.ls = argCommand('ls')
- if (util.isArray(parent)) {
- child = [];
- } else if (util.isRegExp(parent)) {
- child = new RegExp(parent.source, util.getRegExpFlags(parent));
- if (parent.lastIndex) child.lastIndex = parent.lastIndex;
- } else if (util.isDate(parent)) {
- child = new Date(parent.getTime());
- } else if (useBuffer && Buffer.isBuffer(parent)) {
- child = new Buffer(parent.length);
- parent.copy(child);
- return child;
- } else {
- if (typeof prototype == 'undefined') {
- proto = Object.getPrototypeOf(parent);
- child = Object.create(proto);
- }
- else {
- child = Object.create(prototype);
- proto = prototype;
+ self.config = {
+ get: argCommand('config'),
+ set: function (key, value, opts, cb) {
+ if (typeof (opts) === 'function') {
+ cb = opts
+ opts = {}
}
+ return requestAPI('config', [key, value], opts, null, cb)
+ },
+ show: function (cb) {
+ return requestAPI('config/show', null, null, null, true, cb)
+ },
+ replace: function (file, cb) {
+ return requestAPI('config/replace', null, null, file, cb)
}
+ }
- if (circular) {
- var index = allParents.indexOf(parent);
+ self.update = {
+ apply: command('update'),
+ check: command('update/check'),
+ log: command('update/log')
+ }
- if (index != -1) {
- return allChildren[index];
- }
- allParents.push(parent);
- allChildren.push(child);
+ self.version = command('version')
+ self.commands = command('commands')
+
+ self.mount = function (ipfs, ipns, cb) {
+ if (typeof ipfs === 'function') {
+ cb = ipfs
+ ipfs = null
+ } else if (typeof ipns === 'function') {
+ cb = ipns
+ ipns = null
}
+ var opts = {}
+ if (ipfs) opts.f = ipfs
+ if (ipns) opts.n = ipns
+ return requestAPI('mount', null, opts, null, cb)
+ }
- for (var i in parent) {
- var attrs;
- if (proto) {
- attrs = Object.getOwnPropertyDescriptor(proto, i);
- }
-
- if (attrs && attrs.set == null) {
- continue;
+ self.diag = {
+ net: command('diag/net')
+ }
+
+ self.block = {
+ get: argCommand('block/get'),
+ put: function (file, cb) {
+ if (Array.isArray(file)) {
+ return cb(null, new Error('block.put() only accepts 1 file'))
}
- child[i] = _clone(parent[i], depth - 1);
+ return requestAPI('block/put', null, null, file, cb)
}
+ }
- return child;
+ self.object = {
+ get: argCommand('object/get'),
+ put: function (file, encoding, cb) {
+ if (typeof encoding === 'function') {
+ return cb(null, new Error("Must specify an object encoding ('json' or 'protobuf')"))
+ }
+ return requestAPI('object/put', encoding, null, file, cb)
+ },
+ data: argCommand('object/data'),
+ stat: argCommand('object/stat'),
+ links: argCommand('object/links')
}
- return _clone(parent, depth);
-}
+ self.swarm = {
+ peers: command('swarm/peers'),
+ connect: argCommand('swarm/connect')
+ }
-/**
- * Simple flat clone using prototype, accepts only objects, usefull for property
- * override on FLAT configuration object (no nested props).
- *
- * USE WITH CAUTION! This may not behave as you wish if you do not know how this
- * works.
- */
-clone.clonePrototype = function(parent) {
- if (parent === null)
- return null;
+ self.ping = function (id, cb) {
+ return requestAPI('ping', id, { n: 1 }, null, function (err, res) {
+ if (err) return cb(err, null)
+ cb(null, res[1])
+ })
+ }
- var c = function () {};
- c.prototype = parent;
- return new c();
-};
+ self.id = function (id, cb) {
+ if (typeof id === 'function') {
+ cb = id
+ id = null
+ }
+ return requestAPI('id', id, null, null, cb)
+ }
-}).call(this,require("buffer").Buffer)
-},{"buffer":6}],215:[function(require,module,exports){
-arguments[4][195][0].apply(exports,arguments)
-},{"dup":195}],216:[function(require,module,exports){
-'use strict';
+ self.pin = {
+ add: function (hash, opts, cb) {
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = null
+ }
-module.exports = function isValidGlob(glob) {
- if (typeof glob === 'string' && glob.length > 0) {
- return true;
- }
- if (Array.isArray(glob)) {
- return glob.length !== 0 && every(glob);
- }
- return false;
-};
+ requestAPI('pin/add', hash, opts, null, cb)
+ },
+ remove: function (hash, opts, cb) {
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = null
+ }
-function every(arr) {
- var len = arr.length;
- while (len--) {
- if (typeof arr[len] !== 'string' || arr[len].length <= 0) {
- return false;
+ requestAPI('pin/rm', hash, opts, null, cb)
+ },
+ list: function (type, cb) {
+ if (typeof type === 'function') {
+ cb = type
+ type = null
+ }
+ var opts = null
+ if (type) opts = { type: type }
+ return requestAPI('pin/ls', null, opts, null, cb)
}
}
- return true;
-}
-
-},{}],217:[function(require,module,exports){
-arguments[4][51][0].apply(exports,arguments)
-},{"dup":51,"readable-stream/passthrough":229}],218:[function(require,module,exports){
-arguments[4][70][0].apply(exports,arguments)
-},{"./_stream_readable":220,"./_stream_writable":222,"core-util-is":223,"dup":70,"inherits":224,"process-nextick-args":226}],219:[function(require,module,exports){
-arguments[4][71][0].apply(exports,arguments)
-},{"./_stream_transform":221,"core-util-is":223,"dup":71,"inherits":224}],220:[function(require,module,exports){
-arguments[4][72][0].apply(exports,arguments)
-},{"./_stream_duplex":218,"_process":64,"buffer":6,"core-util-is":223,"dup":72,"events":14,"inherits":224,"isarray":225,"process-nextick-args":226,"string_decoder/":227,"util":3}],221:[function(require,module,exports){
-arguments[4][73][0].apply(exports,arguments)
-},{"./_stream_duplex":218,"core-util-is":223,"dup":73,"inherits":224}],222:[function(require,module,exports){
-arguments[4][74][0].apply(exports,arguments)
-},{"./_stream_duplex":218,"buffer":6,"core-util-is":223,"dup":74,"events":14,"inherits":224,"process-nextick-args":226,"util-deprecate":228}],223:[function(require,module,exports){
-arguments[4][11][0].apply(exports,arguments)
-},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21,"dup":11}],224:[function(require,module,exports){
-arguments[4][18][0].apply(exports,arguments)
-},{"dup":18}],225:[function(require,module,exports){
-arguments[4][22][0].apply(exports,arguments)
-},{"dup":22}],226:[function(require,module,exports){
-arguments[4][63][0].apply(exports,arguments)
-},{"_process":64,"dup":63}],227:[function(require,module,exports){
-arguments[4][86][0].apply(exports,arguments)
-},{"buffer":6,"dup":86}],228:[function(require,module,exports){
-arguments[4][88][0].apply(exports,arguments)
-},{"dup":88}],229:[function(require,module,exports){
-arguments[4][75][0].apply(exports,arguments)
-},{"./lib/_stream_passthrough.js":219,"dup":75}],230:[function(require,module,exports){
-(function (process){
-var path = require('path');
-var fs = require('fs');
-var _0777 = parseInt('0777', 8);
-module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
+ self.gateway = {
+ enable: command('gateway/enable'),
+ disable: command('gateway/disable')
+ }
-function mkdirP (p, opts, f, made) {
- if (typeof opts === 'function') {
- f = opts;
- opts = {};
- }
- else if (!opts || typeof opts !== 'object') {
- opts = { mode: opts };
- }
-
- var mode = opts.mode;
- var xfs = opts.fs || fs;
-
- if (mode === undefined) {
- mode = _0777 & (~process.umask());
+ self.log = {
+ tail: function (cb) {
+ return requestAPI('log/tail', null, {enc: 'text'}, null, true, cb)
}
- if (!made) made = null;
-
- var cb = f || function () {};
- p = path.resolve(p);
-
- xfs.mkdir(p, mode, function (er) {
- if (!er) {
- made = made || p;
- return cb(null, made);
- }
- switch (er.code) {
- case 'ENOENT':
- mkdirP(path.dirname(p), opts, function (er, made) {
- if (er) cb(er, made);
- else mkdirP(p, opts, cb, made);
- });
- break;
+ }
- // In the case of any other error, just see if there's a dir
- // there already. If so, then hooray! If not, then something
- // is borked.
- default:
- xfs.stat(p, function (er2, stat) {
- // if the stat fails, then that's super weird.
- // let the original error be the failure reason.
- if (er2 || !stat.isDirectory()) cb(er, made)
- else cb(null, made);
- });
- break;
- }
- });
-}
+ self.name = {
+ publish: argCommand('name/publish'),
+ resolve: argCommand('name/resolve')
+ }
-mkdirP.sync = function sync (p, opts, made) {
- if (!opts || typeof opts !== 'object') {
- opts = { mode: opts };
- }
-
- var mode = opts.mode;
- var xfs = opts.fs || fs;
-
- if (mode === undefined) {
- mode = _0777 & (~process.umask());
- }
- if (!made) made = null;
+ self.Buffer = Buffer
- p = path.resolve(p);
+ self.refs = argCommand('refs')
+ self.refs.local = command('refs/local')
- try {
- xfs.mkdirSync(p, mode);
- made = made || p;
- }
- catch (err0) {
- switch (err0.code) {
- case 'ENOENT' :
- made = sync(path.dirname(p), opts, made);
- sync(p, opts, made);
- break;
+ self.dht = {
+ findprovs: argCommand('dht/findprovs'),
- // In the case of any other error, just see if there's a dir
- // there already. If so, then hooray! If not, then something
- // is borked.
- default:
- var stat;
- try {
- stat = xfs.statSync(p);
- }
- catch (err1) {
- throw err0;
- }
- if (!stat.isDirectory()) throw err0;
- break;
- }
- }
+ get: function (key, opts, cb) {
+ if (typeof (opts) === 'function' && !cb) {
+ cb = opts
+ opts = null
+ }
- return made;
-};
+ return requestAPI('dht/get', key, opts, null, function (err, res) {
+ if (err) return cb(err)
+ if (!res) return cb(new Error('empty response'))
+ if (res.length === 0) return cb(new Error('no value returned for key'))
-}).call(this,require('_process'))
-},{"_process":64,"fs":4,"path":62}],231:[function(require,module,exports){
-/* eslint-disable no-unused-vars */
-'use strict';
-var hasOwnProperty = Object.prototype.hasOwnProperty;
-var propIsEnumerable = Object.prototype.propertyIsEnumerable;
+ if (res[0].Type === 5) {
+ cb(null, res[0].Extra)
+ } else {
+ cb(res)
+ }
+ })
+ },
-function toObject(val) {
- if (val === null || val === undefined) {
- throw new TypeError('Object.assign cannot be called with null or undefined');
- }
+ put: function (key, value, opts, cb) {
+ if (typeof (opts) === 'function' && !cb) {
+ cb = opts
+ opts = null
+ }
- return Object(val);
+ return requestAPI('dht/put', [key, value], opts, null, cb)
+ }
+ }
}
-module.exports = Object.assign || function (target, source) {
- var from;
- var to = toObject(target);
- var symbols;
+}).call(this,require("buffer").Buffer)
+},{"./config":176,"./request-api":179,"buffer":8,"multiaddr":88}],179:[function(require,module,exports){
+var http = require('http')
+var qs = require('querystring')
+var getFilesStream = require('./get-files-stream')
- for (var s = 1; s < arguments.length; s++) {
- from = Object(arguments[s]);
+exports = module.exports = function getRequestAPI (config) {
+ return requestAPI
- for (var key in from) {
- if (hasOwnProperty.call(from, key)) {
- to[key] = from[key];
- }
- }
+ function requestAPI (path, args, opts, files, buffer, cb) {
+ var query, stream, contentType
+ contentType = 'application/json'
- if (Object.getOwnPropertySymbols) {
- symbols = Object.getOwnPropertySymbols(from);
- for (var i = 0; i < symbols.length; i++) {
- if (propIsEnumerable.call(from, symbols[i])) {
- to[symbols[i]] = from[symbols[i]];
- }
- }
- }
- }
+ if (Array.isArray(path)) path = path.join('/')
- return to;
-};
+ opts = opts || {}
-},{}],232:[function(require,module,exports){
-'use strict';
-var firstChunk = require('first-chunk-stream');
-var stripBom = require('strip-bom');
+ if (args && !Array.isArray(args)) args = [args]
+ if (args) opts.arg = args
-module.exports = function () {
- return firstChunk({minSize: 3}, function (chunk, enc, cb) {
- this.push(stripBom(chunk));
- cb();
- });
-};
+ if (files) {
+ stream = getFilesStream(files, opts)
+ if (!stream.boundary) {
+ throw new Error('no boundary in multipart stream')
+ }
+ contentType = 'multipart/form-data; boundary=' + stream.boundary
+ }
-},{"first-chunk-stream":143,"strip-bom":233}],233:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-var isUtf8 = require('is-utf8');
+ if (typeof buffer === 'function') {
+ cb = buffer
+ buffer = false
+ }
-module.exports = function (x) {
- // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
- // conversion translates it to FEFF (UTF-16 BOM)
- if (typeof x === 'string' && x.charCodeAt(0) === 0xFEFF) {
- return x.slice(1);
- }
+ // this option is only used internally, not passed to daemon
+ delete opts.followSymlinks
- if (Buffer.isBuffer(x) && isUtf8(x) &&
- x[0] === 0xEF && x[1] === 0xBB && x[2] === 0xBF) {
- return x.slice(3);
- }
+ opts['stream-channels'] = true
+ query = qs.stringify(opts)
- return x;
-};
+ var reqo = {
+ method: files ? 'POST' : 'GET',
+ host: config.host,
+ port: config.port,
+ path: config['api-path'] + path + '?' + query,
+ headers: {
+ 'User-Agent': config['user-agent'],
+ 'Content-Type': contentType
+ },
+ withCredentials: false
+ }
-}).call(this,{"isBuffer":require("/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js")})
-},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21,"is-utf8":215}],234:[function(require,module,exports){
-"use strict";
+ var req = http.request(reqo, function (res) {
+ var data = ''
+ var objects = []
+ var stream = !!res.headers && !!res.headers['x-stream-output']
+ var chunkedObjects = !!res.headers && !!res.headers['x-chunked-output']
-module.exports = make
-module.exports.ctor = ctor
-module.exports.objCtor = objCtor
-module.exports.obj = obj
+ if (stream && !buffer) return cb(null, res)
+ if (chunkedObjects && buffer) return cb(null, res)
-var through2 = require("through2")
-var xtend = require("xtend")
+ res.on('data', function (chunk) {
+ if (!chunkedObjects) {
+ data += chunk
+ return data
+ }
-function ctor(options, fn) {
- if (typeof options == "function") {
- fn = options
- options = {}
- }
+ try {
+ var obj = JSON.parse(chunk.toString())
+ objects.push(obj)
+ } catch (e) {
+ chunkedObjects = false
+ data += chunk
+ }
+ })
+ res.on('end', function () {
+ var parsed
- var Filter = through2.ctor(options, function (chunk, encoding, callback) {
- if (this.options.wantStrings) chunk = chunk.toString()
- if (fn.call(this, chunk, this._index++)) this.push(chunk)
- return callback()
- })
- Filter.prototype._index = 0
- return Filter
-}
+ if (!chunkedObjects) {
+ try {
+ parsed = JSON.parse(data)
+ data = parsed
+ } catch (e) {}
+ } else {
+ data = objects
+ }
-function objCtor(options, fn) {
- if (typeof options === "function") {
- fn = options
- options = {}
- }
- options = xtend({objectMode: true, highWaterMark: 16}, options)
- return ctor(options, fn)
-}
+ if (res.statusCode >= 400 || !res.statusCode) {
+ if (!data) data = new Error()
+ return cb(data, null)
+ }
+ return cb(null, data)
+ })
+ res.on('error', function (err) {
+ return cb(err, null)
+ })
+ })
-function make(options, fn) {
- return ctor(options, fn)()
-}
+ req.on('error', function (err) {
+ return cb(err, null)
+ })
-function obj(options, fn) {
- if (typeof options === "function") {
- fn = options
- options = {}
+ if (stream) {
+ stream.pipe(req)
+ } else {
+ req.end()
+ }
+
+ return req
}
- options = xtend({objectMode: true, highWaterMark: 16}, options)
- return make(options, fn)
}
-},{"through2":248,"xtend":235}],235:[function(require,module,exports){
-arguments[4][55][0].apply(exports,arguments)
-},{"dup":55}],236:[function(require,module,exports){
-arguments[4][70][0].apply(exports,arguments)
-},{"./_stream_readable":237,"./_stream_writable":239,"core-util-is":240,"dup":70,"inherits":241,"process-nextick-args":243}],237:[function(require,module,exports){
-arguments[4][72][0].apply(exports,arguments)
-},{"./_stream_duplex":236,"_process":64,"buffer":6,"core-util-is":240,"dup":72,"events":14,"inherits":241,"isarray":242,"process-nextick-args":243,"string_decoder/":244,"util":3}],238:[function(require,module,exports){
-arguments[4][73][0].apply(exports,arguments)
-},{"./_stream_duplex":236,"core-util-is":240,"dup":73,"inherits":241}],239:[function(require,module,exports){
-arguments[4][74][0].apply(exports,arguments)
-},{"./_stream_duplex":236,"buffer":6,"core-util-is":240,"dup":74,"events":14,"inherits":241,"process-nextick-args":243,"util-deprecate":245}],240:[function(require,module,exports){
-arguments[4][11][0].apply(exports,arguments)
-},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21,"dup":11}],241:[function(require,module,exports){
-arguments[4][18][0].apply(exports,arguments)
-},{"dup":18}],242:[function(require,module,exports){
-arguments[4][22][0].apply(exports,arguments)
-},{"dup":22}],243:[function(require,module,exports){
-arguments[4][63][0].apply(exports,arguments)
-},{"_process":64,"dup":63}],244:[function(require,module,exports){
-arguments[4][86][0].apply(exports,arguments)
-},{"buffer":6,"dup":86}],245:[function(require,module,exports){
-arguments[4][88][0].apply(exports,arguments)
-},{"dup":88}],246:[function(require,module,exports){
-arguments[4][77][0].apply(exports,arguments)
-},{"./lib/_stream_transform.js":238,"dup":77}],247:[function(require,module,exports){
-arguments[4][55][0].apply(exports,arguments)
-},{"dup":55}],248:[function(require,module,exports){
-arguments[4][182][0].apply(exports,arguments)
-},{"_process":64,"dup":182,"readable-stream/transform":246,"util":90,"xtend":247}],249:[function(require,module,exports){
-arguments[4][96][0].apply(exports,arguments)
-},{"./lib/cloneBuffer":250,"./lib/inspectStream":251,"./lib/isBuffer":252,"./lib/isNull":253,"./lib/isStream":254,"_process":64,"clone":256,"clone-stats":255,"dup":96,"path":62,"replace-ext":257,"stream":81}],250:[function(require,module,exports){
-arguments[4][97][0].apply(exports,arguments)
-},{"buffer":6,"dup":97}],251:[function(require,module,exports){
-arguments[4][98][0].apply(exports,arguments)
-},{"./isStream":254,"dup":98}],252:[function(require,module,exports){
-arguments[4][99][0].apply(exports,arguments)
-},{"buffer":6,"dup":99}],253:[function(require,module,exports){
-arguments[4][100][0].apply(exports,arguments)
-},{"dup":100}],254:[function(require,module,exports){
-arguments[4][101][0].apply(exports,arguments)
-},{"dup":101,"stream":81}],255:[function(require,module,exports){
-arguments[4][8][0].apply(exports,arguments)
-},{"dup":8,"fs":4}],256:[function(require,module,exports){
-arguments[4][9][0].apply(exports,arguments)
-},{"buffer":6,"dup":9}],257:[function(require,module,exports){
-arguments[4][79][0].apply(exports,arguments)
-},{"dup":79,"path":62}]},{},[108])(108)
+},{"./get-files-stream":177,"http":125,"querystring":111}]},{},[178])(178)
});
\ No newline at end of file
diff --git a/dist/ipfsapi.min.js b/dist/ipfsapi.min.js
index 91e4ff59a..976640c55 100644
--- a/dist/ipfsapi.min.js
+++ b/dist/ipfsapi.min.js
@@ -1,9 +1,8 @@
-(function(e){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=e()}else if(typeof define==="function"&&define.amd){define([],e)}else{var t;if(typeof window!=="undefined"){t=window}else if(typeof global!=="undefined"){t=global}else if(typeof self!=="undefined"){t=self}else{t=this}t.ipfsAPI=e()}})(function(){var define,module,exports;return function e(t,r,n){function i(a,o){if(!r[a]){if(!t[a]){var f=typeof require=="function"&&require;if(!o&&f)return f(a,!0);if(s)return s(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var c=r[a]={exports:{}};t[a][0].call(c.exports,function(e){var r=t[a][1][e];return i(r?r:e)},c,c.exports,e,t,r,n)}return r[a].exports}var s=typeof require=="function"&&require;for(var a=0;a=0){var a=n.indexOf("\n",s+1);n=n.substring(a+1)}this.stack=n}}};n.inherits(a.AssertionError,Error);function o(e,t){if(n.isUndefined(t)){return""+t}if(n.isNumber(t)&&!isFinite(t)){return t.toString()}if(n.isFunction(t)||n.isRegExp(t)){return t.toString()}return t}function f(e,t){if(n.isString(e)){return e.length=0;u--){if(a[u]!=o[u])return false}for(u=a.length-1;u>=0;u--){f=a[u];if(!h(e[f],t[f]))return false}return true}a.notDeepEqual=function S(e,t,r){if(h(e,t)){c(e,t,r,"notDeepEqual",a.notDeepEqual)}};a.strictEqual=function E(e,t,r){if(e!==t){c(e,t,r,"===",a.strictEqual)}};a.notStrictEqual=function x(e,t,r){if(e===t){c(e,t,r,"!==",a.notStrictEqual)}};function v(e,t){if(!e||!t){return false}if(Object.prototype.toString.call(t)=="[object RegExp]"){return t.test(e)}else if(e instanceof t){return true}else if(t.call({},e)===true){return true}return false}function m(e,t,r,i){var s;if(n.isString(r)){i=r;r=null}try{t()}catch(a){s=a}i=(r&&r.name?" ("+r.name+").":".")+(i?" "+i:".");if(e&&!s){c(s,r,"Missing expected exception"+i)}if(!e&&v(s,r)){c(s,r,"Got unwanted exception"+i)}if(e&&s&&r&&!v(s,r)||!e&&s){throw s}}a.throws=function(e,t,r){m.apply(this,[true].concat(i.call(arguments)))};a.doesNotThrow=function(e,t){m.apply(this,[false].concat(i.call(arguments)))};a.ifError=function(e){if(e){throw e}};var g=Object.keys||function(e){var t=[];for(var r in e){if(s.call(e,r))t.push(r)}return t}},{"util/":90}],2:[function(e,t,r){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(e){"use strict";var t=typeof Uint8Array!=="undefined"?Uint8Array:Array;var r="+".charCodeAt(0);var i="/".charCodeAt(0);var s="0".charCodeAt(0);var a="a".charCodeAt(0);var o="A".charCodeAt(0);var f="-".charCodeAt(0);var u="_".charCodeAt(0);function c(e){var t=e.charCodeAt(0);if(t===r||t===f)return 62;if(t===i||t===u)return 63;if(t
0){throw new Error("Invalid string. Length must be a multiple of 4")}var f=e.length;a="="===e.charAt(f-2)?2:"="===e.charAt(f-1)?1:0;o=new t(e.length*3/4-a);i=a>0?e.length-4:e.length;var u=0;function l(e){o[u++]=e}for(r=0,n=0;r>16);l((s&65280)>>8);l(s&255)}if(a===2){s=c(e.charAt(r))<<2|c(e.charAt(r+1))>>4;l(s&255)}else if(a===1){s=c(e.charAt(r))<<10|c(e.charAt(r+1))<<4|c(e.charAt(r+2))>>2;l(s>>8&255);l(s&255)}return o}function h(e){var t,r=e.length%3,i="",s,a;function o(e){return n.charAt(e)}function f(e){return o(e>>18&63)+o(e>>12&63)+o(e>>6&63)+o(e&63)}for(t=0,a=e.length-r;t>2);i+=o(s<<4&63);i+="==";break;case 2:s=(e[e.length-2]<<8)+e[e.length-1];i+=o(s>>10);i+=o(s>>4&63);i+=o(s<<2&63);i+="=";break}return i}e.toByteArray=l;e.fromByteArray=h})(typeof r==="undefined"?this.base64js={}:r)},{}],3:[function(e,t,r){},{}],4:[function(e,t,r){arguments[4][3][0].apply(r,arguments)},{dup:3}],5:[function(e,t,r){var n=e("buffer").Buffer;t.exports=function(e,t){if(!n.isBuffer(e))return undefined;if(!n.isBuffer(t))return undefined;if(typeof e.equals==="function")return e.equals(t);if(e.length!==t.length)return false;for(var r=0;r1)return new f(e,arguments[1]);return new f(e)}this.length=0;this.parent=undefined;if(typeof e==="number"){return u(this,e)}if(typeof e==="string"){return c(this,e,arguments.length>1?arguments[1]:"utf8")}return l(this,e)}function u(e,t){e=b(e,t<0?0:y(t)|0);if(!f.TYPED_ARRAY_SUPPORT){for(var r=0;r>>1;if(r)e.parent=a;return e}function y(e){if(e>=o()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+o().toString(16)+" bytes")}return e|0}function w(e,t){if(!(this instanceof w))return new w(e,t);var r=new f(e,t);delete r.parent;return r}f.isBuffer=function ee(e){return!!(e!=null&&e._isBuffer)};f.compare=function te(e,t){if(!f.isBuffer(e)||!f.isBuffer(t)){throw new TypeError("Arguments must be Buffers")}if(e===t)return 0;var r=e.length;var n=t.length;var i=0;var s=Math.min(r,n);while(i>>1;case"base64":return Q(e).length;default:if(n)return X(e).length;t=(""+t).toLowerCase();n=true}}}f.byteLength=_;f.prototype.length=undefined;f.prototype.parent=undefined;function S(e,t,r){var n=false;t=t|0;r=r===undefined||r===Infinity?this.length:r|0;if(!e)e="utf8";if(t<0)t=0;if(r>this.length)r=this.length;if(r<=t)return"";while(true){switch(e){case"hex":return N(this,t,r);case"utf8":case"utf-8":return A(this,t,r);case"ascii":return C(this,t,r);case"binary":return M(this,t,r);case"base64":return L(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase();n=true}}}f.prototype.toString=function ie(){var e=this.length|0;if(e===0)return"";if(arguments.length===0)return A(this,0,e);return S.apply(this,arguments)};f.prototype.equals=function se(e){if(!f.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return true;return f.compare(this,e)===0};f.prototype.inspect=function ae(){var e="";var t=r.INSPECT_MAX_BYTES;if(this.length>0){e=this.toString("hex",0,t).match(/.{2}/g).join(" ");if(this.length>t)e+=" ... "}return""};f.prototype.compare=function oe(e){if(!f.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(this===e)return 0;return f.compare(this,e)};f.prototype.indexOf=function fe(e,t){if(t>2147483647)t=2147483647;else if(t<-2147483648)t=-2147483648;t>>=0;if(this.length===0)return-1;if(t>=this.length)return-1;if(t<0)t=Math.max(this.length+t,0);if(typeof e==="string"){if(e.length===0)return-1;return String.prototype.indexOf.call(this,e,t)}if(f.isBuffer(e)){return r(this,e,t)}if(typeof e==="number"){if(f.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,e,t)}return r(this,[e],t)}function r(e,t,r){var n=-1;for(var i=0;r+ii){n=i}}var s=t.length;if(s%2!==0)throw new Error("Invalid hex string");if(n>s/2){n=s/2}for(var a=0;as)r=s;if(e.length>0&&(r<0||t<0)||t>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!n)n="utf8";var a=false;for(;;){switch(n){case"hex":return E(this,e,t,r);case"utf8":case"utf-8":return x(this,e,t,r);case"ascii":return O(this,e,t,r);case"binary":return j(this,e,t,r);case"base64":return k(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase();a=true}}};f.prototype.toJSON=function he(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function L(e,t,r){if(t===0&&r===e.length){return n.fromByteArray(e)}else{return n.fromByteArray(e.slice(t,r))}}function A(e,t,r){r=Math.min(e.length,r);var n=[];var i=t;while(i239?4:s>223?3:s>191?2:1;if(i+o<=r){var f,u,c,l;switch(o){case 1:if(s<128){a=s}break;case 2:f=e[i+1];if((f&192)===128){l=(s&31)<<6|f&63;if(l>127){a=l}}break;case 3:f=e[i+1];u=e[i+2];if((f&192)===128&&(u&192)===128){l=(s&15)<<12|(f&63)<<6|u&63;if(l>2047&&(l<55296||l>57343)){a=l}}break;case 4:f=e[i+1];u=e[i+2];c=e[i+3];if((f&192)===128&&(u&192)===128&&(c&192)===128){l=(s&15)<<18|(f&63)<<12|(u&63)<<6|c&63;if(l>65535&&l<1114112){a=l}}}}if(a===null){a=65533;o=1}else if(a>65535){a-=65536;n.push(a>>>10&1023|55296);a=56320|a&1023}n.push(a);i+=o}return T(n)}var I=4096;function T(e){var t=e.length;if(t<=I){return String.fromCharCode.apply(String,e)}var r="";var n=0;while(nn)r=n;var i="";for(var s=t;sr){e=r}if(t<0){t+=r;if(t<0)t=0}else if(t>r){t=r}if(tr)throw new RangeError("Trying to access beyond buffer length")}f.prototype.readUIntLE=function de(e,t,r){e=e|0;t=t|0;if(!r)B(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s0&&(i*=256)){n+=this[e+--t]*i}return n};f.prototype.readUInt8=function me(e,t){if(!t)B(e,1,this.length);return this[e]};f.prototype.readUInt16LE=function ge(e,t){if(!t)B(e,2,this.length);return this[e]|this[e+1]<<8};f.prototype.readUInt16BE=function be(e,t){if(!t)B(e,2,this.length);return this[e]<<8|this[e+1]};f.prototype.readUInt32LE=function ye(e,t){if(!t)B(e,4,this.length);return(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};f.prototype.readUInt32BE=function we(e,t){if(!t)B(e,4,this.length);return this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};f.prototype.readIntLE=function _e(e,t,r){e=e|0;t=t|0;if(!r)B(e,t,this.length);var n=this[e];var i=1;var s=0;while(++s=i)n-=Math.pow(2,8*t);return n};f.prototype.readIntBE=function Se(e,t,r){e=e|0;t=t|0;if(!r)B(e,t,this.length);var n=t;var i=1;var s=this[e+--n];while(n>0&&(i*=256)){s+=this[e+--n]*i}i*=128;if(s>=i)s-=Math.pow(2,8*t);return s};f.prototype.readInt8=function Ee(e,t){if(!t)B(e,1,this.length);if(!(this[e]&128))return this[e];return(255-this[e]+1)*-1};f.prototype.readInt16LE=function xe(e,t){if(!t)B(e,2,this.length);var r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};f.prototype.readInt16BE=function Oe(e,t){if(!t)B(e,2,this.length);var r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};f.prototype.readInt32LE=function je(e,t){if(!t)B(e,4,this.length);return this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};f.prototype.readInt32BE=function ke(e,t){if(!t)B(e,4,this.length);return this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};f.prototype.readFloatLE=function Re(e,t){if(!t)B(e,4,this.length);return i.read(this,e,true,23,4)};f.prototype.readFloatBE=function Le(e,t){if(!t)B(e,4,this.length);return i.read(this,e,false,23,4)};f.prototype.readDoubleLE=function Ae(e,t){if(!t)B(e,8,this.length);return i.read(this,e,true,52,8)};f.prototype.readDoubleBE=function Ie(e,t){if(!t)B(e,8,this.length);return i.read(this,e,false,52,8)};function D(e,t,r,n,i,s){if(!f.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(t>i||te.length)throw new RangeError("index out of range")}f.prototype.writeUIntLE=function Te(e,t,r,n){e=+e;t=t|0;r=r|0;if(!n)D(this,e,t,r,Math.pow(2,8*r),0);var i=1;var s=0;this[t]=e&255;while(++s=0&&(s*=256)){this[t+i]=e/s&255}return t+r};f.prototype.writeUInt8=function Me(e,t,r){e=+e;t=t|0;if(!r)D(this,e,t,1,255,0);if(!f.TYPED_ARRAY_SUPPORT)e=Math.floor(e);this[t]=e;return t+1};function U(e,t,r,n){if(t<0)t=65535+t+1;for(var i=0,s=Math.min(e.length-r,2);i>>(n?i:1-i)*8}}f.prototype.writeUInt16LE=function Ne(e,t,r){e=+e;t=t|0;if(!r)D(this,e,t,2,65535,0);if(f.TYPED_ARRAY_SUPPORT){this[t]=e;this[t+1]=e>>>8}else{U(this,e,t,true)}return t+2};f.prototype.writeUInt16BE=function Pe(e,t,r){e=+e;t=t|0;if(!r)D(this,e,t,2,65535,0);if(f.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e}else{U(this,e,t,false)}return t+2};function F(e,t,r,n){if(t<0)t=4294967295+t+1;for(var i=0,s=Math.min(e.length-r,4);i>>(n?i:3-i)*8&255}}f.prototype.writeUInt32LE=function Be(e,t,r){e=+e;t=t|0;if(!r)D(this,e,t,4,4294967295,0);if(f.TYPED_ARRAY_SUPPORT){this[t+3]=e>>>24;this[t+2]=e>>>16;this[t+1]=e>>>8;this[t]=e}else{F(this,e,t,true)}return t+4};f.prototype.writeUInt32BE=function De(e,t,r){e=+e;t=t|0;if(!r)D(this,e,t,4,4294967295,0);if(f.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e}else{F(this,e,t,false)}return t+4};f.prototype.writeIntLE=function Ue(e,t,r,n){e=+e;t=t|0;if(!n){var i=Math.pow(2,8*r-1);D(this,e,t,r,i-1,-i)}var s=0;var a=1;var o=e<0?1:0;this[t]=e&255;while(++s>0)-o&255}return t+r};f.prototype.writeIntBE=function Fe(e,t,r,n){e=+e;t=t|0;if(!n){var i=Math.pow(2,8*r-1);D(this,e,t,r,i-1,-i)}var s=r-1;var a=1;var o=e<0?1:0;this[t+s]=e&255;while(--s>=0&&(a*=256)){this[t+s]=(e/a>>0)-o&255}return t+r};f.prototype.writeInt8=function Ge(e,t,r){e=+e;t=t|0;if(!r)D(this,e,t,1,127,-128);if(!f.TYPED_ARRAY_SUPPORT)e=Math.floor(e);if(e<0)e=255+e+1;this[t]=e;return t+1};f.prototype.writeInt16LE=function We(e,t,r){e=+e;t=t|0;if(!r)D(this,e,t,2,32767,-32768);if(f.TYPED_ARRAY_SUPPORT){this[t]=e;this[t+1]=e>>>8}else{U(this,e,t,true)}return t+2};f.prototype.writeInt16BE=function qe(e,t,r){e=+e;t=t|0;if(!r)D(this,e,t,2,32767,-32768);if(f.TYPED_ARRAY_SUPPORT){this[t]=e>>>8;this[t+1]=e}else{U(this,e,t,false)}return t+2};f.prototype.writeInt32LE=function Ye(e,t,r){e=+e;t=t|0;if(!r)D(this,e,t,4,2147483647,-2147483648);if(f.TYPED_ARRAY_SUPPORT){this[t]=e;this[t+1]=e>>>8;this[t+2]=e>>>16;this[t+3]=e>>>24}else{F(this,e,t,true)}return t+4};f.prototype.writeInt32BE=function He(e,t,r){e=+e;t=t|0;if(!r)D(this,e,t,4,2147483647,-2147483648);if(e<0)e=4294967295+e+1;if(f.TYPED_ARRAY_SUPPORT){this[t]=e>>>24;this[t+1]=e>>>16;this[t+2]=e>>>8;this[t+3]=e}else{F(this,e,t,false)}return t+4};function G(e,t,r,n,i,s){if(t>i||te.length)throw new RangeError("index out of range");if(r<0)throw new RangeError("index out of range")}function W(e,t,r,n,s){if(!s){G(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38)}i.write(e,t,r,n,23,4);return r+4}f.prototype.writeFloatLE=function ze(e,t,r){return W(this,e,t,true,r)};f.prototype.writeFloatBE=function $e(e,t,r){return W(this,e,t,false,r)};function q(e,t,r,n,s){if(!s){G(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308)}i.write(e,t,r,n,52,8);return r+8}f.prototype.writeDoubleLE=function Ke(e,t,r){return q(this,e,t,true,r)};f.prototype.writeDoubleBE=function Xe(e,t,r){return q(this,e,t,false,r)};f.prototype.copy=function Je(e,t,r,n){if(!r)r=0;if(!n&&n!==0)n=this.length;if(t>=e.length)t=e.length;if(!t)t=0;if(n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");if(n>this.length)n=this.length;if(e.length-t=0;s--){e[s+t]=this[s+r]}}else if(i<1e3||!f.TYPED_ARRAY_SUPPORT){for(s=0;s=this.length)throw new RangeError("start out of bounds");if(r<0||r>this.length)throw new RangeError("end out of bounds");var n;if(typeof e==="number"){for(n=t;n55295&&r<57344){if(!i){if(r>56319){if((t-=3)>-1)s.push(239,191,189);continue}else if(a+1===n){if((t-=3)>-1)s.push(239,191,189);continue}i=r;continue}if(r<56320){if((t-=3)>-1)s.push(239,191,189);i=r;continue}r=i-55296<<10|r-56320|65536}else if(i){if((t-=3)>-1)s.push(239,191,189)}i=null;if(r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else{throw new Error("Invalid code point")}}return s}function J(e){var t=[];for(var r=0;r>8;i=r%256;s.push(i);s.push(n)}return s}function Q(e){return n.toByteArray(z(e))}function Z(e,t,r,n){for(var i=0;i=t.length||i>=e.length)break;t[i+r]=e[i]}return i}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":2,ieee754:16,"is-array":20}],7:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Time-out",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Request Entity Too Large",414:"Request-URI Too Large",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Time-out",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],8:[function(e,t,r){var n=e("fs").Stats;t.exports=i;function i(e){var t=new n;Object.keys(e).forEach(function(r){t[r]=e[r]});return t}},{fs:4}],9:[function(e,t,r){(function(e){var r=function(){"use strict";function t(r,n,i,s){var o;if(typeof n==="object"){i=n.depth;s=n.prototype;o=n.filter;n=n.circular}var f=[];var u=[];var c=typeof e!="undefined";if(typeof n=="undefined")n=true;if(typeof i=="undefined")i=Infinity;function l(r,i){if(r===null)return null;if(i==0)return r;var o;var h;if(typeof r!="object"){return r}if(t.__isArray(r)){o=[]}else if(t.__isRegExp(r)){o=new RegExp(r.source,a(r));if(r.lastIndex)o.lastIndex=r.lastIndex}else if(t.__isDate(r)){o=new Date(r.getTime())}else if(c&&e.isBuffer(r)){o=new e(r.length);r.copy(o);return o}else{if(typeof s=="undefined"){h=Object.getPrototypeOf(r);o=Object.create(h)}else{o=Object.create(s);h=s}}if(n){var p=f.indexOf(r);if(p!=-1){return u[p]}f.push(r);u.push(o)}for(var d in r){var v;if(h){v=Object.getOwnPropertyDescriptor(h,d)}if(v&&v.set==null){continue}o[d]=l(r[d],i-1)}return o}return l(r,i)}t.clonePrototype=function o(e){if(e===null)return null;var t=function(){};t.prototype=e;return new t};function r(e){return Object.prototype.toString.call(e)}t.__objToStr=r;function n(e){return typeof e==="object"&&r(e)==="[object Date]"}t.__isDate=n;function i(e){return typeof e==="object"&&r(e)==="[object Array]"}t.__isArray=i;function s(e){return typeof e==="object"&&r(e)==="[object RegExp]"}t.__isRegExp=s;function a(e){var t="";if(e.global)t+="g";if(e.ignoreCase)t+="i";if(e.multiline)t+="m";return t}t.__getRegExpFlags=a;return t}();if(typeof t==="object"&&t.exports){t.exports=r}}).call(this,e("buffer").Buffer)},{buffer:6}],10:[function(e,t,r){t.exports={O_RDONLY:0,O_WRONLY:1,O_RDWR:2,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:512,O_EXCL:2048,O_NOCTTY:131072,O_TRUNC:1024,O_APPEND:8,O_DIRECTORY:1048576,O_NOFOLLOW:256,O_SYNC:128,O_SYMLINK:2097152,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,E2BIG:7,EACCES:13,EADDRINUSE:48,EADDRNOTAVAIL:49,EAFNOSUPPORT:47,EAGAIN:35,EALREADY:37,EBADF:9,EBADMSG:94,EBUSY:16,ECANCELED:89,ECHILD:10,ECONNABORTED:53,ECONNREFUSED:61,ECONNRESET:54,EDEADLK:11,EDESTADDRREQ:39,EDOM:33,EDQUOT:69,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:65,EIDRM:90,EILSEQ:92,EINPROGRESS:36,EINTR:4,EINVAL:22,EIO:5,EISCONN:56,EISDIR:21,ELOOP:62,EMFILE:24,EMLINK:31,EMSGSIZE:40,EMULTIHOP:95,ENAMETOOLONG:63,ENETDOWN:50,ENETRESET:52,ENETUNREACH:51,ENFILE:23,ENOBUFS:55,ENODATA:96,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:77,ENOLINK:97,ENOMEM:12,ENOMSG:91,ENOPROTOOPT:42,ENOSPC:28,ENOSR:98,ENOSTR:99,ENOSYS:78,ENOTCONN:57,ENOTDIR:20,ENOTEMPTY:66,ENOTSOCK:38,ENOTSUP:45,ENOTTY:25,ENXIO:6,EOPNOTSUPP:102,EOVERFLOW:84,EPERM:1,EPIPE:32,EPROTO:100,EPROTONOSUPPORT:43,EPROTOTYPE:41,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:70,ETIME:101,ETIMEDOUT:60,ETXTBSY:26,EWOULDBLOCK:35,EXDEV:18,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:10,SIGFPE:8,SIGKILL:9,SIGUSR1:30,SIGSEGV:11,SIGUSR2:31,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:20,SIGCONT:19,SIGSTOP:17,SIGTSTP:18,SIGTTIN:21,SIGTTOU:22,SIGURG:16,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:23,SIGSYS:12,SSL_OP_ALL:2147486719,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_EPHEMERAL_RSA:2097152,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER:32,SSL_OP_MICROSOFT_SESS_ID_BUG:1,SSL_OP_MSIE_SSLV2_RSA_PADDING:64,SSL_OP_NETSCAPE_CA_DN_BUG:536870912,SSL_OP_NETSCAPE_CHALLENGE_BUG:2,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG:1073741824,SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG:8,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:16777216,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_PKCS1_CHECK_1:0,SSL_OP_PKCS1_CHECK_2:0,SSL_OP_SINGLE_DH_USE:1048576,SSL_OP_SINGLE_ECDH_USE:524288,SSL_OP_SSLEAY_080_CLIENT_DH_BUG:128,SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG:16,SSL_OP_TLS_BLOCK_PADDING_BUG:512,SSL_OP_TLS_D5_BUG:256,SSL_OP_TLS_ROLLBACK_BUG:8388608,NPN_ENABLED:1}},{}],11:[function(e,t,r){(function(e){function t(e){return Array.isArray(e)}r.isArray=t;function n(e){return typeof e==="boolean"}r.isBoolean=n;function i(e){return e===null}r.isNull=i;function s(e){return e==null}r.isNullOrUndefined=s;function a(e){return typeof e==="number"}r.isNumber=a;function o(e){return typeof e==="string"}r.isString=o;function f(e){return typeof e==="symbol"}
-r.isSymbol=f;function u(e){return e===void 0}r.isUndefined=u;function c(e){return l(e)&&g(e)==="[object RegExp]"}r.isRegExp=c;function l(e){return typeof e==="object"&&e!==null}r.isObject=l;function h(e){return l(e)&&g(e)==="[object Date]"}r.isDate=h;function p(e){return l(e)&&(g(e)==="[object Error]"||e instanceof Error)}r.isError=p;function d(e){return typeof e==="function"}r.isFunction=d;function v(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}r.isPrimitive=v;function m(t){return e.isBuffer(t)}r.isBuffer=m;function g(e){return Object.prototype.toString.call(e)}}).call(this,{isBuffer:e("/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js")})},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21}],12:[function(e,t,r){(function(r,n){var i=e("readable-stream");var s=e("end-of-stream");var a=e("util");var o=new n([0]);var f=function(e,t){if(e._corked)e.once("uncork",t);else t()};var u=function(e,t){return function(r){if(r)e.destroy(r.message==="premature close"?null:r);else if(t&&!e._ended)e.end()}};var c=function(e,t){if(!e)return t();if(e._writableState&&e._writableState.finished)return t();if(e._writableState)return e.end(t);e.end();t()};var l=function(e){return new i.Readable({objectMode:true,highWaterMark:16}).wrap(e)};var h=function(e,t,r){if(!(this instanceof h))return new h(e,t,r);i.Duplex.call(this,r);this._writable=null;this._readable=null;this._readable2=null;this._forwardDestroy=!r||r.destroy!==false;this._forwardEnd=!r||r.end!==false;this._corked=1;this._ondrain=null;this._drained=false;this._forwarding=false;this._unwrite=null;this._unread=null;this._ended=false;this.destroyed=false;if(e)this.setWritable(e);if(t)this.setReadable(t)};a.inherits(h,i.Duplex);h.obj=function(e,t,r){if(!r)r={};r.objectMode=true;r.highWaterMark=16;return new h(e,t,r)};h.prototype.cork=function(){if(++this._corked===1)this.emit("cork")};h.prototype.uncork=function(){if(this._corked&&--this._corked===0)this.emit("uncork")};h.prototype.setWritable=function(e){if(this._unwrite)this._unwrite();if(this.destroyed){if(e&&e.destroy)e.destroy();return}if(e===null||e===false){this.end();return}var t=this;var n=s(e,{writable:true,readable:false},u(this,this._forwardEnd));var i=function(){var e=t._ondrain;t._ondrain=null;if(e)e()};var a=function(){t._writable.removeListener("drain",i);n()};if(this._unwrite)r.nextTick(i);this._writable=e;this._writable.on("drain",i);this._unwrite=a;this.uncork()};h.prototype.setReadable=function(e){if(this._unread)this._unread();if(this.destroyed){if(e&&e.destroy)e.destroy();return}if(e===null||e===false){this.push(null);this.resume();return}var t=this;var r=s(e,{writable:false,readable:true},u(this));var n=function(){t._forward()};var i=function(){t.push(null)};var a=function(){t._readable2.removeListener("readable",n);t._readable2.removeListener("end",i);r()};this._drained=true;this._readable=e;this._readable2=e._readableState?e:l(e);this._readable2.on("readable",n);this._readable2.on("end",i);this._unread=a;this._forward()};h.prototype._read=function(){this._drained=true;this._forward()};h.prototype._forward=function(){if(this._forwarding||!this._readable2||!this._drained)return;this._forwarding=true;var e;var t=this._readable2._readableState;while((e=this._readable2.read(t.buffer.length?t.buffer[0].length:t.length))!==null){this._drained=this.push(e)}this._forwarding=false};h.prototype.destroy=function(e){if(this.destroyed)return;this.destroyed=true;var t=this;r.nextTick(function(){t._destroy(e)})};h.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null;if(t)t(e);else this.emit("error",e)}if(this._forwardDestroy){if(this._readable&&this._readable.destroy)this._readable.destroy();if(this._writable&&this._writable.destroy)this._writable.destroy()}this.emit("close")};h.prototype._write=function(e,t,r){if(this.destroyed)return r();if(this._corked)return f(this,this._write.bind(this,e,t,r));if(e===o)return this._finish(r);if(!this._writable)return r();if(this._writable.write(e)===false)this._ondrain=r;else r()};h.prototype._finish=function(e){var t=this;this.emit("preend");f(this,function(){c(t._forwardEnd&&t._writable,function(){if(t._writableState.prefinished===false)t._writableState.prefinished=true;t.emit("prefinish");f(t,e)})})};h.prototype.end=function(e,t,r){if(typeof e==="function")return this.end(null,null,e);if(typeof t==="function")return this.end(e,null,t);this._ended=true;if(e)this.write(e);if(!this._writableState.ending)this.write(o);return i.Writable.prototype.end.call(this,r)};t.exports=h}).call(this,e("_process"),e("buffer").Buffer)},{_process:64,buffer:6,"end-of-stream":13,"readable-stream":76,util:90}],13:[function(e,t,r){var n=e("once");var i=function(){};var s=function(e){return e.setHeader&&typeof e.abort==="function"};var a=function(e,t,r){if(typeof t==="function")return a(e,null,t);if(!t)t={};r=n(r||i);var o=e._writableState;var f=e._readableState;var u=t.readable||t.readable!==false&&e.readable;var c=t.writable||t.writable!==false&&e.writable;var l=function(){if(!e.writable)h()};var h=function(){c=false;if(!u)r()};var p=function(){u=false;if(!c)r()};var d=function(){if(u&&!(f&&f.ended))return r(new Error("premature close"));if(c&&!(o&&o.ended))return r(new Error("premature close"))};var v=function(){e.req.on("finish",h)};if(s(e)){e.on("complete",h);e.on("abort",d);if(e.req)v();else e.on("request",v)}else if(c&&!o){e.on("end",l);e.on("close",l)}e.on("end",p);e.on("finish",h);if(t.error!==false)e.on("error",r);e.on("close",d);return function(){e.removeListener("complete",h);e.removeListener("abort",d);e.removeListener("request",v);if(e.req)e.req.removeListener("finish",h);e.removeListener("end",l);e.removeListener("close",l);e.removeListener("finish",h);e.removeListener("end",p);e.removeListener("error",r);e.removeListener("close",d)}};t.exports=a},{once:60}],14:[function(e,t,r){function n(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}t.exports=n;n.EventEmitter=n;n.prototype._events=undefined;n.prototype._maxListeners=undefined;n.defaultMaxListeners=10;n.prototype.setMaxListeners=function(e){if(!s(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");this._maxListeners=e;return this};n.prototype.emit=function(e){var t,r,n,s,f,u;if(!this._events)this._events={};if(e==="error"){if(!this._events.error||a(this._events.error)&&!this._events.error.length){t=arguments[1];if(t instanceof Error){throw t}throw TypeError('Uncaught, unspecified "error" event.')}}r=this._events[e];if(o(r))return false;if(i(r)){switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:n=arguments.length;s=new Array(n-1);for(f=1;f0&&this._events[e].length>r){this._events[e].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[e].length);if(typeof console.trace==="function"){console.trace()}}}return this};n.prototype.on=n.prototype.addListener;n.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=false;function n(){this.removeListener(e,n);if(!r){r=true;t.apply(this,arguments)}}n.listener=t;this.on(e,n);return this};n.prototype.removeListener=function(e,t){var r,n,s,o;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;r=this._events[e];s=r.length;n=-1;if(r===t||i(r.listener)&&r.listener===t){delete this._events[e];if(this._events.removeListener)this.emit("removeListener",e,t)}else if(a(r)){for(o=s;o-->0;){if(r[o]===t||r[o].listener&&r[o].listener===t){n=o;break}}if(n<0)return this;if(r.length===1){r.length=0;delete this._events[e]}else{r.splice(n,1)}if(this._events.removeListener)this.emit("removeListener",e,t)}return this};n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[e])delete this._events[e];return this}if(arguments.length===0){for(t in this._events){if(t==="removeListener")continue;this.removeAllListeners(t)}this.removeAllListeners("removeListener");this._events={};return this}r=this._events[e];if(i(r)){this.removeListener(e,r)}else{while(r.length)this.removeListener(e,r[r.length-1])}delete this._events[e];return this};n.prototype.listeners=function(e){var t;if(!this._events||!this._events[e])t=[];else if(i(this._events[e]))t=[this._events[e]];else t=this._events[e].slice();return t};n.listenerCount=function(e,t){var r;if(!e._events||!e._events[t])r=0;else if(i(e._events[t]))r=1;else r=e._events[t].length;return r};function i(e){return typeof e==="function"}function s(e){return typeof e==="number"}function a(e){return typeof e==="object"&&e!==null}function o(e){return e===void 0}},{}],15:[function(e,t,r){var n=Object.prototype.hasOwnProperty;var i=Object.prototype.toString;t.exports=function s(e,t,r){if(i.call(t)!=="[object Function]"){throw new TypeError("iterator must be a function")}var s=e.length;if(s===+s){for(var a=0;a>1;var c=-7;var l=r?i-1:0;var h=r?-1:1;var p=e[t+l];l+=h;s=p&(1<<-c)-1;p>>=-c;c+=o;for(;c>0;s=s*256+e[t+l],l+=h,c-=8){}a=s&(1<<-c)-1;s>>=-c;c+=n;for(;c>0;a=a*256+e[t+l],l+=h,c-=8){}if(s===0){s=1-u}else if(s===f){return a?NaN:(p?-1:1)*Infinity}else{a=a+Math.pow(2,n);s=s-u}return(p?-1:1)*a*Math.pow(2,s-n)};r.write=function(e,t,r,n,i,s){var a,o,f;var u=s*8-i-1;var c=(1<>1;var h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0;var p=n?0:s-1;var d=n?1:-1;var v=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){o=isNaN(t)?1:0;a=c}else{a=Math.floor(Math.log(t)/Math.LN2);if(t*(f=Math.pow(2,-a))<1){a--;f*=2}if(a+l>=1){t+=h/f}else{t+=h*Math.pow(2,1-l)}if(t*f>=2){a++;f/=2}if(a+l>=c){o=0;a=c}else if(a+l>=1){o=(t*f-1)*Math.pow(2,i);a=a+l}else{o=t*Math.pow(2,l-1)*Math.pow(2,i);a=0}}for(;i>=8;e[r+p]=o&255,p+=d,o/=256,i-=8){}a=a<0;e[r+p]=a&255,p+=d,a/=256,u-=8){}e[r+p-d]|=v*128}},{}],17:[function(e,t,r){var n=[].indexOf;t.exports=function(e,t){if(n)return e.indexOf(t);for(var r=0;r>8&255;n[r++]=e&255})}else{throw Error("Invalid ip address: "+e)}return n};n.toString=function f(e,t,r){t=~~t;r=r||e.length-t;var n=[];if(r===4){for(var i=0;i32){t="ipv6"}else{t=a(t)}var r=4;if(t==="ipv6"){r=16}var s=new i(r);for(var o=0,f=s.length;o>u)}return n.toString(s)};n.mask=function c(e,c){e=n.toBuffer(e);c=n.toBuffer(c);var t=new i(Math.max(e.length,c.length));if(e.length===c.length){for(var r=0;re.length){i=t;s=e}var a=i.length-s.length;for(var r=a;r>>0};n.fromLong=function E(e){return(e>>>24)+"."+(e>>16&255)+"."+(e>>8&255)+"."+(e&255)};function a(e){return e?e.toLowerCase():"ipv4"}},{buffer:6,os:61}],20:[function(e,t,r){var n=Array.isArray;var i=Object.prototype.toString;t.exports=n||function(e){return!!e&&"[object Array]"==i.call(e)}},{}],21:[function(e,t,r){t.exports=function(e){return!!(e!=null&&(e._isBuffer||e.constructor&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)))}},{}],22:[function(e,t,r){t.exports=Array.isArray||function(e){return Object.prototype.toString.call(e)=="[object Array]"}},{}],23:[function(e,t,r){var n=[];t.exports=n},{}],24:[function(e,t,r){var n=e("lodash._basecreate"),i=e("lodash.isobject"),s=e("lodash._setbinddata"),a=e("lodash._slice");var o=[];var f=o.push;function u(e){var t=e[0],r=e[2],o=e[4];function u(){if(r){var e=a(r);f.apply(e,arguments)}if(this instanceof u){var s=n(t.prototype),c=t.apply(s,e||arguments);return i(c)?c:s}return t.apply(o,e||arguments)}s(u,e);return u}t.exports=u},{"lodash._basecreate":25,"lodash._setbinddata":35,"lodash._slice":37,"lodash.isobject":45}],25:[function(e,t,r){(function(r){var n=e("lodash._isnative"),i=e("lodash.isobject"),s=e("lodash.noop");var a=n(a=Object.create)&&a;function o(e,t){return i(e)?a(e):{}}if(!a){o=function(){function e(){}return function(t){if(i(t)){e.prototype=t;var n=new e;e.prototype=null}return n||r.Object()}}()}t.exports=o}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"lodash._isnative":31,"lodash.isobject":45,"lodash.noop":48}],26:[function(e,t,r){var n=e("lodash.bind"),i=e("lodash.identity"),s=e("lodash._setbinddata"),a=e("lodash.support");var o=/^\s*function[ \n\r\t]+\w/;var f=/\bthis\b/;var u=Function.prototype.toString;function c(e,t,r){if(typeof e!="function"){return i}if(typeof t=="undefined"||!("prototype"in e)){return e}var c=e.__bindData__;if(typeof c=="undefined"){if(a.funcNames){c=!e.name}c=c||!a.funcDecomp;if(!c){var l=u.call(e);if(!a.funcNames){c=!o.test(l)}if(!c){c=f.test(l);s(e,c)}}}if(c===false||c!==true&&c[1]&1){return e}switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,n){return e.call(t,r,n)};case 3:return function(r,n,i){return e.call(t,r,n,i)};case 4:return function(r,n,i,s){return e.call(t,r,n,i,s)}}return n(e,t)}t.exports=c},{"lodash._setbinddata":35,"lodash.bind":38,"lodash.identity":43,"lodash.support":50}],27:[function(e,t,r){var n=e("lodash._basecreate"),i=e("lodash.isobject"),s=e("lodash._setbinddata"),a=e("lodash._slice");var o=[];var f=o.push;function u(e){var t=e[0],r=e[1],o=e[2],c=e[3],l=e[4],h=e[5];var p=r&1,d=r&2,v=r&4,m=r&8,g=t;function b(){var e=p?l:this;if(o){var s=a(o);f.apply(s,arguments)}if(c||v){s||(s=a(arguments));if(c){f.apply(s,c)}if(v&&s.length-1}})}}w.pop();_.pop();if(T){o(w);o(_)}return S}t.exports=y},{"lodash._getarray":30,"lodash._objecttypes":33,"lodash._releasearray":34,"lodash.forin":41,"lodash.isfunction":44}],29:[function(e,t,r){var n=e("lodash._basebind"),i=e("lodash._basecreatewrapper"),s=e("lodash.isfunction"),a=e("lodash._slice");var o=[];var f=o.push,u=o.unshift;function c(e,t,r,o,l,h){var p=t&1,d=t&2,v=t&4,m=t&8,g=t&16,b=t&32;if(!d&&!s(e)){throw new TypeError}if(g&&!r.length){t&=~16;g=r=false}if(b&&!o.length){t&=~32;b=o=false}var y=e&&e.__bindData__;if(y&&y!==true){y=a(y);if(y[2]){y[2]=a(y[2])}if(y[3]){y[3]=a(y[3])}if(p&&!(y[1]&1)){y[4]=l}if(!p&&y[1]&1){t|=8}if(v&&!(y[1]&4)){y[5]=h}if(g){f.apply(y[2]||(y[2]=[]),r)}if(b){u.apply(y[3]||(y[3]=[]),o)}y[1]|=t;return c.apply(null,y)}var w=t==1||t===17?n:i;return w([e,t,r,o,l,h])}t.exports=c},{"lodash._basebind":24,"lodash._basecreatewrapper":27,"lodash._slice":37,"lodash.isfunction":44}],30:[function(e,t,r){var n=e("lodash._arraypool");function i(){return n.pop()||[]}t.exports=i},{"lodash._arraypool":23}],31:[function(e,t,r){var n=Object.prototype;var i=n.toString;var s=RegExp("^"+String(i).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");function a(e){return typeof e=="function"&&s.test(e)}t.exports=a},{}],32:[function(e,t,r){var n=40;t.exports=n},{}],33:[function(e,t,r){var n={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};t.exports=n},{}],34:[function(e,t,r){var n=e("lodash._arraypool"),i=e("lodash._maxpoolsize");function s(e){e.length=0;if(n.length2?n(e,17,i(arguments,2),null,t):n(e,1,null,null,t)}t.exports=s},{"lodash._createwrapper":29,"lodash._slice":37}],39:[function(e,t,r){var n=e("lodash._basecreatecallback"),i=e("lodash._baseisequal"),s=e("lodash.isobject"),a=e("lodash.keys"),o=e("lodash.property");function f(e,t,r){var f=typeof e;if(e==null||f=="function"){return n(e,t,r)}if(f!="object"){return o(e)}var u=a(e),c=u[0],l=e[c];if(u.length==1&&l===l&&!s(l)){return function(e){var t=e[c];return l===t&&(l!==0||1/l==1/t)}}return function(t){var r=u.length,n=false;while(r--){if(!(n=i(t[u[r]],e[u[r]],null,true))){break}}return n}}t.exports=f},{"lodash._basecreatecallback":26,"lodash._baseisequal":28,"lodash.isobject":45,"lodash.keys":46,"lodash.property":49}],40:[function(e,t,r){var n=e("lodash.createcallback"),i=e("lodash.forown");function s(e,t,r){var s=[];t=n(t,r,3);var a=-1,o=e?e.length:0;if(typeof o=="number"){while(++a=r.length)throw S("invalid address: "+e);t.push([i,r[n]])}return t}function c(e){var t=[];n(e,function(e){var r=E(e);t.push(r.name);if(e.length>1)t.push(e[1])});return"/"+t.join("/")}function l(e){return n(e,function(e){var t=E(e);if(e.length>1)return[t.code,a.toBuffer(t.code,e[1])];return[t.code]})}function h(e){return n(e,function(e){var t=E(e);if(e.length>1)return[t.code,a.toString(t.code,e[1])];return[t.code]})}function p(e){return b(r.concat(n(e,function(e){var t=E(e);var n=new r([t.code]);if(e.length>1)n=r.concat([n,e[1]]);return n})))}function d(e){var t=[];for(var r=0;re.length)throw S("Invalid address buffer: "+e.toString("hex"));t.push([n,a])}return t}function v(e){var t=d(e);var r=h(t);return c(r)}function m(e){e=_(e);var t=u(e);var r=l(t);return p(r)}function g(e){return m(e)}function b(e){var t=y(e);if(t)throw t;return new r(e)}function y(e){d(e)}function w(e){try{y(e);return true}catch(t){return false}}function _(e){return"/"+i(e.trim().split("/")).join("/")}function S(e){return new Error("Error parsing address: "+e)}function E(e){var t=o(e[0]);if(e.length>1&&t.size==0)throw S("tuple has address but protocol size is 0");return t}}).call(this,e("buffer").Buffer)},{"./convert":53,"./protocols":56,buffer:6,"lodash.filter":40,"lodash.map":47}],53:[function(e,t,r){(function(r){var n=e("ip");var i=e("./protocols");t.exports=s;function s(e,t){if(t instanceof r)return s.toString(e,t);else return s.toBuffer(e,t)}s.toString=function f(e,t){e=i(e);switch(e.code){case 4:case 41:return n.toString(t);case 6:case 17:case 33:case 132:return o(t)}return t.toString("hex")};s.toBuffer=function u(e,t){e=i(e);switch(e.code){case 4:case 41:return n.toBuffer(t);case 6:case 17:case 33:case 132:return a(parseInt(t,10))}return new r(t,"hex")};function a(e){var t=new r(2);t.writeUInt16BE(e,0);return t}function o(e){return e.readUInt16BE(0)}}).call(this,e("buffer").Buffer)},{"./protocols":56,buffer:6,ip:19}],54:[function(e,t,r){(function(r){var n=e("lodash.map");var i=e("xtend");var s=e("./codec");var a=e("buffer-equal");var o=e("./protocols");var f=new Error("Sorry, Not Implemented Yet.");t.exports=u;function u(e){if(!(this instanceof u))return new u(e);if(!e)e="";if(e instanceof r)this.buffer=s.fromBuffer(e);else if(typeof e=="string"||e instanceof String)this.buffer=s.fromString(e);else if(e.buffer&&e.protos&&e.protoCodes)this.buffer=s.fromBuffer(e.buffer);else throw new Error("addr must be a string, Buffer, or Multiaddr")}u.prototype.toString=function c(){return s.bufferToString(this.buffer)};u.prototype.toOptions=function l(){var e={};var t=this.toString().split("/");e.family=t[1]==="ip4"?"ipv4":"ipv6";e.host=t[2];e.port=t[4];return e};u.prototype.inspect=function h(){return""};u.prototype.protos=function p(){return n(this.protoCodes(),function(e){return i(o(e))})};u.prototype.protos=function d(){return n(this.protoCodes(),function(e){return i(o(e))})};u.prototype.protoCodes=function v(){var e=[];for(var t=0;t0&&!n.call(e,0)){for(var d=0;d0){for(var v=0;v=0&&n.call(e.callee)==="[object Function]"}return r}},{}],60:[function(e,t,r){var n=e("wrappy");t.exports=n(i);i.proto=i(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return i(this)},configurable:true})});function i(e){var t=function(){if(t.called)return t.value;t.called=true;return t.value=e.apply(this,arguments)};t.called=false;return t}},{wrappy:103}],61:[function(e,t,r){r.endianness=function(){return"LE"};r.hostname=function(){if(typeof location!=="undefined"){return location.hostname}else return""};r.loadavg=function(){return[]};r.uptime=function(){return 0};r.freemem=function(){return Number.MAX_VALUE};r.totalmem=function(){return Number.MAX_VALUE};r.cpus=function(){return[]};r.type=function(){return"Browser"};r.release=function(){if(typeof navigator!=="undefined"){return navigator.appVersion}return""};r.networkInterfaces=r.getNetworkInterfaces=function(){return{}};r.arch=function(){return"javascript"};r.platform=function(){return"browser"};r.tmpdir=r.tmpDir=function(){return"/tmp"};r.EOL="\n"},{}],62:[function(e,t,r){(function(e){function t(e,t){var r=0;for(var n=e.length-1;n>=0;n--){var i=e[n];if(i==="."){e.splice(n,1)}else if(i===".."){e.splice(n,1);r++}else if(r){e.splice(n,1);r--}}if(t){for(;r--;r){e.unshift("..")}}return e}var n=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var i=function(e){return n.exec(e).slice(1)};r.resolve=function(){var r="",n=false;for(var i=arguments.length-1;i>=-1&&!n;i--){var a=i>=0?arguments[i]:e.cwd();if(typeof a!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!a){continue}r=a+"/"+r;n=a.charAt(0)==="/"}r=t(s(r.split("/"),function(e){return!!e}),!n).join("/");return(n?"/":"")+r||"."};r.normalize=function(e){var n=r.isAbsolute(e),i=a(e,-1)==="/";e=t(s(e.split("/"),function(e){return!!e}),!n).join("/");if(!e&&!n){e="."}if(e&&i){e+="/"}return(n?"/":"")+e};r.isAbsolute=function(e){return e.charAt(0)==="/"};r.join=function(){var e=Array.prototype.slice.call(arguments,0);return r.normalize(s(e,function(e,t){if(typeof e!=="string"){throw new TypeError("Arguments to path.join must be strings")}return e}).join("/"))};r.relative=function(e,t){e=r.resolve(e).substr(1);t=r.resolve(t).substr(1);function n(e){var t=0;for(;t=0;r--){if(e[r]!=="")break}if(t>r)return[];return e.slice(t,r-t+1)}var i=n(e.split("/"));var s=n(t.split("/"));var a=Math.min(i.length,s.length);var o=a;for(var f=0;f1){for(var r=1;r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},_=u-c,S=Math.floor,E=String.fromCharCode,x;function O(e){throw RangeError(w[e])}function j(e,t){var r=e.length;var n=[];while(r--){n[r]=t(e[r])}return n}function k(e,t){var r=e.split("@");var n="";if(r.length>1){n=r[0]+"@";e=r[1]}e=e.replace(y,".");var i=e.split(".");var s=j(i,t).join(".");return n+s}function R(e){var t=[],r=0,n=e.length,i,s;while(r=55296&&i<=56319&&r65535){e-=65536;t+=E(e>>>10&1023|55296);e=56320|e&1023}t+=E(e);return t}).join("")}function A(e){if(e-48<10){return e-22}if(e-65<26){return e-65}if(e-97<26){return e-97}return u}function I(e,t){return e+22+75*(e<26)-((t!=0)<<5)}function T(e,t,r){var n=0;e=r?S(e/p):e>>1;e+=S(e/t);for(;e>_*l>>1;n+=u){e=S(e/_)}return S(n+(_+1)*e/(e+h))}function C(e){var t=[],r=e.length,n,i=0,s=v,a=d,o,h,p,g,b,y,w,_,E;o=e.lastIndexOf(m);if(o<0){o=0}for(h=0;h=128){O("not-basic")}t.push(e.charCodeAt(h))}for(p=o>0?o+1:0;p=r){O("invalid-input")}w=A(e.charCodeAt(p++));if(w>=u||w>S((f-i)/b)){O("overflow")}i+=w*b;_=y<=a?c:y>=a+l?l:y-a;if(w<_){break}E=u-_;if(b>S(f/E)){O("overflow")}b*=E}n=t.length+1;a=T(i-g,n,g==0);if(S(i/n)>f-s){O("overflow")}s+=S(i/n);i%=n;t.splice(i++,0,s)}return L(t)}function M(e){var t,r,n,i,s,a,o,h,p,g,b,y=[],w,_,x,j;e=R(e);w=e.length;t=v;r=0;s=d;for(a=0;a=t&&bS((f-r)/_)){O("overflow")}r+=(o-t)*_;t=o;for(a=0;af){O("overflow")}if(b==t){for(h=r,p=u;;p+=u){g=p<=s?c:p>=s+l?l:p-s;if(h0&&u>f){u=f}for(var c=0;c=0){p=l.substr(0,h);d=l.substr(h+1)}else{p=l;d=""}v=decodeURIComponent(p);m=decodeURIComponent(d);if(!n(a,v)){a[v]=m}else if(i(a[v])){a[v].push(m)}else{a[v]=[a[v],m]}}return a};var i=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"}},{}],67:[function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,o){t=t||"&";r=r||"=";if(e===null){e=undefined}if(typeof e==="object"){return s(a(e),function(a){var o=encodeURIComponent(n(a))+r;if(i(e[a])){return s(e[a],function(e){return o+encodeURIComponent(n(e))}).join(t)}else{return o+encodeURIComponent(n(e[a]))}}).join(t)}if(!o)return"";return encodeURIComponent(n(o))+r+encodeURIComponent(n(e))};var i=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};function s(e,t){if(e.map)return e.map(t);var r=[];for(var n=0;n0){if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var a=new Error("stream.unshift() after end event");e.emit("error",a)}else{if(t.decoder&&!i&&!n)r=t.decoder.write(r);if(!i)t.reading=false;if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(i)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)w(e)}S(e,t)}}else if(!i){t.reading=false}return d(t)}function d(e){return!e.ended&&(e.needReadable||e.length=v){e=v}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function g(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(e===null||isNaN(e)){if(t.flowing&&t.buffer.length)return t.buffer[0].length;else return t.length}if(e<=0)return 0;if(e>t.highWaterMark)t.highWaterMark=m(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else{return t.length}}return e}h.prototype.read=function(e){u("read",e);var t=this._readableState;var r=e;if(typeof e!=="number"||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){u("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)A(this);else w(this);return null}e=g(e,t);if(e===0&&t.ended){if(t.length===0)A(this);return null}var n=t.needReadable;u("need readable",n);if(t.length===0||t.length-e0)i=L(e,t);else i=null;if(i===null){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(r!==e&&t.ended&&t.length===0)A(this);if(i!==null)this.emit("data",i);return i};function b(e,t){var r=null;if(!s.isBuffer(t)&&typeof t!=="string"&&t!==null&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function y(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;w(e)}function w(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){u("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)n(_,e);else _(e)}}function _(e){u("emit readable");e.emit("readable");R(e)}function S(e,t){if(!t.readingMore){t.readingMore=true;n(E,e,t)}}function E(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(i)o=r.join("");else o=s.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;n(I,t,e)}}function I(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function T(e,t){for(var r=0,n=e.length;r-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e};function p(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=new i(t,r)}return t}function d(e,t,r,n,s){r=p(t,r,n);if(i.isBuffer(r))n="buffer";var a=t.objectMode?1:r.length;t.length+=a;var o=t.length0&&this._separator){this.push(this._separator)}};s.prototype._pushTail=function(){if(this._tail){this.push(this._tail)}};function a(e){var t=new s(e);return t}a.SandwichStream=s;t.exports=a},{stream:81}],81:[function(e,t,r){t.exports=s;var n=e("events").EventEmitter;var i=e("inherits");i(s,n);s.Readable=e("readable-stream/readable.js");s.Writable=e("readable-stream/writable.js");s.Duplex=e("readable-stream/duplex.js");s.Transform=e("readable-stream/transform.js");s.PassThrough=e("readable-stream/passthrough.js");s.Stream=s;function s(){n.call(this)}s.prototype.pipe=function(e,t){var r=this;function i(t){if(e.writable){if(false===e.write(t)&&r.pause){r.pause()}}}r.on("data",i);function s(){if(r.readable&&r.resume){r.resume()}}e.on("drain",s);if(!e._isStdio&&(!t||t.end!==false)){r.on("end",o);r.on("close",f)}var a=false;function o(){if(a)return;a=true;e.end()}function f(){if(a)return;a=true;if(typeof e.destroy==="function")e.destroy()}function u(e){c();if(n.listenerCount(this,"error")===0){throw e}}r.on("error",u);e.on("error",u);function c(){r.removeListener("data",i);e.removeListener("drain",s);r.removeListener("end",o);r.removeListener("close",f);r.removeListener("error",u);e.removeListener("error",u);r.removeListener("end",c);r.removeListener("close",c);e.removeListener("close",c)}r.on("end",c);r.on("close",c);e.on("close",c);e.emit("pipe",r);return e}},{events:14,inherits:18,"readable-stream/duplex.js":69,"readable-stream/passthrough.js":75,"readable-stream/readable.js":76,"readable-stream/transform.js":77,"readable-stream/writable.js":78}],82:[function(e,t,r){var n=e("./lib/request");var i=e("xtend");var s=e("builtin-status-codes");var a=e("url");var o=r;o.request=function(e,t){if(typeof e==="string")e=a.parse(e);else e=i(e);var r=e.protocol||"";var s=e.hostname||e.host;var o=e.port;var f=e.path||"/";if(s&&s.indexOf(":")!==-1)s="["+s+"]";e.url=(s?r+"//"+s:"")+(o?":"+o:"")+f;e.method=(e.method||"GET").toUpperCase();e.headers=e.headers||{};var u=new n(e);if(t)u.on("response",t);return u};o.get=function f(e,t){var r=o.request(e,t);r.end();return r};o.Agent=function(){};o.Agent.defaultMaxSockets=4;o.STATUS_CODES=s;o.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]},{"./lib/request":84,"builtin-status-codes":7,url:87,xtend:104}],83:[function(e,t,r){(function(e){r.fetch=o(e.fetch)&&o(e.ReadableByteStream);r.blobConstructor=false;try{new Blob([new ArrayBuffer(1)]);r.blobConstructor=true}catch(t){}var n=new e.XMLHttpRequest;n.open("GET",e.location.host?"/":"https://example.com");function i(e){try{n.responseType=e;return n.responseType===e}catch(t){}return false}var s=typeof e.ArrayBuffer!=="undefined";var a=s&&o(e.ArrayBuffer.prototype.slice);r.arraybuffer=s&&i("arraybuffer");r.msstream=!r.fetch&&a&&i("ms-stream");r.mozchunkedarraybuffer=!r.fetch&&s&&i("moz-chunked-arraybuffer");r.overrideMimeType=o(n.overrideMimeType);r.vbArray=o(e.VBArray);function o(e){return typeof e==="function"}n=null}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],84:[function(e,t,r){(function(r,n,i){var s=e("./capability");var a=e("foreach");var o=e("indexof");var f=e("inherits");var u=e("object-keys");var c=e("./response");var l=e("stream");var h=c.IncomingMessage;var p=c.readyStates;function d(e){if(s.fetch){return"fetch"}else if(s.mozchunkedarraybuffer){return"moz-chunked-arraybuffer"}else if(s.msstream){return"ms-stream"}else if(s.arraybuffer&&e){return"arraybuffer"}else if(s.vbArray&&e){return"text:vbarray"}else{return"text"}}var v=t.exports=function(e){var t=this;l.Writable.call(t);t._opts=e;t._body=[];t._headers={};if(e.auth)t.setHeader("Authorization","Basic "+new i(e.auth).toString("base64"));a(u(e.headers),function(r){t.setHeader(r,e.headers[r])});var r;if(e.mode==="prefer-streaming"){r=false}else if(e.mode==="allow-wrong-content-type"){r=!s.overrideMimeType}else if(!e.mode||e.mode==="default"||e.mode==="prefer-fast"){r=true}else{throw new Error("Invalid value for opts.mode")}t._mode=d(r);t.on("finish",function(){t._onFinish()})};f(v,l.Writable);v.prototype.setHeader=function(e,t){var r=this;var n=e.toLowerCase();if(o(g,n)!==-1)return;r._headers[n]={name:e,value:t}};v.prototype.getHeader=function(e){var t=this;return t._headers[e.toLowerCase()].value};v.prototype.removeHeader=function(e){var t=this;delete t._headers[e.toLowerCase()]};v.prototype._onFinish=function(){var e=this;if(e._destroyed)return;var t=e._opts;var o=e._headers;var f;if(t.method==="POST"||t.method==="PUT"){if(s.blobConstructor){f=new n.Blob(e._body.map(function(e){return e.toArrayBuffer()}),{type:(o["content-type"]||{}).value||""})}else{f=i.concat(e._body).toString()}}if(e._mode==="fetch"){var c=u(o).map(function(e){return[o[e].name,o[e].value]});n.fetch(e._opts.url,{method:e._opts.method,headers:c,body:f,mode:"cors",credentials:t.withCredentials?"include":"same-origin"}).then(function(t){e._fetchResponse=t;e._connect()}).then(undefined,function(t){e.emit("error",t)})}else{var l=e._xhr=new n.XMLHttpRequest;try{l.open(e._opts.method,e._opts.url,true)}catch(h){r.nextTick(function(){e.emit("error",h)});return}if("responseType"in l)l.responseType=e._mode.split(":")[0];if("withCredentials"in l)l.withCredentials=!!t.withCredentials;if(e._mode==="text"&&"overrideMimeType"in l)l.overrideMimeType("text/plain; charset=x-user-defined");a(u(o),function(e){l.setRequestHeader(o[e].name,o[e].value)});e._response=null;l.onreadystatechange=function(){switch(l.readyState){case p.LOADING:case p.DONE:e._onXHRProgress();break}};if(e._mode==="moz-chunked-arraybuffer"){l.onprogress=function(){e._onXHRProgress()}}l.onerror=function(){if(e._destroyed)return;e.emit("error",new Error("XHR error"))};try{l.send(f)}catch(h){r.nextTick(function(){e.emit("error",h)});return}}};function m(e){try{return e.status!==null}catch(t){return false}}v.prototype._onXHRProgress=function(){var e=this;if(!m(e._xhr)||e._destroyed)return;if(!e._response)e._connect();e._response._onXHRProgress()};v.prototype._connect=function(){var e=this;if(e._destroyed)return;e._response=new h(e._xhr,e._fetchResponse,e._mode);e.emit("response",e._response)};v.prototype._write=function(e,t,r){var n=this;n._body.push(e);r()};v.prototype.abort=v.prototype.destroy=function(){var e=this;e._destroyed=true;if(e._response)e._response._destroyed=true;if(e._xhr)e._xhr.abort()};v.prototype.end=function(e,t,r){var n=this;if(typeof e==="function"){r=e;e=undefined}l.Writable.prototype.end.call(n,e,t,r)};v.prototype.flushHeaders=function(){};v.prototype.setTimeout=function(){};v.prototype.setNoDelay=function(){};v.prototype.setSocketKeepAlive=function(){};var g=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","user-agent","via"]}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{"./capability":83,"./response":85,_process:64,buffer:6,foreach:15,indexof:17,inherits:18,"object-keys":58,stream:81}],85:[function(e,t,r){(function(t,n,i){var s=e("./capability");var a=e("foreach");var o=e("inherits");var f=e("stream");var u=r.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4};var c=r.IncomingMessage=function(e,r,n){var o=this;f.Readable.call(o);o._mode=n;o.headers={};o.rawHeaders=[];o.trailers={};o.rawTrailers=[];o.on("end",function(){t.nextTick(function(){o.emit("close")})});if(n==="fetch"){o._fetchResponse=r;o.statusCode=r.status;o.statusMessage=r.statusText;for(var u,c,l=r.headers[Symbol.iterator]();u=(c=l.next()).value,!c.done;){o.headers[u[0].toLowerCase()]=u[1];o.rawHeaders.push(u[0],u[1])}var h=r.body.getReader();function p(){h.read().then(function(e){if(o._destroyed)return;if(e.done){o.push(null);return}o.push(new i(e.value));p()})}p()}else{o._xhr=e;o._pos=0;o.statusCode=e.status;o.statusMessage=e.statusText;var d=e.getAllResponseHeaders().split(/\r?\n/);a(d,function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var r=t[1].toLowerCase();if(o.headers[r]!==undefined)o.headers[r]+=", "+t[2];else o.headers[r]=t[2];o.rawHeaders.push(t[1],t[2])}});o._charset="x-user-defined";if(!s.overrideMimeType){var v=o.rawHeaders["mime-type"];if(v){var m=v.match(/;\s*charset=([^;])(;|$)/);if(m){o._charset=m[1].toLowerCase()}}if(!o._charset)o._charset="utf-8"}}};o(c,f.Readable);c.prototype._read=function(){};c.prototype._onXHRProgress=function(){var e=this;var t=e._xhr;var r=null;switch(e._mode){case"text:vbarray":if(t.readyState!==u.DONE)break;try{r=new n.VBArray(t.responseBody).toArray()}catch(s){}if(r!==null){e.push(new i(r));break}case"text":try{r=t.responseText}catch(s){e._mode="text:vbarray";break}if(r.length>e._pos){var a=r.substr(e._pos);if(e._charset==="x-user-defined"){var o=new i(a.length);for(var f=0;fe._pos){e.push(new i(new Uint8Array(c.result.slice(e._pos))));e._pos=c.result.byteLength}};c.onload=function(){e.push(null)};c.readAsArrayBuffer(r);break}if(e._xhr.readyState===u.DONE&&e._mode!=="ms-stream"){e.push(null)}}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},e("buffer").Buffer)},{"./capability":83,_process:64,buffer:6,foreach:15,inherits:18,stream:81}],86:[function(e,t,r){var n=e("buffer").Buffer;var i=n.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function s(e){if(e&&!i(e)){throw new Error("Unknown encoding: "+e)}}var a=r.StringDecoder=function(e){this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,"");s(e);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=f;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=u;break;default:this.write=o;return}this.charBuffer=new n(6);this.charReceived=0;this.charLength=0};a.prototype.write=function(e){var t="";while(this.charLength){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;e.copy(this.charBuffer,this.charReceived,0,r);this.charReceived+=r;if(this.charReceived=55296&&n<=56319){this.charLength+=this.surrogateSize;t="";continue}this.charReceived=this.charLength=0;if(e.length===0){return t}break}this.detectIncompleteChar(e);var i=e.length;if(this.charLength){e.copy(this.charBuffer,0,e.length-this.charReceived,i);i-=this.charReceived}t+=e.toString(this.encoding,0,i);var i=t.length-1;var n=t.charCodeAt(i);if(n>=55296&&n<=56319){var s=this.surrogateSize;this.charLength+=s;this.charReceived+=s;this.charBuffer.copy(this.charBuffer,s,0,s);e.copy(this.charBuffer,0,0,s);return t.substring(0,i)}return t};a.prototype.detectIncompleteChar=function(e){var t=e.length>=3?3:e.length;for(;t>0;t--){var r=e[e.length-t];if(t==1&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t};a.prototype.end=function(e){var t="";if(e&&e.length)t=this.write(e);if(this.charReceived){var r=this.charReceived;var n=this.charBuffer;var i=this.encoding;t+=n.slice(0,r).toString(i)}return t};function o(e){return e.toString(this.encoding)}function f(e){this.charReceived=e.length%2;this.charLength=this.charReceived?2:0}function u(e){this.charReceived=e.length%3;this.charLength=this.charReceived?3:0}},{buffer:6}],87:[function(e,t,r){var n=e("punycode");r.parse=y;r.resolve=_;r.resolveObject=S;r.format=w;r.Url=i;function i(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null}var s=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,o=["<",">",'"',"`"," ","\r","\n"," "],f=["{","}","|","\\","^","`"].concat(o),u=["'"].concat(f),c=["%","/","?",";","#"].concat(u),l=["/","?","#"],h=255,p=/^[a-z0-9A-Z_-]{0,63}$/,d=/^([a-z0-9A-Z_-]{0,63})(.*)$/,v={javascript:true,"javascript:":true},m={javascript:true,"javascript:":true},g={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},b=e("querystring");function y(e,t,r){if(e&&x(e)&&e instanceof i)return e;var n=new i;n.parse(e,t,r);return n}i.prototype.parse=function(e,t,r){if(!E(e)){throw new TypeError("Parameter 'url' must be a string, not "+typeof e)}var i=e;i=i.trim();var a=s.exec(i);if(a){a=a[0];var o=a.toLowerCase();this.protocol=o;i=i.substr(a.length)}if(r||a||i.match(/^\/\/[^@\/]+@[^@\/]+/)){var f=i.substr(0,2)==="//";if(f&&!(a&&m[a])){i=i.substr(2);this.slashes=true}}if(!m[a]&&(f||a&&!g[a])){var y=-1;for(var w=0;w127){L+="x"}else{L+=R[A]}}if(!L.match(p)){var T=j.slice(0,w);var C=j.slice(w+1);var M=R.match(d);if(M){T.push(M[1]);C.unshift(M[2])}if(C.length){i="/"+C.join(".")+i}this.hostname=T.join(".");break}}}}if(this.hostname.length>h){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!O){var N=this.hostname.split(".");var P=[];for(var w=0;w0?r.host.split("@"):false;if(p){r.auth=p.shift();r.host=r.hostname=p.shift()}}r.search=e.search;r.query=e.query;if(!O(r.pathname)||!O(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.href=r.format();return r}if(!l.length){r.pathname=null;if(r.search){r.path="/"+r.search}else{r.path=null}r.href=r.format();return r}var d=l.slice(-1)[0];var v=(r.host||e.host)&&(d==="."||d==="..")||d==="";var b=0;for(var y=l.length;y>=0;y--){d=l[y];if(d=="."){l.splice(y,1)}else if(d===".."){l.splice(y,1);b++}else if(b){l.splice(y,1);b--}}if(!u&&!c){for(;b--;b){l.unshift("..")}}if(u&&l[0]!==""&&(!l[0]||l[0].charAt(0)!=="/")){l.unshift("")}if(v&&l.join("/").substr(-1)!=="/"){l.push("")}var w=l[0]===""||l[0]&&l[0].charAt(0)==="/";if(h){r.hostname=r.host=w?"":l.length?l.shift():"";var p=r.host&&r.host.indexOf("@")>0?r.host.split("@"):false;if(p){r.auth=p.shift();r.host=r.hostname=p.shift()}}u=u||r.host&&l.length;if(u&&!w){l.unshift("")}if(!l.length){r.pathname=null;r.path=null}else{r.pathname=l.join("/")}if(!O(r.pathname)||!O(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.auth=e.auth||r.auth;r.slashes=r.slashes||e.slashes;r.href=r.format();return r};i.prototype.parseHost=function(){var e=this.host;var t=a.exec(e);if(t){t=t[0];if(t!==":"){this.port=t.substr(1)}e=e.substr(0,e.length-t.length)}if(e)this.hostname=e};function E(e){return typeof e==="string"}function x(e){return typeof e==="object"&&e!==null}function O(e){return e===null}function j(e){return e==null}},{punycode:65,querystring:68}],88:[function(e,t,r){(function(e){t.exports=r;function r(e,t){if(n("noDeprecation")){return e}var r=false;function i(){if(!r){if(n("throwDeprecation")){throw new Error(t)}else if(n("traceDeprecation")){console.trace(t)}else{console.warn(t)}r=true}return e.apply(this,arguments)}return i}function n(t){if(!e.localStorage)return false;var r=e.localStorage[t];if(null==r)return false;return String(r).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],89:[function(e,t,r){t.exports=function n(e){return e&&typeof e==="object"&&typeof e.copy==="function"&&typeof e.fill==="function"&&typeof e.readUInt8==="function"}},{}],90:[function(e,t,r){(function(t,n){var i=/%[sdj%]/g;r.format=function(e){if(!S(e)){var t=[];for(var r=0;r=s)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return e}});for(var f=n[r];r=3)n.depth=arguments[2];if(arguments.length>=4)n.colors=arguments[3];if(b(t)){n.showHidden=t}else if(t){r._extend(n,t)}if(x(n.showHidden))n.showHidden=false;if(x(n.depth))n.depth=2;if(x(n.colors))n.colors=false;if(x(n.customInspect))n.customInspect=true;if(n.colors)n.stylize=f;return l(n,e,n.depth)}r.inspect=o;o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};o.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function f(e,t){var r=o.styles[t];if(r){return"["+o.colors[r][0]+"m"+e+"["+o.colors[r][1]+"m"}else{return e}}function u(e,t){return e}function c(e){var t={};e.forEach(function(e,r){t[e]=true});return t}function l(e,t,n){if(e.customInspect&&t&&L(t.inspect)&&t.inspect!==r.inspect&&!(t.constructor&&t.constructor.prototype===t)){var i=t.inspect(n,e);if(!S(i)){i=l(e,i,n)}return i}var s=h(e,t);if(s){return s}var a=Object.keys(t);var o=c(a);if(e.showHidden){a=Object.getOwnPropertyNames(t)}if(R(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0)){return p(t)}if(a.length===0){if(L(t)){var f=t.name?": "+t.name:"";return e.stylize("[Function"+f+"]","special")}if(O(t)){return e.stylize(RegExp.prototype.toString.call(t),"regexp")}if(k(t)){return e.stylize(Date.prototype.toString.call(t),"date")}if(R(t)){return p(t)}}var u="",b=false,y=["{","}"];if(g(t)){b=true;y=["[","]"]}if(L(t)){var w=t.name?": "+t.name:"";u=" [Function"+w+"]"}if(O(t)){u=" "+RegExp.prototype.toString.call(t)}if(k(t)){u=" "+Date.prototype.toUTCString.call(t)}if(R(t)){u=" "+p(t)}if(a.length===0&&(!b||t.length==0)){return y[0]+u+y[1]}if(n<0){if(O(t)){return e.stylize(RegExp.prototype.toString.call(t),"regexp")}else{return e.stylize("[Object]","special")}}e.seen.push(t);var _;if(b){_=d(e,t,n,o,a)}else{_=a.map(function(r){return v(e,t,n,o,r,b)})}e.seen.pop();return m(_,u,y)}function h(e,t){if(x(t))return e.stylize("undefined","undefined");if(S(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(_(t))return e.stylize(""+t,"number");if(b(t))return e.stylize(""+t,"boolean");if(y(t))return e.stylize("null","null")}function p(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,r,n,i){var s=[];for(var a=0,o=t.length;a-1){if(s){o=o.split("\n").map(function(e){return" "+e}).join("\n").substr(2)}else{o="\n"+o.split("\n").map(function(e){return" "+e}).join("\n")}}}else{o=e.stylize("[Circular]","special")}}if(x(a)){if(s&&i.match(/^\d+$/)){return o}a=JSON.stringify(""+i);if(a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){a=a.substr(1,a.length-2);a=e.stylize(a,"name")}else{a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");a=e.stylize(a,"string")}}return a+": "+o}function m(e,t,r){var n=0;var i=e.reduce(function(e,t){n++;if(t.indexOf("\n")>=0)n++;return e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(i>60){return r[0]+(t===""?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1]}return r[0]+t+" "+e.join(", ")+" "+r[1]}function g(e){return Array.isArray(e)}r.isArray=g;function b(e){return typeof e==="boolean"}r.isBoolean=b;function y(e){return e===null}r.isNull=y;function w(e){return e==null}r.isNullOrUndefined=w;function _(e){return typeof e==="number"}r.isNumber=_;function S(e){return typeof e==="string"}r.isString=S;function E(e){return typeof e==="symbol"}r.isSymbol=E;function x(e){return e===void 0}r.isUndefined=x;function O(e){return j(e)&&I(e)==="[object RegExp]"}r.isRegExp=O;function j(e){return typeof e==="object"&&e!==null}r.isObject=j;function k(e){return j(e)&&I(e)==="[object Date]"}r.isDate=k;function R(e){return j(e)&&(I(e)==="[object Error]"||e instanceof Error)}r.isError=R;function L(e){return typeof e==="function"}r.isFunction=L;function A(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}r.isPrimitive=A;r.isBuffer=e("./support/isBuffer");function I(e){return Object.prototype.toString.call(e)}function T(e){return e<10?"0"+e.toString(10):e.toString(10)}var C=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function M(){var e=new Date;var t=[T(e.getHours()),T(e.getMinutes()),T(e.getSeconds())].join(":");return[e.getDate(),C[e.getMonth()],t].join(" ")}r.log=function(){console.log("%s - %s",M(),r.format.apply(r,arguments))};r.inherits=e("inherits");r._extend=function(e,t){if(!t||!j(t))return e;var r=Object.keys(t);var n=r.length;while(n--){e[r[n]]=t[r[n]]}return e};function N(e,t){return Object.prototype.hasOwnProperty.call(e,t)}}).call(this,e("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":89,_process:64,inherits:18}],91:[function(e,t,r){var n=e("path");t.exports=i;function i(e,t){var r={paths:[],named:{},unnamed:[]};function i(e){if(!r.named[e]){r.named[e]={children:[]}}return r.named[e]}e.on("data",function(s){if(t===null){e.on("data",function(){});return}if(s.path){var a=i(s.path);a.file=s;var o=i(n.dirname(s.path));if(a!==o)o.children.push(a);r.paths.push(s.path)}else{r.unnamed.push({file:s,children:[]})}});e.on("error",function(e){t&&t(e);t=null});e.on("end",function(){t&&t(null,r);t=null})}},{path:62}],92:[function(e,t,r){var n=t.exports={};n.randomString=i;n.cleanPath=s;function i(){return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function s(e,t){if(!e)return"";if(!t)return e;if(t[t.length-1]!="/"){t+="/"}e=e.replace(t,"");e=e.replace(/[\/]+/g,"/");return e}},{}],93:[function(e,t,r){var n=e("./mp2v_flat");var i=e("./mp2v_tree");var s=t.exports=i;s.flat=n;s.tree=i},{"./mp2v_flat":94,"./mp2v_tree":95}],94:[function(e,t,r){var n=e("multipart-stream");var i=e("duplexify");var s=e("stream");var a=e("./common");l=a.randomString;t.exports=o;function o(e){e=e||{};e.boundary=e.boundary||l();var t=new s.Writable({objectMode:true});var r=new s.PassThrough({objectMode:true});var a=new n(e.boundary);t._write=function(e,t,r){f(a,e,r)};t.on("finish",function(){a.pipe(r)});var o=i.obj(t,r);o.boundary=e.boundary;return o}function f(e,t,r){var n=t.contents;if(n===null)n=u();e.addPart({body:t.contents,headers:c(t)});r(null)}function u(){var e=new s.PassThrough({objectMode:true});e.write(null);return e}function c(e){var t=a.cleanPath(e.path,e.base);var r={};r["Content-Disposition"]='file; filename="'+t+'"';if(e.isDirectory()){r["Content-Type"]="text/directory"}else{r["Content-Type"]="application/octet-stream"}return r}function l(){return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}},{"./common":92,duplexify:12,"multipart-stream":57,stream:81}],95:[function(e,t,r){var n=e("multipart-stream");var i=e("duplexify");var s=e("stream");var a=e("path");var o=e("./collect");var f=e("./common");randomString=f.randomString;t.exports=u;function u(e){e=e||{};e.boundary=e.boundary||randomString();var t=new s.PassThrough({objectMode:true});var r=new s.PassThrough({objectMode:true});var n=i.obj(r,t);n.boundary=e.boundary;o(r,function(r,i){if(r){t.emit("error",r);return}try{var s=c(e.boundary,i);n.multipartHdr="Content-Type: multipart/mixed; boundary="+s.boundary;if(e.writeHeader){t.write(n.multipartHdr+"\r\n");t.write("\r\n")}s.pipe(t)}catch(a){t.emit("error",a)}});return n}function c(e,t){var r=[];t.paths.sort();for(var i=0;i0){throw new Error("non-directory has children. lib error")}return t.file.contents}function d(e,t){t.boundary=randomString();if(!t.children||t.children.length<1){return l("--"+t.boundary+"--\r\n")}var r=new n(t.boundary);for(var i=0;i"};p.isVinyl=function(e){return e&&e._isVinyl===true};Object.defineProperty(p.prototype,"contents",{get:function(){return this._contents},set:function(e){if(!o(e)&&!f(e)&&!u(e)){throw new Error("File.contents can only be a Buffer, a Stream, or null.")}this._contents=e}});Object.defineProperty(p.prototype,"relative",{get:function(){if(!this.base)throw new Error("No base specified! Can not get relative.");if(!this.path)throw new Error("No path specified! Can not get relative.");return n.relative(this.base,this.path)},set:function(){throw new Error("File.relative is generated from the base and path attributes. Do not modify it.")}});Object.defineProperty(p.prototype,"dirname",{get:function(){if(!this.path)throw new Error("No path specified! Can not get dirname.");return n.dirname(this.path)},set:function(e){if(!this.path)throw new Error("No path specified! Can not set dirname.");this.path=n.join(e,n.basename(this.path))}});Object.defineProperty(p.prototype,"basename",{get:function(){if(!this.path)throw new Error("No path specified! Can not get basename.");return n.basename(this.path)},set:function(e){if(!this.path)throw new Error("No path specified! Can not set basename.");this.path=n.join(n.dirname(this.path),e)}});Object.defineProperty(p.prototype,"extname",{get:function(){if(!this.path)throw new Error("No path specified! Can not get extname.");return n.extname(this.path)},set:function(e){if(!this.path)throw new Error("No path specified! Can not set extname.");this.path=h(this.path,e)}});Object.defineProperty(p.prototype,"path",{get:function(){return this.history[this.history.length-1]},set:function(e){if(typeof e!=="string")throw new Error("path should be string");if(e&&e!==this.path){this.history.push(e)}}});t.exports=p}).call(this,e("_process"))},{"./lib/cloneBuffer":97,"./lib/inspectStream":98,"./lib/isBuffer":99,"./lib/isNull":100,"./lib/isStream":101,_process:64,clone:9,"clone-stats":8,path:62,"replace-ext":79,stream:81}],97:[function(e,t,r){var n=e("buffer").Buffer;t.exports=function(e){var t=new n(e.length);e.copy(t);return t}},{buffer:6}],98:[function(e,t,r){var n=e("./isStream");t.exports=function(e){if(!n(e))return;var t=e.constructor.name;if(t==="Stream")t="";return"<"+t+"Stream>"}},{"./isStream":101}],99:[function(e,t,r){t.exports=e("buffer").Buffer.isBuffer},{buffer:6}],100:[function(e,t,r){t.exports=function(e){return e===null}},{}],101:[function(e,t,r){var n=e("stream").Stream;t.exports=function(e){return!!e&&e instanceof n}},{stream:81}],102:[function(require,module,exports){var indexOf=require("indexof");var Object_keys=function(e){if(Object.keys)return Object.keys(e);else{var t=[];for(var r in e)t.push(r);return t}};var forEach=function(e,t){if(e.forEach)return e.forEach(t);else for(var r=0;r dist/ipfsapi.min.js"},standard:{ignore:["dist/*"]},"pre-commit":["lint"],keywords:["ipfs"],author:"Matt Bell ",contributors:["Travis Person ","Jeromy Jonson "],license:"MIT",bugs:{url:"https://github.com/ipfs/node-ipfs-api/issues"},homepage:"https://github.com/ipfs/node-ipfs-api"}},{}],106:[function(e,t,r){var n=e("../package.json");r=t.exports={"api-path":"/api/v0/","user-agent":"/node-"+n.name+"/"+n.version+"/",host:"localhost",port:"5001"}},{"../package.json":105}],107:[function(e,t,r){(function(n){var i=e("vinyl");var s=e("vinyl-fs-browser");var a=e("vinyl-multipart-stream");var o=e("stream");var f=e("merge-stream");r=t.exports=u;function u(e,t){if(!e)return null;if(!Array.isArray(e))e=[e];var r=new f;var n=new o.PassThrough({objectMode:true});r.add(n);for(var i=0;i=400||!e.statusCode){if(!t)t=new Error;return u(t,null)}return u(null,t)});e.on("error",function(e){return u(e,null)})});d.on("error",function(e){return u(e,null)});if(l){l.pipe(d)}else{d.end()}return d}},{"./config":106,"./get-files-stream":107,http:82,querystring:68}],110:[function(e,t,r){"use strict";t.exports={src:e("./lib/src"),dest:e("./lib/dest"),symlink:e("./lib/symlink")}},{"./lib/dest":111,"./lib/src":124,"./lib/symlink":126}],111:[function(e,t,r){(function(r){"use strict";var n=e("through2");var i=r.browser?null:e("gulp-sourcemaps");var s=e("duplexify");var a=e("../prepareWrite");var o=e("./writeContents");function f(e,t){if(!t){t={}}function r(r,n,i){a(e,r,t,function(e,t){if(e){return i(e)}o(t,r,i)})}var f=n.obj(r);if(!t.sourcemaps){return f}var u=i.write(t.sourcemaps.path,t.sourcemaps);var c=s.obj(u,f);u.pipe(f);return c}t.exports=f}).call(this,e("_process"))},{"../prepareWrite":118,"./writeContents":112,_process:64,duplexify:127,"gulp-sourcemaps":188,through2:248}],112:[function(e,t,r){"use strict";var n=e("./writeDir");var i=e("./writeStream");var s=e("./writeBuffer");var a=e("./writeSymbolicLink");function o(e,t,r){if(t.isDirectory()){return n(e,t,f)}if(t.isStream()){return i(e,t,f)}if(t.symlink){return a(e,t,f)}if(t.isBuffer()){return s(e,t,f)}if(t.isNull()){return o()}function o(e){r(e,t)}function f(r){if(u(r)){return o(r)}if(!t.stat||typeof t.stat.mode!=="number"||t.symlink){return o()}fs.stat(e,function(r,n){if(r){return o(r)}var i=n.mode&parseInt("0777",8);var s=t.stat.mode&parseInt("0777",8);if(i===s){return o()}fs.chmod(e,s,o)})}function u(e){if(!e){return false}else if(e.code==="EEXIST"&&t.flag==="wx"){return false}return true}}t.exports=o},{"./writeBuffer":113,"./writeDir":114,"./writeStream":115,"./writeSymbolicLink":116}],113:[function(e,t,r){(function(r){"use strict";var n=r.browser?e("fs"):e("graceful-fs");function i(e,t,r){var i={mode:t.stat.mode,flag:t.flag};n.writeFile(e,t.contents,i,r)}t.exports=i}).call(this,e("_process"))},{_process:64,fs:4,"graceful-fs":185}],114:[function(e,t,r){"use strict";var n=e("mkdirp");function i(e,t,r){n(e,t.stat.mode,r)}t.exports=i},{mkdirp:230}],115:[function(e,t,r){(function(r){"use strict";var n=e("../../src/getContents/streamFile");var i=r.browser?e("fs"):e("graceful-fs");function s(e,t,r){var s={mode:t.stat.mode,flag:t.flag};var a=i.createWriteStream(e,s);t.contents.once("error",f);a.once("error",f);a.once("finish",o);t.contents.pipe(a);function o(){n(t,{},f)}function f(e){t.contents.removeListener("error",r);a.removeListener("error",r);a.removeListener("finish",o);r(e)}}t.exports=s}).call(this,e("_process"))},{"../../src/getContents/streamFile":123,_process:64,fs:4,"graceful-fs":185}],116:[function(e,t,r){(function(r){"use strict";var n=r.browser?e("fs"):e("graceful-fs");function i(e,t,r){n.symlink(t.symlink,e,function(e){if(e&&e.code!=="EEXIST"){return r(e)}r(null,t)})}t.exports=i}).call(this,e("_process"))},{_process:64,fs:4,"graceful-fs":185}],117:[function(e,t,r){"use strict";var n=e("through2-filter");t.exports=function(e){var t=typeof e==="number"||e instanceof Number||e instanceof Date;if(!t){throw new Error("expected since option to be a date or a number")}return n.obj(function(t){return t.stat&&t.stat.mtime>e})}},{"through2-filter":234}],118:[function(e,t,r){(function(r){"use strict";var n=e("object-assign");var i=e("path");var s=e("mkdirp");var a=r.browser?e("fs"):e("graceful-fs");function o(e,t){if(typeof e!=="boolean"&&typeof e!=="function"){return null}return typeof e==="boolean"?e:e(t)}function f(e,t){if(typeof e!=="string"&&typeof e!=="function"){return null}return typeof e==="string"?e:e(t)}function u(e,t,u,c){var l=n({cwd:r.cwd(),mode:t.stat?t.stat.mode:null,dirMode:null,overwrite:true},u);var h=o(l.overwrite,t);l.flag=h?"w":"wx";var p=i.resolve(l.cwd);var d=f(e,t);if(!d){throw new Error("Invalid output folder")}var v=l.base?f(l.base,t):i.resolve(p,d);if(!v){throw new Error("Invalid base option")}var m=i.resolve(v,t.relative);var g=i.dirname(m);t.stat=t.stat||new a.Stats;t.stat.mode=l.mode;t.flag=l.flag;t.cwd=p;t.base=v;t.path=m;s(g,l.dirMode,function(e){if(e){return c(e)}c(null,m)})}t.exports=u}).call(this,e("_process"))},{_process:64,fs:4,"graceful-fs":185,mkdirp:230,"object-assign":231,path:62}],119:[function(e,t,r){(function(r){"use strict";var n=r.browser?e("fs"):e("graceful-fs");var i=e("strip-bom");function s(e,t,r){n.readFile(e.path,function(n,s){if(n){return r(n)}if(t.stripBOM){e.contents=i(s)}else{e.contents=s}r(null,e)})}t.exports=s}).call(this,e("_process"))},{_process:64,fs:4,"graceful-fs":185,"strip-bom":233}],120:[function(e,t,r){"use strict";var n=e("through2");var i=e("./readDir");var s=e("./readSymbolicLink");var a=e("./bufferFile");var o=e("./streamFile");function f(e){return n.obj(function(t,r,n){if(t.isDirectory()){return i(t,e,n)}if(t.stat&&t.stat.isSymbolicLink()){return s(t,e,n)}if(e.buffer!==false){return a(t,e,n)}return o(t,e,n)})}t.exports=f},{"./bufferFile":119,"./readDir":121,"./readSymbolicLink":122,"./streamFile":123,through2:248}],121:[function(e,t,r){"use strict";function n(e,t,r){r(null,e)}t.exports=n},{}],122:[function(e,t,r){(function(r){"use strict";var n=r.browser?e("fs"):e("graceful-fs");function i(e,t,r){n.readlink(e.path,function(t,n){if(t){return r(t)}e.symlink=n;return r(null,e)})}t.exports=i}).call(this,e("_process"))},{_process:64,fs:4,"graceful-fs":185}],123:[function(e,t,r){(function(r){"use strict";var n=r.browser?e("fs"):e("graceful-fs");var i=e("strip-bom-stream");function s(e,t,r){e.contents=n.createReadStream(e.path);if(t.stripBOM){e.contents=e.contents.pipe(i())}r(null,e)}t.exports=s}).call(this,e("_process"))},{_process:64,fs:4,"graceful-fs":185,"strip-bom-stream":232}],124:[function(e,t,r){(function(r){"use strict";var n=e("object-assign");var i=e("through2");var s=e("glob-stream");var a=e("vinyl");var o=e("duplexify");var f=e("merge-stream");var u=r.browser?null:e("gulp-sourcemaps");var c=e("../filterSince");var l=e("is-valid-glob");var h=e("./getContents");var p=e("./resolveSymlinks");function d(e,t,r){r(null,new a(e))}function v(e,t){var r=n({read:true,buffer:true,stripBOM:true,sourcemaps:false,passthrough:false,followSymlinks:true},t);var a;if(!l(e)){throw new Error("Invalid glob argument: "+e)}var v=s.create(e,r);var m=v.pipe(p(r)).pipe(i.obj(d));if(r.since!=null){m=m.pipe(c(r.since))}if(r.read!==false){m=m.pipe(h(r))}if(r.passthrough===true){a=i.obj();m=o.obj(a,f(m,a))}if(r.sourcemaps===true){m=m.pipe(u.init({loadMaps:true}))}v.on("error",m.emit.bind(m,"error"));return m}t.exports=v}).call(this,e("_process"))},{"../filterSince":117,"./getContents":120,"./resolveSymlinks":125,_process:64,duplexify:127,"glob-stream":144,"gulp-sourcemaps":188,"is-valid-glob":216,"merge-stream":217,"object-assign":231,through2:248,vinyl:249}],125:[function(e,t,r){(function(r){"use strict";var n=e("through2");var i=r.browser?e("fs"):e("graceful-fs");var s=e("path");function a(e){function t(r,n,a){i.lstat(r.path,function(o,f){if(o){return a(o)}r.stat=f;if(!f.isSymbolicLink()||!e.followSymlinks){return a(null,r)}i.realpath(r.path,function(e,i){if(e){return a(e)}r.base=s.dirname(i);r.path=i;t(r,n,a)})})}return n.obj(t)}t.exports=a}).call(this,e("_process"))},{_process:64,fs:4,"graceful-fs":185,path:62,through2:248}],126:[function(e,t,r){(function(r){"use strict";var n=e("through2");var i=r.browser?e("fs"):e("graceful-fs");var s=e("../prepareWrite");function a(e,t){function r(r,n,a){var o=r.path;var f=r.isDirectory()?"dir":"file";s(e,r,t,function(e,t){if(e){return a(e)}i.symlink(o,t,f,function(e){if(e&&e.code!=="EEXIST"){return a(e)}a(null,r)})})}var a=n.obj(r);a.resume();return a}t.exports=a}).call(this,e("_process"))},{"../prepareWrite":118,_process:64,fs:4,"graceful-fs":185,through2:248}],127:[function(e,t,r){arguments[4][12][0].apply(r,arguments)},{_process:64,buffer:6,dup:12,"end-of-stream":128,"readable-stream":142,util:90}],128:[function(e,t,r){arguments[4][13][0].apply(r,arguments)},{dup:13,once:130}],129:[function(e,t,r){arguments[4][103][0].apply(r,arguments)},{dup:103}],130:[function(e,t,r){arguments[4][60][0].apply(r,arguments)},{dup:60,wrappy:129}],131:[function(e,t,r){arguments[4][70][0].apply(r,arguments)},{"./_stream_readable":133,"./_stream_writable":135,"core-util-is":136,dup:70,inherits:137,"process-nextick-args":139}],132:[function(e,t,r){arguments[4][71][0].apply(r,arguments)},{"./_stream_transform":134,"core-util-is":136,dup:71,inherits:137}],133:[function(e,t,r){arguments[4][72][0].apply(r,arguments)},{"./_stream_duplex":131,_process:64,buffer:6,"core-util-is":136,dup:72,events:14,inherits:137,isarray:138,"process-nextick-args":139,"string_decoder/":140,util:3}],134:[function(e,t,r){arguments[4][73][0].apply(r,arguments)},{"./_stream_duplex":131,"core-util-is":136,dup:73,inherits:137}],135:[function(e,t,r){arguments[4][74][0].apply(r,arguments)},{"./_stream_duplex":131,buffer:6,"core-util-is":136,dup:74,events:14,inherits:137,"process-nextick-args":139,"util-deprecate":141}],136:[function(e,t,r){arguments[4][11][0].apply(r,arguments)},{"/media/d/projects/node-ipfs-api/node_modules/is-buffer/index.js":21,dup:11}],137:[function(e,t,r){arguments[4][18][0].apply(r,arguments)},{dup:18}],138:[function(e,t,r){arguments[4][22][0].apply(r,arguments)},{dup:22}],139:[function(e,t,r){arguments[4][63][0].apply(r,arguments)},{_process:64,dup:63}],140:[function(e,t,r){arguments[4][86][0].apply(r,arguments)},{buffer:6,dup:86}],141:[function(e,t,r){arguments[4][88][0].apply(r,arguments)},{dup:88}],142:[function(e,t,r){arguments[4][76][0].apply(r,arguments)},{"./lib/_stream_duplex.js":131,"./lib/_stream_passthrough.js":132,"./lib/_stream_readable.js":133,"./lib/_stream_transform.js":134,"./lib/_stream_writable.js":135,dup:76}],143:[function(e,t,r){(function(r){"use strict";var n=e("util");var i=e("stream").Transform;function s(e,t){n.inherits(s,i);if(typeof e==="function"){t=e;e={}}if(typeof t!=="function"){throw new Error("transform function required")}function s(t){if(!(this instanceof s)){return new s(t)}i.call(this,t);this._firstChunk=true;this._transformCalled=false;this._minSize=e.minSize}s.prototype._transform=function(e,n,i){this._enc=n;if(this._firstChunk){this._firstChunk=false;if(this._minSize==null){t.call(this,e,n,i);this._transformCalled=true;return}this._buffer=e;i();return}if(this._minSize==null){this.push(e);i();return}if(this._buffer.length=this._minSize){t.call(this,this._buffer.slice(),n,function(){this.push(e);i()}.bind(this));this._transformCalled=true;this._buffer=false;return}this.push(e);i()};s.prototype._flush=function(e){if(!this._buffer){e();return}if(this._transformCalled){this.push(this._buffer);e()}else{t.call(this,this._buffer.slice(),this._enc,e)}};return s}t.exports=function(){return s.apply(s,arguments)()};t.exports.ctor=s}).call(this,e("buffer").Buffer)},{buffer:6,stream:81,util:90}],144:[function(e,t,r){(function(r){"use strict";var n=e("through2");var i=e("ordered-read-streams");var s=e("unique-stream");var a=e("glob");var o=e("minimatch").Minimatch;var f=e("glob2base");var u=e("path");var c={createStream:function(e,t,r){e=p(r.cwd,e);var i=new a.Glob(e,r);var s=r.base||f(i);var o=n.obj(t.length?h:undefined);var c=false;i.on("error",o.emit.bind(o,"error"));i.on("end",function(){if(r.allowEmpty!==true&&!c&&m(i)){o.emit("error",new Error("File not found with singular glob"))}o.end()});i.on("match",function(e){c=true;o.write({cwd:r.cwd,base:s,path:u.resolve(r.cwd,e)})});return o;function h(e,r,n){var i=l.bind(null,e);if(t.every(i)){n(null,e)}else{n()}}},create:function(e,t){if(!t)t={};if(typeof t.cwd!=="string")t.cwd=r.cwd();if(typeof t.dot!=="boolean")t.dot=false;if(typeof t.silent!=="boolean")t.silent=true;if(typeof t.nonull!=="boolean")t.nonull=false;if(typeof t.cwdbase!=="boolean")t.cwdbase=false;if(t.cwdbase)t.base=t.cwd;if(!Array.isArray(e))e=[e];var n=[];var a=[];e.forEach(function(e,r){if(typeof e!=="string"&&!(e instanceof RegExp)){throw new Error("Invalid glob at index "+r)}var i=h(e)?a:n;if(i===a&&typeof e==="string"){e=new o(p(t.cwd,e),t)}i.push({index:r,glob:e})});if(n.length===0)throw new Error("Missing positive glob");if(n.length===1)return g(n[0]);var f=n.map(g);var u=new i(f);var l=s("path");var m=u.pipe(l);u.on("error",function(e){m.emit("error",e)});return m;function g(e){var r=a.filter(d(e.index)).map(v);return c.createStream(e.glob,r,t)}}};function l(e,t){if(t instanceof o)return t.match(e.path);if(t instanceof RegExp)return t.test(e.path)}function h(e){if(typeof e==="string")return e[0]==="!";if(e instanceof RegExp)return true}function p(e,t){var r="";if(t[0]==="!"){r=t[0];t=t.slice(1)}return r+u.resolve(e,t)}function d(e){return function(t){return t.index>e}}function v(e){return e.glob}function m(e){var t=e.minimatch.set;if(t.length!==1){return false}return t[0].every(function r(e){return typeof e==="string"})}t.exports=c}).call(this,e("_process"))},{_process:64,glob:146,glob2base:154,minimatch:156,"ordered-read-streams":160,path:62,through2:182,"unique-stream":183}],145:[function(e,t,r){(function(t){r.alphasort=u;r.alphasorti=f;r.setopts=h;r.ownProp=n;r.makeAbs=m;r.finish=d;r.mark=v;r.isIgnored=g;r.childrenIgnored=b;function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var i=e("path");var s=e("minimatch");var a=e("path-is-absolute");var o=s.Minimatch;function f(e,t){return e.toLowerCase().localeCompare(t.toLowerCase())}function u(e,t){return e.localeCompare(t)}function c(e,t){e.ignore=t.ignore||[];if(!Array.isArray(e.ignore))e.ignore=[e.ignore];if(e.ignore.length){e.ignore=e.ignore.map(l)}}function l(e){var t=null;if(e.slice(-3)==="/**"){var r=e.replace(/(\/\*\*)+$/,"");t=new o(r)}return{matcher:new o(e),gmatcher:t}}function h(e,r,s){if(!s)s={};if(s.matchBase&&-1===r.indexOf("/")){if(s.noglobstar){throw new Error("base matching requires globstar")}r="**/"+r}e.silent=!!s.silent;e.pattern=r;e.strict=s.strict!==false;e.realpath=!!s.realpath;e.realpathCache=s.realpathCache||Object.create(null);e.follow=!!s.follow;e.dot=!!s.dot;e.mark=!!s.mark;e.nodir=!!s.nodir;if(e.nodir)e.mark=true;e.sync=!!s.sync;e.nounique=!!s.nounique;e.nonull=!!s.nonull;e.nosort=!!s.nosort;e.nocase=!!s.nocase;e.stat=!!s.stat;e.noprocess=!!s.noprocess;e.maxLength=s.maxLength||Infinity;e.cache=s.cache||Object.create(null);e.statCache=s.statCache||Object.create(null);e.symlinks=s.symlinks||Object.create(null);c(e,s);e.changedCwd=false;var a=t.cwd();if(!n(s,"cwd"))e.cwd=a;else{e.cwd=s.cwd;e.changedCwd=i.resolve(s.cwd)!==a}e.root=s.root||i.resolve(e.cwd,"/");e.root=i.resolve(e.root);if(t.platform==="win32")e.root=e.root.replace(/\\/g,"/");e.nomount=!!s.nomount;s.nonegate=s.nonegate===false?false:true;s.nocomment=s.nocomment===false?false:true;p(s);e.minimatch=new o(r,s);e.options=e.minimatch.options}r.deprecationWarned;function p(e){if(!e.nonegate||!e.nocomment){if(t.noDeprecation!==true&&!r.deprecationWarned){var n="glob WARNING: comments and negation will be disabled in v6";if(t.throwDeprecation)throw new Error(n);else if(t.traceDeprecation)console.trace(n);else console.error(n);r.deprecationWarned=true}}}function d(e){var t=e.nounique;var r=t?[]:Object.create(null);for(var n=0,i=e.matches.length;n1)return true;for(var s=0;sthis.maxLength)return t();if(!this.stat&&m(this.cache,r)){var s=this.cache[r];if(Array.isArray(s))s="DIR";if(!i||s==="DIR")return t(null,s);if(i&&s==="FILE")return t()}var a;var o=this.statCache[r];if(o!==undefined){if(o===false)return t(null,o);else{var f=o.isDirectory()?"DIR":"FILE";if(i&&f==="FILE")return t();else return t(null,f,o)}}var u=this;var c=g("stat\x00"+r,l);if(c)n.lstat(r,c);function l(i,s){if(s&&s.isSymbolicLink()){return n.stat(r,function(n,i){if(n)u._stat2(e,r,null,s,t);else u._stat2(e,r,n,i,t)})}else{u._stat2(e,r,i,s,t)}}};x.prototype._stat2=function(e,t,r,n,i){if(r){this.statCache[t]=false;return i()}var s=e.slice(-1)==="/";this.statCache[t]=n;if(t.slice(-1)==="/"&&!n.isDirectory())return i(null,false,n);var a=n.isDirectory()?"DIR":"FILE";this.cache[t]=this.cache[t]||a;if(s&&a!=="DIR")return i();return i(null,a,n)}}).call(this,e("_process"))},{"./common.js":145,"./sync.js":153,_process:64,assert:1,events:14,fs:4,inflight:147,inherits:149,minimatch:156,once:151,path:62,"path-is-absolute":152,util:90}],147:[function(e,t,r){(function(r){var n=e("wrappy");var i=Object.create(null);var s=e("once");t.exports=n(a);function a(e,t){if(i[e]){i[e].push(t);return null}else{i[e]=[t];return o(e)}}function o(e){return s(function t(){var n=i[e];var s=n.length;var a=f(arguments);for(var o=0;os){n.splice(0,s);r.nextTick(function(){t.apply(null,a)})}else{delete i[e]}})}function f(e){var t=e.length;var r=[];for(var n=0;nthis.maxLength)return false;if(!this.stat&&v(this.cache,t)){var i=this.cache[t];if(Array.isArray(i))i="DIR";if(!r||i==="DIR")return i;if(r&&i==="FILE")return false}var s;var a=this.statCache[t];if(!a){var o;try{o=n.lstatSync(t)}catch(f){return false}if(o.isSymbolicLink()){try{a=n.statSync(t)}catch(f){a=o}}else{a=o}}this.statCache[t]=a;var i=a.isDirectory()?"DIR":"FILE";this.cache[t]=this.cache[t]||i;if(r&&i!=="DIR")return false;return i};b.prototype._mark=function(e){return l.mark(this,e)};b.prototype._makeAbs=function(e){return l.makeAbs(this,e)}}).call(this,e("_process"))},{"./common.js":145,"./glob.js":146,_process:64,assert:1,fs:4,minimatch:156,path:62,"path-is-absolute":152,util:90}],154:[function(e,t,r){"use strict";var n=e("path");var i=e("find-index");var s=function(e){var t=[];var r=true;for(var n=0;n-1;T--){var C=c[T];var M=n.slice(0,C.reStart);var N=n.slice(C.reStart,C.reEnd-8);var P=n.slice(C.reEnd-8,C.reEnd);var B=n.slice(C.reEnd);P+=B;var D=M.split("(").length-1;var U=B;for(w=0;w