diff --git a/dist/ipfsapi.js b/dist/ipfsapi.js index cbc57bf5a..d9d0fa08d 100644 --- a/dist/ipfsapi.js +++ b/dist/ipfsapi.js @@ -1,365 +1,77 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ipfsAPI = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o -// -// 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 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. - -// when used in node, this will actually load the util module we depend on -// versus loading the builtin util module as happens otherwise -// this is a bug in node module loading as far as I am concerned -var util = require('util/'); - -var pSlice = Array.prototype.slice; -var hasOwn = Object.prototype.hasOwnProperty; - -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) - -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } - else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = stackStartFunction.name; - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; - } - if (util.isNumber(value) && !isFinite(value)) { - return value.toString(); - } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); - } - return value; -} - -function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} - -function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); -} - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) { - return a === b; - } - var aIsArgs = isArguments(a), - bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - var ka = objectKeys(a), - kb = objectKeys(b), - key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } +'use strict'; +module.exports = function () { + return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g; }; -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } - - return false; -} +},{}],2:[function(require,module,exports){ +'use strict'; -function _throws(shouldThrow, block, expected, message) { - var actual; +function assembleStyles () { + var styles = { + modifiers: { + reset: [0, 0], + bold: [1, 22], // 21 isn't widely supported and 22 does the same thing + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + colors: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39] + }, + bgColors: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49] + } + }; - if (util.isString(expected)) { - message = expected; - expected = null; - } + // fix humans + styles.colors.grey = styles.colors.gray; - try { - block(); - } catch (e) { - actual = e; - } + Object.keys(styles).forEach(function (groupName) { + var group = styles[groupName]; - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); + Object.keys(group).forEach(function (styleName) { + var style = group[styleName]; - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } + styles[styleName] = group[styleName] = { + open: '\u001b[' + style[0] + 'm', + close: '\u001b[' + style[1] + 'm' + }; + }); - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + }); - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } + return styles; } -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function(err) { if (err) {throw err;}}; - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); -},{"util/":90}],2:[function(require,module,exports){ +},{}],3:[function(require,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { @@ -485,11 +197,7 @@ 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 Buffer = require('buffer').Buffer; // for use with browserify module.exports = function (a, b) { @@ -505,7 +213,7 @@ module.exports = function (a, b) { return true; }; -},{"buffer":6}],6:[function(require,module,exports){ +},{"buffer":5}],5:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. @@ -555,20 +263,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 +1232,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 +1249,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 +1263,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 +1285,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 +1300,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 +1353,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 +1362,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 +1376,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 +1388,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 +1407,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,1167 +1761,312 @@ 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){ -module.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" +},{"base64-js":3,"ieee754":10,"is-array":12}],6:[function(require,module,exports){ +(function (process){ +'use strict'; +var escapeStringRegexp = require('escape-string-regexp'); +var ansiStyles = require('ansi-styles'); +var stripAnsi = require('strip-ansi'); +var hasAnsi = require('has-ansi'); +var supportsColor = require('supports-color'); +var defineProps = Object.defineProperties; +var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM); + +function Chalk(options) { + // detect mode if not set manually + this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled; } -},{}],8:[function(require,module,exports){ -var Stat = require('fs').Stats +// use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001b[94m'; +} -module.exports = cloneStats +var styles = (function () { + var ret = {}; -function cloneStats(stats) { - var replacement = new Stat + Object.keys(ansiStyles).forEach(function (key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - Object.keys(stats).forEach(function(key) { - replacement[key] = stats[key] - }) + ret[key] = { + get: function () { + return build.call(this, this._styles.concat(key)); + } + }; + }); - return replacement -} + return ret; +})(); -},{"fs":4}],9:[function(require,module,exports){ -(function (Buffer){ -var clone = (function() { -'use strict'; +var proto = defineProps(function chalk() {}, styles); -/** - * 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). -*/ -function clone(parent, circular, depth, prototype) { - var filter; - if (typeof circular === 'object') { - depth = circular.depth; - prototype = circular.prototype; - filter = circular.filter; - circular = circular.circular - } - // maintain two arrays for circular references, where corresponding parents - // and children have the same index - var allParents = []; - var allChildren = []; +function build(_styles) { + var builder = function () { + return applyStyle.apply(builder, arguments); + }; - var useBuffer = typeof Buffer != 'undefined'; + builder._styles = _styles; + builder.enabled = this.enabled; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + /* eslint-disable no-proto */ + builder.__proto__ = proto; - if (typeof circular == 'undefined') - circular = true; + return builder; +} - if (typeof depth == 'undefined') - depth = Infinity; +function applyStyle() { + // support varags, but simply cast to string in case there's only one arg + var args = arguments; + var argsLen = args.length; + var str = argsLen !== 0 && String(arguments[0]); - // 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; + if (argsLen > 1) { + // don't slice `arguments`, it prevents v8 optimizations + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } - if (depth == 0) - return parent; + if (!this.enabled || !str) { + return str; + } - var child; - var proto; - if (typeof parent != 'object') { - return parent; - } + var nestedStyles = this._styles; + var i = nestedStyles.length; - if (clone.__isArray(parent)) { - child = []; - } else if (clone.__isRegExp(parent)) { - child = new RegExp(parent.source, __getRegExpFlags(parent)); - if (parent.lastIndex) child.lastIndex = parent.lastIndex; - } else if (clone.__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; - } - } + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + var originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) { + ansiStyles.dim.open = ''; + } - if (circular) { - var index = allParents.indexOf(parent); + while (i--) { + var code = ansiStyles[nestedStyles[i]]; - if (index != -1) { - return allChildren[index]; - } - allParents.push(parent); - allChildren.push(child); - } + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + } - for (var i in parent) { - var attrs; - if (proto) { - attrs = Object.getOwnPropertyDescriptor(proto, i); - } + // Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue. + ansiStyles.dim.open = originalDim; - if (attrs && attrs.set == null) { - continue; - } - child[i] = _clone(parent[i], depth - 1); - } + return str; +} - return child; - } +function init() { + var ret = {}; - return _clone(parent, depth); + Object.keys(styles).forEach(function (name) { + ret[name] = { + get: function () { + return build.call(this, [name]); + } + }; + }); + + return ret; } -/** - * 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 clonePrototype(parent) { - if (parent === null) - return null; +defineProps(Chalk.prototype, init()); - var c = function () {}; - c.prototype = parent; - return new c(); -}; +module.exports = new Chalk(); +module.exports.styles = ansiStyles; +module.exports.hasColor = hasAnsi; +module.exports.stripColor = stripAnsi; +module.exports.supportsColor = supportsColor; -// private utility functions +}).call(this,require('_process')) +},{"_process":48,"ansi-styles":2,"escape-string-regexp":8,"has-ansi":9,"strip-ansi":54,"supports-color":57}],7:[function(require,module,exports){ -function __objToStr(o) { - return Object.prototype.toString.call(o); -}; -clone.__objToStr = __objToStr; +/** + * Expose `Emitter`. + */ -function __isDate(o) { - return typeof o === 'object' && __objToStr(o) === '[object Date]'; -}; -clone.__isDate = __isDate; +module.exports = Emitter; -function __isArray(o) { - return typeof o === 'object' && __objToStr(o) === '[object Array]'; -}; -clone.__isArray = __isArray; +/** + * Initialize a new `Emitter`. + * + * @api public + */ -function __isRegExp(o) { - return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; -}; -clone.__isRegExp = __isRegExp; - -function __getRegExpFlags(re) { - var flags = ''; - if (re.global) flags += 'g'; - if (re.ignoreCase) flags += 'i'; - if (re.multiline) flags += 'm'; - return flags; +function Emitter(obj) { + if (obj) return mixin(obj); }; -clone.__getRegExpFlags = __getRegExpFlags; -return clone; -})(); +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ -if (typeof module === 'object' && module.exports) { - module.exports = clone; +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; } -}).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, - "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 -} +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ -},{}],11:[function(require,module,exports){ -(function (Buffer){ -// 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. +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks[event] = this._callbacks[event] || []) + .push(fn); + return this; +}; -// 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; +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; +Emitter.prototype.once = function(event, fn){ + var self = this; + this._callbacks = this._callbacks || {}; -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; + function on() { + self.off(event, on); + fn.apply(this, arguments); + } -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; + on.fn = fn; + this.on(event, on); + return this; +}; -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; + // specific event + var callbacks = this._callbacks[event]; + if (!callbacks) return this; -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks[event]; + return this; + } -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -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; - -function isBuffer(arg) { - return Buffer.isBuffer(arg); -} -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){ -(function (process,Buffer){ -var stream = require('readable-stream') -var eos = require('end-of-stream') -var util = require('util') - -var SIGNAL_FLUSH = new Buffer([0]) - -var onuncork = function(self, fn) { - if (self._corked) self.once('uncork', fn) - else fn() -} - -var destroyer = function(self, end) { - return function(err) { - if (err) self.destroy(err.message === 'premature close' ? null : err) - else if (end && !self._ended) self.end() - } -} - -var end = function(ws, fn) { - if (!ws) return fn() - if (ws._writableState && ws._writableState.finished) return fn() - if (ws._writableState) return ws.end(fn) - ws.end() - fn() -} - -var toStreams2 = function(rs) { - return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) -} - -var Duplexify = function(writable, readable, opts) { - if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) - stream.Duplex.call(this, opts) - - this._writable = null - this._readable = null - this._readable2 = null - - this._forwardDestroy = !opts || opts.destroy !== false - this._forwardEnd = !opts || opts.end !== false - this._corked = 1 // start corked - this._ondrain = null - this._drained = false - this._forwarding = false - this._unwrite = null - this._unread = null - this._ended = false - - this.destroyed = false - - if (writable) this.setWritable(writable) - if (readable) this.setReadable(readable) -} - -util.inherits(Duplexify, stream.Duplex) - -Duplexify.obj = function(writable, readable, opts) { - if (!opts) opts = {} - opts.objectMode = true - opts.highWaterMark = 16 - return new Duplexify(writable, readable, opts) -} - -Duplexify.prototype.cork = function() { - if (++this._corked === 1) this.emit('cork') -} - -Duplexify.prototype.uncork = function() { - if (this._corked && --this._corked === 0) this.emit('uncork') -} - -Duplexify.prototype.setWritable = function(writable) { - if (this._unwrite) this._unwrite() - - if (this.destroyed) { - if (writable && writable.destroy) writable.destroy() - return - } - - if (writable === null || writable === false) { - this.end() - return - } - - var self = this - var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) - - var ondrain = function() { - var ondrain = self._ondrain - self._ondrain = null - if (ondrain) ondrain() - } - - var clear = function() { - self._writable.removeListener('drain', ondrain) - unend() - } - - if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks - - this._writable = writable - this._writable.on('drain', ondrain) - this._unwrite = clear - - this.uncork() // always uncork setWritable -} - -Duplexify.prototype.setReadable = function(readable) { - if (this._unread) this._unread() - - if (this.destroyed) { - if (readable && readable.destroy) readable.destroy() - return - } - - if (readable === null || readable === false) { - this.push(null) - this.resume() - return - } - - var self = this - var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) - - var onreadable = function() { - self._forward() - } - - var onend = function() { - self.push(null) - } - - var clear = function() { - self._readable2.removeListener('readable', onreadable) - self._readable2.removeListener('end', onend) - unend() - } - - this._drained = true - this._readable = readable - this._readable2 = readable._readableState ? readable : toStreams2(readable) - this._readable2.on('readable', onreadable) - this._readable2.on('end', onend) - this._unread = clear - - this._forward() -} - -Duplexify.prototype._read = function() { - this._drained = true - this._forward() -} - -Duplexify.prototype._forward = function() { - if (this._forwarding || !this._readable2 || !this._drained) return - this._forwarding = true - - var data - var state = this._readable2._readableState - - while ((data = this._readable2.read(state.buffer.length ? state.buffer[0].length : state.length)) !== null) { - this._drained = this.push(data) - } - - this._forwarding = false -} - -Duplexify.prototype.destroy = function(err) { - if (this.destroyed) return - this.destroyed = true - - var self = this - process.nextTick(function() { - self._destroy(err) - }) -} - -Duplexify.prototype._destroy = function(err) { - if (err) { - var ondrain = this._ondrain - this._ondrain = null - if (ondrain) ondrain(err) - else this.emit('error', err) - } - - if (this._forwardDestroy) { - if (this._readable && this._readable.destroy) this._readable.destroy() - if (this._writable && this._writable.destroy) this._writable.destroy() - } - - this.emit('close') -} - -Duplexify.prototype._write = function(data, enc, cb) { - if (this.destroyed) return cb() - if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) - if (data === SIGNAL_FLUSH) return this._finish(cb) - if (!this._writable) return cb() - - if (this._writable.write(data) === false) this._ondrain = cb - else cb() -} - - -Duplexify.prototype._finish = function(cb) { - var self = this - this.emit('preend') - onuncork(this, function() { - end(self._forwardEnd && self._writable, function() { - // haxx to not emit prefinish twice - if (self._writableState.prefinished === false) self._writableState.prefinished = true - self.emit('prefinish') - onuncork(self, cb) - }) - }) -} - -Duplexify.prototype.end = function(data, enc, cb) { - if (typeof data === 'function') return this.end(null, null, data) - if (typeof enc === 'function') return this.end(data, null, enc) - this._ended = true - if (data) this.write(data) - if (!this._writableState.ending) this.write(SIGNAL_FLUSH) - return stream.Writable.prototype.end.call(this, 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){ -var once = require('once'); - -var noop = function() {}; - -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; - -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - - callback = once(callback || noop); - - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; - - var onfinish = function() { - writable = false; - if (!readable) callback(); - }; - - var onend = function() { - readable = false; - if (!writable) callback(); - }; - - var onclose = function() { - if (readable && !(rs && rs.ended)) return callback(new Error('premature close')); - if (writable && !(ws && ws.ended)) return callback(new Error('premature close')); - }; - - var onrequest = function() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', callback); - stream.on('close', onclose); - - return function() { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', callback); - stream.removeListener('close', onclose); - }; -}; - -module.exports = eos; -},{"once":60}],14:[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 EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; - -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } - throw TypeError('Uncaught, unspecified "error" event.'); - } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - len = arguments.length; - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - handler.apply(this, args); - } - } else if (isObject(handler)) { - len = arguments.length; - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - var m; - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; } } - - g.listener = listener; - this.on(type, g); - return this; }; -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ - if (position < 0) - return this; +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks[event]; - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); } return this; }; -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ - return this; +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks[event] || []; }; -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ -EventEmitter.listenerCount = function(emitter, type) { - var ret; - if (!emitter._events || !emitter._events[type]) - ret = 0; - else if (isFunction(emitter._events[type])) - ret = 1; - else - ret = emitter._events[type].length; - return ret; +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; }; -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} +},{}],8:[function(require,module,exports){ +'use strict'; -},{}],15:[function(require,module,exports){ +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -var hasOwn = Object.prototype.hasOwnProperty; -var toString = Object.prototype.toString; +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } -module.exports = function forEach (obj, fn, ctx) { - if (toString.call(fn) !== '[object Function]') { - throw new TypeError('iterator must be a function'); - } - 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); - } - } - } + return str.replace(matchOperatorsRe, '\\$&'); }; +},{}],9:[function(require,module,exports){ +'use strict'; +var ansiRegex = require('ansi-regex'); +var re = new RegExp(ansiRegex().source); // remove the `g` flag +module.exports = re.test.bind(re); -},{}],16:[function(require,module,exports){ +},{"ansi-regex":1}],10:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -3297,43 +2152,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],17:[function(require,module,exports){ - -var indexOf = [].indexOf; - -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 - } -} - -},{}],19:[function(require,module,exports){ +},{}],11:[function(require,module,exports){ var ip = exports, Buffer = require('buffer').Buffer, os = require('os'); @@ -3715,7 +2534,7 @@ function _normalizeFamily(family) { return family ? family.toLowerCase() : 'ipv4'; } -},{"buffer":6,"os":61}],20:[function(require,module,exports){ +},{"buffer":5,"os":47}],12:[function(require,module,exports){ /** * isArray @@ -3750,7 +2569,7 @@ module.exports = isArray || function (val) { return !! val && '[object Array]' == str.call(val); }; -},{}],21:[function(require,module,exports){ +},{}],13:[function(require,module,exports){ /** * Determine if an object is Buffer * @@ -3769,12 +2588,7 @@ module.exports = function (obj) { )) } -},{}],22:[function(require,module,exports){ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; - -},{}],23:[function(require,module,exports){ +},{}],14:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -3789,7 +2603,7 @@ var arrayPool = []; module.exports = arrayPool; -},{}],24:[function(require,module,exports){ +},{}],15:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -3853,7 +2667,7 @@ function baseBind(bindData) { module.exports = baseBind; -},{"lodash._basecreate":25,"lodash._setbinddata":35,"lodash._slice":37,"lodash.isobject":45}],25:[function(require,module,exports){ +},{"lodash._basecreate":16,"lodash._setbinddata":26,"lodash._slice":28,"lodash.isobject":36}],16:[function(require,module,exports){ (function (global){ /** * Lo-Dash 2.4.1 (Custom Build) @@ -3899,7 +2713,7 @@ if (!nativeCreate) { module.exports = baseCreate; }).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){ +},{"lodash._isnative":22,"lodash.isobject":36,"lodash.noop":39}],17:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -3981,7 +2795,7 @@ function baseCreateCallback(func, thisArg, argCount) { module.exports = baseCreateCallback; -},{"lodash._setbinddata":35,"lodash.bind":38,"lodash.identity":43,"lodash.support":50}],27:[function(require,module,exports){ +},{"lodash._setbinddata":26,"lodash.bind":29,"lodash.identity":34,"lodash.support":41}],18:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4061,7 +2875,7 @@ function baseCreateWrapper(bindData) { module.exports = baseCreateWrapper; -},{"lodash._basecreate":25,"lodash._setbinddata":35,"lodash._slice":37,"lodash.isobject":45}],28:[function(require,module,exports){ +},{"lodash._basecreate":16,"lodash._setbinddata":26,"lodash._slice":28,"lodash.isobject":36}],19:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4272,7 +3086,7 @@ function baseIsEqual(a, b, callback, isWhere, stackA, stackB) { module.exports = baseIsEqual; -},{"lodash._getarray":30,"lodash._objecttypes":33,"lodash._releasearray":34,"lodash.forin":41,"lodash.isfunction":44}],29:[function(require,module,exports){ +},{"lodash._getarray":21,"lodash._objecttypes":24,"lodash._releasearray":25,"lodash.forin":32,"lodash.isfunction":35}],20:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4380,7 +3194,7 @@ function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, ar module.exports = createWrapper; -},{"lodash._basebind":24,"lodash._basecreatewrapper":27,"lodash._slice":37,"lodash.isfunction":44}],30:[function(require,module,exports){ +},{"lodash._basebind":15,"lodash._basecreatewrapper":18,"lodash._slice":28,"lodash.isfunction":35}],21:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4403,7 +3217,7 @@ function getArray() { module.exports = getArray; -},{"lodash._arraypool":23}],31:[function(require,module,exports){ +},{"lodash._arraypool":14}],22:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4439,7 +3253,7 @@ function isNative(value) { module.exports = isNative; -},{}],32:[function(require,module,exports){ +},{}],23:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4454,7 +3268,7 @@ var maxPoolSize = 40; module.exports = maxPoolSize; -},{}],33:[function(require,module,exports){ +},{}],24:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4476,7 +3290,7 @@ var objectTypes = { module.exports = objectTypes; -},{}],34:[function(require,module,exports){ +},{}],25:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4503,7 +3317,7 @@ function releaseArray(array) { module.exports = releaseArray; -},{"lodash._arraypool":23,"lodash._maxpoolsize":32}],35:[function(require,module,exports){ +},{"lodash._arraypool":14,"lodash._maxpoolsize":23}],26:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4548,7 +3362,7 @@ var setBindData = !defineProperty ? noop : function(func, value) { module.exports = setBindData; -},{"lodash._isnative":31,"lodash.noop":48}],36:[function(require,module,exports){ +},{"lodash._isnative":22,"lodash.noop":39}],27:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4588,7 +3402,7 @@ var shimKeys = function(object) { module.exports = shimKeys; -},{"lodash._objecttypes":33}],37:[function(require,module,exports){ +},{"lodash._objecttypes":24}],28:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4628,7 +3442,7 @@ function slice(array, start, end) { module.exports = slice; -},{}],38:[function(require,module,exports){ +},{}],29:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4670,7 +3484,7 @@ function bind(func, thisArg) { module.exports = bind; -},{"lodash._createwrapper":29,"lodash._slice":37}],39:[function(require,module,exports){ +},{"lodash._createwrapper":20,"lodash._slice":28}],30:[function(require,module,exports){ /** * Lo-Dash 2.4.3 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4753,7 +3567,7 @@ function createCallback(func, thisArg, argCount) { module.exports = createCallback; -},{"lodash._basecreatecallback":26,"lodash._baseisequal":28,"lodash.isobject":45,"lodash.keys":46,"lodash.property":49}],40:[function(require,module,exports){ +},{"lodash._basecreatecallback":17,"lodash._baseisequal":19,"lodash.isobject":36,"lodash.keys":37,"lodash.property":40}],31:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4831,7 +3645,7 @@ function filter(collection, callback, thisArg) { module.exports = filter; -},{"lodash.createcallback":39,"lodash.forown":42}],41:[function(require,module,exports){ +},{"lodash.createcallback":30,"lodash.forown":33}],32:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4887,7 +3701,7 @@ var forIn = function(collection, callback, thisArg) { module.exports = forIn; -},{"lodash._basecreatecallback":26,"lodash._objecttypes":33}],42:[function(require,module,exports){ +},{"lodash._basecreatecallback":17,"lodash._objecttypes":24}],33:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4939,7 +3753,7 @@ var forOwn = function(collection, callback, thisArg) { module.exports = forOwn; -},{"lodash._basecreatecallback":26,"lodash._objecttypes":33,"lodash.keys":46}],43:[function(require,module,exports){ +},{"lodash._basecreatecallback":17,"lodash._objecttypes":24,"lodash.keys":37}],34:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4969,7 +3783,7 @@ function identity(value) { module.exports = identity; -},{}],44:[function(require,module,exports){ +},{}],35:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -4998,7 +3812,7 @@ function isFunction(value) { module.exports = isFunction; -},{}],45:[function(require,module,exports){ +},{}],36:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -5039,7 +3853,7 @@ function isObject(value) { module.exports = isObject; -},{"lodash._objecttypes":33}],46:[function(require,module,exports){ +},{"lodash._objecttypes":24}],37:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -5077,7 +3891,7 @@ var keys = !nativeKeys ? shimKeys : function(object) { module.exports = keys; -},{"lodash._isnative":31,"lodash._shimkeys":36,"lodash.isobject":45}],47:[function(require,module,exports){ +},{"lodash._isnative":22,"lodash._shimkeys":27,"lodash.isobject":36}],38:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -5149,7 +3963,7 @@ function map(collection, callback, thisArg) { module.exports = map; -},{"lodash.createcallback":39,"lodash.forown":42}],48:[function(require,module,exports){ +},{"lodash.createcallback":30,"lodash.forown":33}],39:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -5177,7 +3991,7 @@ function noop() { module.exports = noop; -},{}],49:[function(require,module,exports){ +},{}],40:[function(require,module,exports){ /** * Lo-Dash 2.4.1 (Custom Build) * Build: `lodash modularize modern exports="npm" -o ./npm/` @@ -5219,7 +4033,7 @@ function property(key) { module.exports = property; -},{}],50:[function(require,module,exports){ +},{}],41:[function(require,module,exports){ (function (global){ /** * Lo-Dash 2.4.1 (Custom Build) @@ -5263,49 +4077,7 @@ 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){ +},{"lodash._isnative":22}],42:[function(require,module,exports){ (function (Buffer){ var map = require('lodash.map') var filter = require('lodash.filter') @@ -5481,7 +4253,7 @@ function protoFromTuple(tup) { } }).call(this,require("buffer").Buffer) -},{"./convert":53,"./protocols":56,"buffer":6,"lodash.filter":40,"lodash.map":47}],53:[function(require,module,exports){ +},{"./convert":43,"./protocols":46,"buffer":5,"lodash.filter":31,"lodash.map":38}],43:[function(require,module,exports){ (function (Buffer){ var ip = require('ip') var protocols = require('./protocols') @@ -5539,7 +4311,7 @@ function buf2port(buf) { } }).call(this,require("buffer").Buffer) -},{"./protocols":56,"buffer":6,"ip":19}],54:[function(require,module,exports){ +},{"./protocols":46,"buffer":5,"ip":11}],44:[function(require,module,exports){ (function (Buffer){ var map = require('lodash.map') var extend = require('xtend') @@ -5700,7 +4472,7 @@ Multiaddr.prototype.fromStupidString = function fromStupidString(str) { 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){ +},{"./codec":42,"./protocols":46,"buffer":5,"buffer-equal":4,"lodash.map":38,"xtend":45}],45:[function(require,module,exports){ module.exports = extend function extend() { @@ -5719,7 +4491,7 @@ function extend() { return target } -},{}],56:[function(require,module,exports){ +},{}],46:[function(require,module,exports){ var map = require('lodash.map') module.exports = Protocols @@ -5774,236 +4546,7 @@ 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){ +},{"lodash.map":38}],47:[function(require,module,exports){ exports.endianness = function () { return 'LE' }; exports.hostname = function () { @@ -6050,252 +4593,7 @@ exports.tmpdir = exports.tmpDir = function () { 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){ +},{}],48:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -6388,7 +4686,7 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],65:[function(require,module,exports){ +},{}],49:[function(require,module,exports){ (function (global){ /*! https://mths.be/punycode v1.3.2 by @mathias */ ;(function(root) { @@ -6922,7 +5220,7 @@ process.umask = function() { return 0; }; }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],66:[function(require,module,exports){ +},{}],50:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -7008,7 +5306,7 @@ var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; -},{}],67:[function(require,module,exports){ +},{}],51:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -7095,15156 +5393,2492 @@ var objectKeys = Object.keys || function (obj) { return res; }; -},{}],68:[function(require,module,exports){ +},{}],52:[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") +},{"./decode":50,"./encode":51}],53:[function(require,module,exports){ -},{"./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. +/** + * Reduce `arr` with `fn`. + * + * @param {Array} arr + * @param {Function} fn + * @param {Mixed} initial + * + * TODO: combatible error handling? + */ -'use strict'; +module.exports = function(arr, fn, initial){ + var idx = 0; + var len = arr.length; + var curr = arguments.length == 3 + ? initial + : arr[idx++]; -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -} -/**/ + while (idx < len) { + curr = fn.call(null, curr, arr[idx], ++idx, arr); + } + + return curr; +}; +},{}],54:[function(require,module,exports){ +'use strict'; +var ansiRegex = require('ansi-regex')(); +module.exports = function (str) { + return typeof str === 'string' ? str.replace(ansiRegex, '') : str; +}; -module.exports = Duplex; +},{"ansi-regex":1}],55:[function(require,module,exports){ +'use strict'; +var url = require('url'); +var querystring = require('querystring'); +var chalk = require('chalk'); +var superagent = require('superagent'); -/**/ -var processNextTick = require('process-nextick-args'); -/**/ +exports = module.exports = function(options) { + if(!options) options = {}; + if(options instanceof superagent.Request) + return attachSuperagentLogger({}, options); + return attachSuperagentLogger.bind(null, options); +}; +function attachSuperagentLogger(options, req) { + var start = new Date().getTime(); -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + var uri = url.parse(req.url); + var method = req.method; -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); + if(options.outgoing) { + console.log('%s %s %s %s %s', + chalk.gray( + rightPad(uri.protocol.toUpperCase().replace(/[^\w]/g, ''), 5) + ), + chalk.gray(rightPad(method.toUpperCase(), 'delete'.length)), + chalk.gray(' - '), + chalk.gray(uri.href + (req.qs ? '' : '?' + querystring.encode(req.qs))), + chalk.gray('(pending)') + ); + } + + req.on('response', function(res) { + var now = new Date().getTime(); + var elapsed = now - start; + + var st = res.status; + if(st < 300) { + st = chalk.green(st); + } else if (st < 400) { + st = chalk.yellow(st); + } else { + st = chalk.red(st); + } -util.inherits(Duplex, Readable); -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]; + console.log('%s %s %s %s %s', + chalk.magenta( + rightPad(uri.protocol.toUpperCase().replace(/[^\w]/g, ''), 5) + ), + chalk.cyan(rightPad(method.toUpperCase(), 'delete'.length)), + st, + chalk.gray(uri.href + (req.qs ? '' : '?' + querystring.encode(req.qs))), + chalk.gray('(') + + chalk[colorForSpeed(elapsed)](elapsed + 'ms') + + chalk.gray(')') + ); + }); } -function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); +function colorForSpeed(ms) { + if(ms < 200) { + return 'green'; + } else if(ms < 1000) { + return 'gray'; + } else if(ms < 5000) { + return 'yellow'; + } else { + return 'red'; + } +} - Readable.call(this, options); - Writable.call(this, options); +function rightPad(str, len) { + var l = str.length; + if(l < len) { + for(var i = 0, n = len - l; i < n; i++) { + str += ' '; + } + } + return str; +} - if (options && options.readable === false) - this.readable = false; +},{"chalk":6,"querystring":52,"superagent":56,"url":58}],56:[function(require,module,exports){ +/** + * Module dependencies. + */ - if (options && options.writable === false) - this.writable = false; +var Emitter = require('emitter'); +var reduce = require('reduce'); - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; +/** + * Root reference for iframes. + */ - this.once('end', onend); +var root; +if (typeof window !== 'undefined') { // Browser window + root = window; +} else if (typeof self !== 'undefined') { // Web Worker + root = self; +} else { // Other environments + root = this; } -// 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; +/** + * Noop. + */ - // no more data can be written. - // But allow more writes to happen in this tick. - processNextTick(onEndNT, this); -} +function noop(){}; -function onEndNT(self) { - self.end(); -} +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * TODO: future proof, move to compoent land + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isHost(obj) { + var str = {}.toString.call(obj); -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); + switch (str) { + case '[object File]': + case '[object Blob]': + case '[object FormData]': + return true; + default: + return false; } } -},{"./_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. - -'use strict'; - -module.exports = PassThrough; - -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); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); -}; - -},{"./_stream_transform":73,"core-util-is":11,"inherits":18}],72:[function(require,module,exports){ -(function (process){ -'use strict'; - -module.exports = Readable; - -/**/ -var processNextTick = require('process-nextick-args'); -/**/ - - -/**/ -var isArray = require('isarray'); -/**/ - - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Readable.ReadableState = ReadableState; - -var EE = require('events').EventEmitter; +/** + * Determine XHR. + */ -/**/ -if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; +request.getXHR = function () { + if (root.XMLHttpRequest + && (!root.location || 'file:' != root.location.protocol + || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} + } + return false; }; -/**/ - - -/**/ -var Stream; -(function (){try{ - Stream = require('st' + 'ream'); -}catch(_){}finally{ - if (!Stream) - Stream = require('events').EventEmitter; -}}()) -/**/ - -var Buffer = require('buffer').Buffer; - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ +var trim = ''.trim + ? function(s) { return s.trim(); } + : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; +/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ -/**/ -var debug = require('util'); -if (debug && debug.debuglog) { - debug = debug.debuglog('stream'); -} else { - debug = function () {}; +function isObject(obj) { + return obj === Object(obj); } -/**/ - -var StringDecoder; - -util.inherits(Readable, Stream); -function ReadableState(options, stream) { - var Duplex = require('./_stream_duplex'); - - options = options || {}; +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ - // 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; - - // 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; - - // 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; - - // 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 serialize(obj) { + if (!isObject(obj)) return obj; + var pairs = []; + for (var key in obj) { + if (null != obj[key]) { + pairs.push(encodeURIComponent(key) + + '=' + encodeURIComponent(obj[key])); + } } + return pairs.join('&'); } -function Readable(options) { - var Duplex = require('./_stream_duplex'); +/** + * Expose serialization method. + */ - if (!(this instanceof Readable)) - return new Readable(options); + request.serializeObject = serialize; - this._readableState = new ReadableState(options, this); + /** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ - // legacy - this.readable = true; +function parseString(str) { + var obj = {}; + var pairs = str.split('&'); + var parts; + var pair; - if (options && typeof options.read === 'function') - this._read = options.read; + for (var i = 0, len = pairs.length; i < len; ++i) { + pair = pairs[i]; + parts = pair.split('='); + obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); + } - Stream.call(this); + return obj; } -// 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 = ''; - } - } +/** + * Expose parser. + */ - return readableAddChunk(this, state, chunk, encoding, false); -}; +request.parseString = parseString; -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ -Readable.prototype.isPaused = function() { - return this._readableState.flowing === false; +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'application/xml', + urlencoded: 'application/x-www-form-urlencoded', + 'form': 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' }; -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 (!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); - - if (state.needReadable) - emitReadable(stream); - } - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + request.serialize = { + 'application/x-www-form-urlencoded': serialize, + 'application/json': JSON.stringify + }; -// 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); -} + /** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ -// 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; +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse }; -// 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; -} - -function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ - if (state.objectMode) - return n === 0 ? 0 : 1; +function parseHeader(str) { + var lines = str.split(/\r?\n/); + var fields = {}; + var index; + var line; + var field; + var val; - 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; - } + lines.pop(); // trailing CRLF - if (n <= 0) - return 0; - - // 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); - - // 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; - } + for (var i = 0, len = lines.length; i < len; ++i) { + line = lines[i]; + index = line.indexOf(':'); + field = line.slice(0, index).toLowerCase(); + val = trim(line.slice(index + 1)); + fields[field] = val; } - return n; + return fields; } -// 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; - - // 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; - } +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ - n = howMuchToRead(n, state); +function type(str){ + return str.split(/ *; */).shift(); +}; - // 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; - } +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ - // 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. +function params(str){ + return reduce(str.split(/ *; */), function(obj, str){ + var parts = str.split(/ *= */) + , key = parts.shift() + , val = parts.shift(); - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); + if (key && val) obj[key] = val; + return obj; + }, {}); +}; - // 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); - } +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ - // 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); - } +function Response(req, options) { + options = options || {}; + this.req = req; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers + this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') + ? this.xhr.responseText + : null; + this.statusText = this.req.xhr.statusText; + this.setStatusProperties(this.xhr.status); + this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this.setHeaderProperties(this.header); + this.body = this.req.method != 'HEAD' + ? this.parseBody(this.text ? this.text : this.xhr.response) + : 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; - } +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ - // 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); +Response.prototype.get = function(field){ + return this.header[field.toLowerCase()]; +}; - var ret; - if (n > 0) - ret = fromList(n, state); - else - ret = null; +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ - if (ret === null) { - state.needReadable = true; - n = 0; - } +Response.prototype.setHeaderProperties = function(header){ + // content-type + var ct = this.header['content-type'] || ''; + this.type = type(ct); - state.length -= n; + // params + var obj = params(ct); + for (var key in obj) this[key] = obj[key]; +}; - // 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; +/** + * Force given parser + * + * Sets the body parser no matter type. + * + * @param {Function} + * @api public + */ - // 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); +Response.prototype.parse = function(fn){ + this.parser = fn; + return this; +}; - if (ret !== null) - this.emit('data', ret); +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ - return ret; +Response.prototype.parseBody = function(str){ + var parse = this.parser || request.parse[this.type]; + return parse && str && (str.length || str instanceof Object) + ? parse(str) + : null; }; -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; -} - +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ -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; - } +Response.prototype.setStatusProperties = function(status){ + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + if (status === 1223) { + status = 204; } - state.ended = true; - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} + var type = status / 100 | 0; -// 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); - } -} + // status / class + this.status = this.statusCode = status; + this.statusType = type; -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} + // basics + this.info = 1 == type; + this.ok = 2 == type; + this.clientError = 4 == type; + this.serverError = 5 == type; + this.error = (4 == type || 5 == type) + ? this.toError() + : false; + // sugar + this.accepted = 202 == status; + this.noContent = 204 == status; + this.badRequest = 400 == status; + this.unauthorized = 401 == status; + this.notAcceptable = 406 == status; + this.notFound = 404 == status; + this.forbidden = 403 == status; +}; -// 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); - } -} +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ -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; -} +Response.prototype.toError = function(){ + var req = this.req; + var method = req.method; + var url = req.url; -// 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')); + var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; + var err = new Error(msg); + err.status = this.status; + err.method = method; + err.url = url; + + return err; }; -Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; +/** + * Expose `Response`. + */ - 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); +request.Response = Response; - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - processNextTick(endFn); - else - src.once('end', endFn); +function Request(method, url) { + var self = this; + Emitter.call(this); + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; + this._header = {}; + this.on('end', function(){ + var err = null; + var res = null; - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); + try { + res = new Response(self); + } catch(e) { + err = new Error('Parser is unable to parse the response'); + err.parse = true; + err.original = e; + return self.callback(err); } - } - function onend() { - debug('onend'); - dest.end(); - } + self.emit('response', res); - // 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() { - 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); - - // 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(); - } + if (err) { + return self.callback(err, res); + } - 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 (res.status >= 200 && res.status < 300) { + return self.callback(err, res); } - } - // 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]; + var new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); + new_err.original = err; + new_err.response = res; + new_err.status = res.status; + self.callback(new_err, res); + }); +} +/** + * Mixin `Emitter`. + */ - // 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); +Emitter(Request.prototype); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } +/** + * Allow for extension + */ - // tell the dest that it's being piped to - dest.emit('pipe', src); +Request.prototype.use = function(fn) { + fn(this); + return this; +} - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } +/** + * Set timeout to `ms`. + * + * @param {Number} ms + * @return {Request} for chaining + * @api public + */ - return dest; +Request.prototype.timeout = function(ms){ + this._timeout = ms; + return this; }; -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; +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; +Request.prototype.clearTimeout = function(){ + this._timeout = 0; + clearTimeout(this._timer); + return this; +}; - // 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; - - 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; - } +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} + * @api public + */ - // slow case. multiple pipe destinations. +Request.prototype.abort = function(){ + if (this.aborted) return; + this.aborted = true; + this.xhr.abort(); + this.clearTimeout(); + this.emit('abort'); + return this; +}; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; +/** + * Set header `field` to `val`, or multiple fields with one object. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); +Request.prototype.set = function(field, val){ + if (isObject(field)) { + for (var key in field) { + this.set(key, field[key]); + } return this; } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - + this._header[field.toLowerCase()] = val; + this.header[field] = val; return this; }; -// 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 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 (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); - } - } - } +/** + * Remove header `field`. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field + * @return {Request} for chaining + * @api public + */ - return res; +Request.prototype.unset = function(field){ + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; }; -Readable.prototype.addListener = Readable.prototype.on; -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} +/** + * Get case-insensitive header `field` value. + * + * @param {String} field + * @return {String} + * @api private + */ -// 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; +Request.prototype.getHeader = function(field){ + return this._header[field.toLowerCase()]; }; -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - processNextTick(resume_, stream, state); - } -} +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } +Request.prototype.type = function(type){ + this.set('Content-Type', request.types[type] || type); + return this; +}; - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) - stream.read(0); -} +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ -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'); - } +Request.prototype.accept = function(type){ + this.set('Accept', request.types[type] || type); return this; }; -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - if (state.flowing) { - do { - var chunk = stream.read(); - } while (null !== chunk && state.flowing); - } -} - -// 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; +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} pass + * @return {Request} for chaining + * @api public + */ - 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); - } +Request.prototype.auth = function(user, pass){ + var str = btoa(user + ':' + pass); + this.set('Authorization', 'Basic ' + str); + return this; +}; - self.push(null); - }); +/** +* Add query-string `val`. +* +* Examples: +* +* request.get('/shoes') +* .query('size=10') +* .query({ color: 'blue' }) +* +* @param {Object|String} val +* @return {Request} for chaining +* @api public +*/ - 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(); - } - }); +Request.prototype.query = function(val){ + if ('string' != typeof val) val = serialize(val); + if (val) this._query.push(val); + return this; +}; - // 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); - } - } +/** + * Write the field `name` and `val` for "multipart/form-data" + * request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * ``` + * + * @param {String} name + * @param {String|Blob|File} val + * @return {Request} for chaining + * @api public + */ - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); +Request.prototype.field = function(name, val){ + if (!this._formData) this._formData = new root.FormData(); + this._formData.append(name, val); + return this; +}; - // 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(); - } - }; +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `filename`. + * + * ``` js + * request.post('/upload') + * .attach(new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String} filename + * @return {Request} for chaining + * @api public + */ - return self; +Request.prototype.attach = function(field, file, filename){ + if (!this._formData) this._formData = new root.FormData(); + this._formData.append(field, file, filename); + return this; }; +/** + * Send `data`, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // querystring + * request.get('/search') + * .end(callback) + * + * // multiple data "writes" + * request.get('/search') + * .send({ search: 'query' }) + * .send({ range: '1..5' }) + * .send({ order: 'desc' }) + * .end(callback) + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}) + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ - -// 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(); +Request.prototype.send = function(data){ + var obj = isObject(data); + var type = this.getHeader('Content-Type'); + + // merge + if (obj && isObject(this._data)) { + for (var key in data) { + this._data[key] = data[key]; + } + } else if ('string' == typeof data) { + if (!type) this.type('form'); + type = this.getHeader('Content-Type'); + if ('application/x-www-form-urlencoded' == type) { + this._data = this._data + ? this._data + '&' + data + : data; } 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 (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } + this._data = (this._data || '') + data; } + } else { + this._data = data; } - return ret; -} + if (!obj || isHost(data)) return this; + if (!type) this.type('json'); + return this; +}; -function endReadable(stream) { - var state = stream._readableState; +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ - // 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'); +Request.prototype.callback = function(err, res){ + var fn = this._callback; + this.clearTimeout(); + fn(err, res); +}; - if (!state.endEmitted) { - state.ended = true; - processNextTick(endReadableNT, state, stream); - } -} +/** + * Invoke callback with x-domain error. + * + * @api private + */ -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'); - } -} +Request.prototype.crossDomainError = function(){ + var err = new Error('Origin is not allowed by Access-Control-Allow-Origin'); + err.crossDomain = true; + this.callback(err); +}; -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} +/** + * Invoke callback with timeout error. + * + * @api private + */ -function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} +Request.prototype.timeoutError = function(){ + var timeout = this._timeout; + var err = new Error('timeout of ' + timeout + 'ms exceeded'); + err.timeout = timeout; + this.callback(err); +}; -}).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. +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ -'use strict'; +Request.prototype.withCredentials = function(){ + this._withCredentials = true; + return this; +}; -module.exports = Transform; +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ -var Duplex = require('./_stream_duplex'); +Request.prototype.end = function(fn){ + var self = this; + var xhr = this.xhr = request.getXHR(); + var query = this._query.join('&'); + var timeout = this._timeout; + var data = this._formData || this._data; -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + // store callback + this._callback = fn || noop; -util.inherits(Transform, Duplex); + // state change + xhr.onreadystatechange = function(){ + if (4 != xhr.readyState) return; + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + var status; + try { status = xhr.status } catch(e) { status = 0; } -function TransformState(stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); + if (0 == status) { + if (self.timedout) return self.timeoutError(); + if (self.aborted) return; + return self.crossDomainError(); + } + self.emit('end'); }; - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; + // progress + var handleProgress = function(e){ + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + } + self.emit('progress', e); + }; + if (this.hasListeners('progress')) { + xhr.onprogress = handleProgress; + } + try { + if (xhr.upload && this.hasListeners('progress')) { + xhr.upload.onprogress = handleProgress; + } + } catch(e) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); + // timeout + if (timeout && !this._timer) { + this._timer = setTimeout(function(){ + self.timedout = true; + self.abort(); + }, timeout); + } - ts.writechunk = null; - ts.writecb = null; + // querystring + if (query) { + query = request.serializeObject(query); + this.url += ~this.url.indexOf('?') + ? '&' + query + : '?' + query; + } - if (data !== null && data !== undefined) - stream.push(data); + // initiate request + xhr.open(this.method, this.url, true); - if (cb) - cb(er); + // CORS + if (this._withCredentials) xhr.withCredentials = true; - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); + // body + if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) { + // serialize stuff + var contentType = this.getHeader('Content-Type'); + var serialize = request.serialize[contentType ? contentType.split(';')[0] : '']; + if (serialize) data = serialize(data); } -} + // set header fields + for (var field in this.header) { + if (null == this.header[field]) continue; + xhr.setRequestHeader(field, this.header[field]); + } -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); + // send stuff + this.emit('request', this); + xhr.send(data); + return this; +}; - Duplex.call(this, options); +/** + * Faux promise support + * + * @param {Function} fulfill + * @param {Function} reject + * @return {Request} + */ - this._transformState = new TransformState(this); +Request.prototype.then = function (fulfill, reject) { + return this.end(function(err, res) { + err ? reject(err) : fulfill(res); + }); +} - // when the writable side finishes, then flush out anything remaining. - var stream = this; +/** + * Expose `Request`. + */ - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; +request.Request = Request; - // 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; +/** + * Issue a request: + * + * Examples: + * + * request('GET', '/users').end(callback) + * request('/users').end(callback) + * request('/users', callback) + * + * @param {String} method + * @param {String|Function} url or callback + * @return {Request} + * @api public + */ - if (options) { - if (typeof options.transform === 'function') - this._transform = options.transform; +function request(method, url) { + // callback + if ('function' == typeof url) { + return new Request('GET', method).end(url); + } - if (typeof options.flush === 'function') - this._flush = options.flush; + // url first + if (1 == arguments.length) { + return new Request('GET', method); } - this.once('prefinish', function() { - if (typeof this._flush === 'function') - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); + return new Request(method, url); } -Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ -// 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'); +request.get = function(url, data, fn){ + var req = request('GET', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.query(data); + if (fn) req.end(fn); + return req; }; -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); - } +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ + +request.head = function(url, data, fn){ + var req = request('HEAD', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; }; -// 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; +/** + * DELETE `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Function} fn + * @return {Request} + * @api public + */ - 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; - } +request.del = function(url, fn){ + var req = request('DELETE', url); + if (fn) req.end(fn); + return req; }; +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */ -function done(stream, er) { - if (er) - return stream.emit('error', er); +request.patch = function(url, data, fn){ + var req = request('PATCH', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; - // 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; +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */ - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); +request.post = function(url, data, fn){ + var req = request('POST', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; - if (ts.transforming) - throw new Error('calling transform done when still transforming'); +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ - return stream.push(null); -} +request.put = function(url, data, fn){ + var req = request('PUT', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; -},{"./_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. +/** + * Expose `request`. + */ -'use strict'; +module.exports = request; -module.exports = Writable; +},{"emitter":7,"reduce":53}],57:[function(require,module,exports){ +(function (process){ +'use strict'; +var argv = process.argv; -/**/ -var processNextTick = require('process-nextick-args'); -/**/ +var terminator = argv.indexOf('--'); +var hasFlag = function (flag) { + flag = '--' + flag; + var pos = argv.indexOf(flag); + return pos !== -1 && (terminator !== -1 ? pos < terminator : true); +}; +module.exports = (function () { + if ('FORCE_COLOR' in process.env) { + return true; + } -/**/ -var Buffer = require('buffer').Buffer; -/**/ + if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + return false; + } -Writable.WritableState = WritableState; + if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + return true; + } + if (process.stdout && !process.stdout.isTTY) { + return false; + } -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + if (process.platform === 'win32') { + return true; + } + if ('COLORTERM' in process.env) { + return true; + } + if (process.env.TERM === 'dumb') { + return false; + } -/**/ -var Stream; -(function (){try{ - Stream = require('st' + 'ream'); -}catch(_){}finally{ - if (!Stream) - Stream = require('events').EventEmitter; -}}()) -/**/ + if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { + return true; + } -var Buffer = require('buffer').Buffer; + return false; +})(); -util.inherits(Writable, Stream); +}).call(this,require('_process')) +},{"_process":48}],58:[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 nop() {} +var punycode = require('punycode'); -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; -function WritableState(options, stream) { - var Duplex = require('./_stream_duplex'); +exports.Url = Url; - options = options || {}; - - // 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; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; - - // 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; - - // 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, because 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; - - // 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; +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; } -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: require('util-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; +// Reference: RFC 3986, RFC 1808, RFC 2396 - if (typeof options.writev === 'function') - this._writev = options.writev; - } +// 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]*$/, - Stream.call(this); -} + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); -}; + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + // 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 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); -} +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && isObject(url) && url instanceof Url) return url; -// 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; + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; } -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); +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } - return ret; -}; - -Writable.prototype.cork = function() { - var state = this._writableState; - - state.corked++; -}; - -Writable.prototype.uncork = function() { - var state = this._writableState; + var rest = url; - if (state.corked) { - state.corked--; + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); - if (!state.writing && - !state.corked && - !state.finished && - !state.bufferProcessing && - state.bufferedRequest) - clearBuffer(this, state); + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); } -}; - -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; -}; -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); + // 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; + } } - return chunk; -} -// 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 (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; + // 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 - state.length += len; + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; + // 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; + } - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; + // 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 { - state.bufferedRequest = state.lastBufferedRequest; + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); } - } 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; -} + // 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); + } -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) - processNextTick(cb, er); - else - cb(er); + // 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; - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} + // pull out port. + this.parseHost(); -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; - onwriteStateUpdate(state); + // 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] === ']'; - 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); + // 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 (sync) { - processNextTick(afterWrite, stream, state, finished, cb); + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; } else { - afterWrite(stream, state, finished, cb); + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); } - } -} - -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 there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - 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; + 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('.'); } - // 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); - } - }); + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; - // 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; + // 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; } } - - if (entry === null) - state.lastBufferedRequest = null; - } - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; } - if (chunk !== null && chunk !== undefined) - this.write(chunk, encoding); + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); + // 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); + } } - // 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); -} - -function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); + // 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); } -} - -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); + 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 = {}; } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - processNextTick(cb); - else - stream.once('finish', cb); + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; } - state.ended = true; -} - -},{"./_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") - -},{"./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") - -},{"./lib/_stream_transform.js":73}],78:[function(require,module,exports){ -module.exports = require("./lib/_stream_writable.js") - -},{"./lib/_stream_writable.js":74}],79:[function(require,module,exports){ -var path = require('path'); -module.exports = function(npath, ext) { - if (typeof npath !== 'string') return npath; - if (npath.length === 0) return npath; + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } - var nFileName = path.basename(npath, path.extname(npath))+ext; - return path.join(path.dirname(npath), nFileName); + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; }; -},{"path":62}],80:[function(require,module,exports){ -var Readable = require('stream').Readable; -var PassThrough = require('stream').PassThrough; -function SandwichStream(options) { - Readable.call(this, options); - options = options || {}; - this._streamsActive = false; - this._streamsAdded = false; - this._streams = []; - this._currentStream = undefined; - this._errorsEmitted = false; - - if (options.head) { - this._head = options.head; - } - if (options.tail) { - this._tail = options.tail; - } - if (options.separator) { - this._separator = options.separator; - } +// 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(); } -SandwichStream.prototype = Object.create(Readable.prototype, { - constructor: SandwichStream -}); - -SandwichStream.prototype._read = function () { - if (!this._streamsActive) { - this._streamsActive = true; - this._pushHead(); - this._streamNextStream(); - } -}; - -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'); +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; } -}; -SandwichStream.prototype._substreamOnError = function (error) { - this._errorsEmitted = true; - this.emit('error', error); -}; + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; -SandwichStream.prototype._pushHead = function () { - if (this._head) { - this.push(this._head); + 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; + } } -}; -SandwichStream.prototype._streamNextStream = function () { - if (this._nextStream()) { - this._bindCurrentStreamEvents(); - } - else { - this._pushTail(); - this.push(null); + if (this.query && + isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); } -}; -SandwichStream.prototype._nextStream = function () { - this._currentStream = this._streams.shift(); - return this._currentStream !== undefined; -}; + var search = this.search || (query && ('?' + query)) || ''; -SandwichStream.prototype._bindCurrentStreamEvents = function () { - this._currentStream.on('readable', this._currentStreamOnReadable.bind(this)); - this._currentStream.on('end', this._currentStreamOnEnd.bind(this)); -}; + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; -SandwichStream.prototype._currentStreamOnReadable = function () { - this.push(this._currentStream.read() || ''); -}; + // 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 = ''; + } -SandwichStream.prototype._currentStreamOnEnd = function () { - this._pushSeparator(); - this._streamNextStream(); -}; + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; -SandwichStream.prototype._pushSeparator = function () { - if (this._streams.length > 0 && this._separator) { - this.push(this._separator); - } -}; + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); -SandwichStream.prototype._pushTail = function () { - if (this._tail) { - this.push(this._tail); - } + return protocol + host + pathname + search + hash; }; -function sandwichStream(options) { - var stream = new SandwichStream(options); - return stream; +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); } -sandwichStream.SandwichStream = SandwichStream; - -module.exports = sandwichStream; - -},{"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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -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'); - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; -function Stream() { - EE.call(this); +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); } -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } +Url.prototype.resolveObject = function(relative) { + if (isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; } - 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 result = new Url(); + Object.keys(this).forEach(function(k) { + result[k] = this[k]; + }, this); - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; - dest.end(); + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; } + // 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]; + }); - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // 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. + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; } - } - - 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); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); + result.href = result.format(); + return result; } - source.on('end', cleanup); - source.on('close', cleanup); + 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; + } - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"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') - -var http = exports - -http.request = function (opts, cb) { - if (typeof opts === 'string') - opts = url.parse(opts) - else - opts = extend(opts) - - var protocol = opts.protocol || '' - var host = opts.hostname || opts.host - var port = opts.port - var path = opts.path || '/' - - // Necessary for IPv6 addresses - if (host && host.indexOf(':') !== -1) - host = '[' + host + ']' - - // 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 - - var req = new ClientRequest(opts) - if (cb) - req.on('response', cb) - return req -} - -http.get = function get (opts, cb) { - var req = http.request(opts, cb) - req.end() - return req -} - -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":84,"builtin-status-codes":7,"url":87,"xtend":104}],83:[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 -} - -// 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 - -}).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') - -var IncomingMessage = response.IncomingMessage -var rStates = response.readyStates - -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' - } -} - -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]) - }) - - 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) - - self.on('finish', function () { - self._onFinish() - }) -} - -inherits(ClientRequest, stream.Writable) - -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 - - self._headers[lowerName] = { - name: name, - value: value - } -} - -ClientRequest.prototype.getHeader = function (name) { - var self = this - return self._headers[name.toLowerCase()].value -} - -ClientRequest.prototype.removeHeader = function (name) { - var self = this - delete self._headers[name.toLowerCase()] -} - -ClientRequest.prototype._onFinish = function () { - var self = this - - if (self._destroyed) - return - var opts = self._opts - - 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() - } - } - - if (self._mode === 'fetch') { - var headers = keys(headersObj).map(function (name) { - return [headersObj[name].name, headersObj[name].value] - }) - - 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 - } - - // Can't set responseType on really old browsers - if ('responseType' in xhr) - xhr.responseType = self._mode.split(':')[0] - - if ('withCredentials' in xhr) - xhr.withCredentials = !!opts.withCredentials - - if (self._mode === 'text' && 'overrideMimeType' in xhr) - xhr.overrideMimeType('text/plain; charset=x-user-defined') - - foreach(keys(headersObj), function (name) { - xhr.setRequestHeader(headersObj[name].name, headersObj[name].value) - }) - - 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() - } - } - - xhr.onerror = function () { - if (self._destroyed) - return - self.emit('error', new Error('XHR error')) - } - - try { - xhr.send(body) - } catch (err) { - process.nextTick(function () { - self.emit('error', err) - }) - return - } - } -} - -/** - * 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 - } -} - -ClientRequest.prototype._onXHRProgress = function () { - var self = this - - if (!statusValid(self._xhr) || self._destroyed) - return - - if (!self._response) - self._connect() - - self._response._onXHRProgress() -} - -ClientRequest.prototype._connect = function () { - var self = this - - if (self._destroyed) - return - - self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode) - self.emit('response', self._response) -} - -ClientRequest.prototype._write = function (chunk, encoding, cb) { - var self = this - - self._body.push(chunk) - cb() -} - -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 -} - -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) -} - -ClientRequest.prototype.flushHeaders = function () {} -ClientRequest.prototype.setTimeout = function () {} -ClientRequest.prototype.setNoDelay = function () {} -ClientRequest.prototype.setSocketKeepAlive = function () {} - -// 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":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 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) - - self._mode = mode - self.headers = {} - self.rawHeaders = [] - self.trailers = {} - self.rawTrailers = [] - - // 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') - }) - }) - - if (mode === 'fetch') { - self._fetchResponse = response - - 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]) - } - - // 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() - - } else { - self._xhr = xhr - self._pos = 0 - - 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 - } - } -} - -inherits(IncomingMessage, stream.Readable) - -IncomingMessage.prototype._read = function () {} - -IncomingMessage.prototype._onXHRProgress = function () { - var self = this - - var xhr = self._xhr - - 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 - - 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 - } - - // 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'),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. - -var Buffer = require('buffer').Buffer; - -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. -// -// @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. -// -// 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; - - // 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; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - 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; - } - - 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); - } - - // or just emit the charStr - return charStr; -}; - -// 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; - - // 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]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - 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 base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; -} - -},{"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. - -var punycode = require('punycode'); - -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; - -exports.Url = Url; - -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 - -// 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]*$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // 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; -} - -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } - - var rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); - } - - // 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 (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { - - // 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 - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // 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; - } - - // 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); - } - - // 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] === ']'; - - // 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 (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } - - 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('.'); - } - - 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; - } - } - } - - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { - - // 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); - } - } - - - // 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 = '/'; - } - - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } - - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; -}; - -// 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(); -} - -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } - - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; - - 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 (this.query && - isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); - } - - var search = this.search || (query && ('?' + query)) || ''; - - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - - // 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 urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); -} - -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); -}; - -function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); -} - -Url.prototype.resolveObject = function(relative) { - if (isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; - } - - var result = new Url(); - Object.keys(this).forEach(function(k) { - result[k] = this[k]; - }, this); - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } - - // 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]; - }); - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; - } - - 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; - } - - 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; - } - - 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 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 (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 { - 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--; - } - } - - // 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 (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } - - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // 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(); - } - } - - mustEndAbs = mustEndAbs || (result.host && srcPath.length); - - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } - - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } - - //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; -}; - -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 isString(arg) { - return typeof arg === "string"; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isNull(arg) { - return arg === null; -} -function isNullOrUndefined(arg) { - return arg == null; -} - -},{"punycode":65,"querystring":68}],88:[function(require,module,exports){ -(function (global){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * 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 - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - 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); - } - - 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 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(' '); - } - - 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; -}; - - -// 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); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - 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); - } - - return deprecated; -}; - - -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; - - -// 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 stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -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; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - 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 base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // 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); - - 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(); - - 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'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -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 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'); - } - } - 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'); - } - } - 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'); - } - } - - return name + ': ' + str; -} - - -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); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[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; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -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; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 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(' '); -} - - -// 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)); -}; - - -/** - * 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'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - 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'),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') - -module.exports = collect - -function collect(stream, cb) { - - // 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. - } - - function get(name) { - if (!files.named[name]) { - files.named[name] = { - children: [], - } - } - return files.named[name] - } - - 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. - } - - if (file.path) { - // add file to named - var fo = get(file.path) - fo.file = file - - // add reference to file at parent - var po = get(Path.dirname(file.path)) - if (fo !== po) po.children.push(fo) - - // add name to names list. - files.paths.push(file.path) - } else { - files.unnamed.push({ file: file, children: [] }) - } - }) - - stream.on('error', function(err) { - cb && cb(err) - cb = null - }) - - stream.on('end', function() { - cb && cb(null, files) - cb = null - }) -} - -},{"path":62}],92:[function(require,module,exports){ -var x = module.exports = {} -x.randomString = randomString -x.cleanPath = cleanPath - -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 cleanPath(path, base) { - if (!path) return '' - if (!base) return path - - if (base[base.length-1] != '/') { - base += "/" - } - - // remove base from path - path = path.replace(base, '') - path = path.replace(/[\/]+/g, '/') - return path -} - -},{}],93:[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 - -},{"./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 - -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 w = new stream.Writable({objectMode: true}) - var r = new stream.PassThrough({objectMode: true}) - var mp = new Multipart(opts.boundary) - - // 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) - }) - - var out = duplexify.obj(w, r) - out.boundary = opts.boundary - return out -} - -function writePart(mp, file, cb) { - var c = file.contents - if (c === null) - c = emptyStream() - - mp.addPart({ - body: file.contents, - headers: headersForFile(file), - }) - cb(null) - // TODO: call cb when file.contents ends instead. -} - -function emptyStream() { - var s = new stream.PassThrough({objectMode: true}) - s.write(null) - return s -} - -function headersForFile(file) { - var fpath = common.cleanPath(file.path, file.base) - - var h = {} - h['Content-Disposition'] = 'file; filename="' +fpath+ '"' - - if (file.isDirectory()) { - h['Content-Type'] = 'text/directory' - } else { - h['Content-Type'] = 'application/octet-stream' - } - - return h -} - -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) -} - -},{"./common":92,"duplexify":12,"multipart-stream":57,"stream":81}],95:[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') -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 - - 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) - - // 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) - } - }) - - return out -} - -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])}) - } - - // 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)}) - } - - if (parts.length == 0) { // avoid multipart bug. - var s = streamForString("--" + boundary + "--\r\n") // close multipart. - s.boundary = boundary - return s - } - - // 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 -} - -function streamForPath(files, path) { - var o = files.named[path] - if (!o) { - throw new Error("no object for path. lib error.") - } - - if (!o.file) { // no vinyl file, so no need to process this one. - return - } - - // avoid processing twice. - if (o.done) return null // already processed it - o.done = true // mark it as already processed. - - return streamForWrapped(files, o) -} - -function streamForWrapped(files, f) { - if (f.file.isDirectory()) { - return multipartForDir(files, f) - } - - // stream for a file - if (f.children.length > 0) { // sanity check - throw new Error("non-directory has children. lib error") - } - - return f.file.contents -} - -function multipartForDir(files, dir) { - // we still write the boundary for the headers - dir.boundary = randomString() - - 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. - } - - 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) - - var h = {} - h['Content-Disposition'] = 'file; filename="' + fpath + '"' - - if (o.file.isDirectory()) { - h['Content-Type'] = 'multipart/mixed; boundary=' + o.boundary - } else { - h['Content-Type'] = 'application/octet-stream' - } - - return h -} - -},{"./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; - - // contents = stream, buffer, or null if not read - this.contents = file.contents || null; - - this._isVinyl = true; -} - -File.prototype.isBuffer = function() { - return isBuffer(this.contents); -}; - -File.prototype.isStream = function() { - return isStream(this.contents); -}; - -File.prototype.isNull = function() { - return isNull(this.contents); -}; - -// TODO: should this be moved to vinyl-fs? -File.prototype.isDirectory = function() { - return this.isNull() && this.stat && this.stat.isDirectory(); -}; - -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; - } - - // 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; - } - - var file = new File({ - cwd: this.cwd, - base: this.base, - stat: (this.stat ? cloneStats(this.stat) : null), - history: this.history.slice(), - contents: contents - }); - - // 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; -}; - -File.prototype.pipe = function(stream, opt) { - if (!opt) opt = {}; - if (typeof opt.end === 'undefined') opt.end = true; - - if (this.isStream()) { - return this.contents.pipe(stream, opt); - } - if (this.isBuffer()) { - if (opt.end) { - stream.end(this.contents); - } else { - stream.write(this.contents); - } - return stream; - } - - // isNull - if (opt.end) stream.end(); - return stream; -}; - -File.prototype.inspect = function() { - var inspect = []; - - // use relative path if possible - var filePath = (this.base && this.path) ? this.relative : this.path; - - if (filePath) { - inspect.push('"'+filePath+'"'); - } - - if (this.isBuffer()) { - inspect.push(this.contents.inspect()); - } - - if (this.isStream()) { - inspect.push(inspectStream(this.contents)); - } - - return ''; -}; - -File.isVinyl = function(file) { - return file && file._isVinyl === true; -}; - -// 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; - } -}); - -// 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.'); - } -}); - -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]; - }, - 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); - } - } -}); - -module.exports = File; - -}).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; - -module.exports = function(buf) { - var out = new Buffer(buf.length); - buf.copy(out); - return out; -}; - -},{"buffer":6}],98:[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":101}],99:[function(require,module,exports){ -module.exports = require('buffer').Buffer.isBuffer; - -},{"buffer":6}],100:[function(require,module,exports){ -module.exports = function(v) { - return v === null; -}; - -},{}],101:[function(require,module,exports){ -var Stream = require('stream').Stream; - -module.exports = function(o) { - return !!o && o instanceof Stream; -}; -},{"stream":81}],102:[function(require,module,exports){ -var indexOf = require('indexof'); - -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; - } -}; - -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); - } -}; - -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; - }; - } -}()); - -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']; - -function Context() {} -Context.prototype = {}; - -var Script = exports.Script = function NodeScript (code) { - if (!(this instanceof Script)) return new Script(code); - this.code = code; -}; - -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; - - 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); - - 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]; - } - }); - - forEach(globals, function (key) { - if (!(key in context)) { - defineProp(context, key, win[key]); - } - }); - - document.body.removeChild(iframe); - - return res; -}; - -Script.prototype.runInThisContext = function () { - return eval(this.code); // maybe... -}; - -Script.prototype.runInNewContext = function (context) { - var ctx = Script.createContext(context); - var res = this.runInContext(ctx); - - forEach(Object_keys(ctx), function (key) { - context[key] = ctx[key]; - }); - - return res; -}; - -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)); - }; -}); - -exports.createScript = function (code) { - return exports.Script(code); -}; - -exports.createContext = Script.createContext = function (context) { - var copy = new Context(); - if(typeof context === 'object') { - forEach(Object_keys(context), function (key) { - copy[key] = context[key]; - }); - } - return copy; -}; - -},{"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') - - 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 - } -} - -},{}],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" -} - -},{}],106:[function(require,module,exports){ -var pkg = require('../package.json') - -exports = module.exports = { - 'api-path': '/api/v0/', - 'user-agent': '/node-' + pkg.name + '/' + pkg.version + '/', - 'host': 'localhost', - 'port': '5001' -} - -},{"../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') - -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("/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') - -exports = module.exports = IpfsAPI - -function IpfsAPI (host_or_multiaddr, port) { - var self = this - - if (!(self instanceof IpfsAPI)) { - return new IpfsAPI(host_or_multiaddr, port) - } - - 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] - } - - // -- Internal - - function command (name) { - return function (opts, cb) { - if (typeof (opts) === 'function') { - cb = opts - opts = {} - } - return requestAPI(name, null, opts, null, cb) - } - } - - function argCommand (name) { - return function (arg, opts, cb) { - if (typeof (opts) === 'function') { - cb = opts - opts = {} - } - return requestAPI(name, arg, opts, null, cb) - } - } - - // -- Interface - - self.send = requestAPI - - self.add = function (files, opts, cb) { - if (typeof (opts) === 'function' && cb === undefined) { - cb = opts - opts = {} - } - - return requestAPI('add', null, opts, files, cb) - } - - self.cat = argCommand('cat') - self.ls = argCommand('ls') - - 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) - } - } - - self.update = { - apply: command('update'), - check: command('update/check'), - log: command('update/log') - } - - 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) - } - - 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')) - } - return requestAPI('block/put', null, null, file, cb) - } - } - - 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) - } - - self.pin = { - add: function (hash, opts, cb) { - if (typeof opts === 'function') { - cb = opts - opts = null - } - - requestAPI('pin/add', hash, opts, null, cb) - }, - remove: function (hash, opts, cb) { - if (typeof opts === 'function') { - cb = opts - opts = null - } - - 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) - } - } - - self.gateway = { - enable: command('gateway/enable'), - disable: command('gateway/disable') - } - - self.log = { - tail: function (cb) { - return requestAPI('log/tail', null, {enc: 'text'}, null, true, cb) - } - } - - self.name = { - publish: argCommand('name/publish'), - resolve: argCommand('name/resolve') - } - - self.Buffer = Buffer - - self.refs = argCommand('refs') - self.refs.local = command('refs/local') - - self.dht = { - findprovs: argCommand('dht/findprovs'), - - get: function (key, opts, cb) { - if (typeof (opts) === 'function' && !cb) { - cb = opts - opts = null - } - - 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')) - - if (res[0].Type === 5) { - cb(null, res[0].Extra) - } else { - cb(res) - } - }) - }, - - put: function (key, value, opts, cb) { - if (typeof (opts) === 'function' && !cb) { - cb = opts - opts = null - } - - return requestAPI('dht/put', [key, value], opts, null, cb) - } - } -} - -}).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') - -exports = module.exports = requestAPI - -function requestAPI (path, args, opts, files, buffer, cb) { - var query, stream, contentType - contentType = 'application/json' - - if (Array.isArray(path)) path = path.join('/') - - opts = opts || {} - - if (args && !Array.isArray(args)) args = [args] - if (args) opts.arg = args - - if (files) { - stream = getFilesStream(files, opts) - if (!stream.boundary) { - throw new Error('no boundary in multipart stream') - } - contentType = 'multipart/form-data; boundary=' + stream.boundary - } - - if (typeof buffer === 'function') { - cb = buffer - buffer = false - } - - // this option is only used internally, not passed to daemon - delete opts.followSymlinks - - opts['stream-channels'] = true - query = qs.stringify(opts) - - 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 - } - - 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'] - - if (stream && !buffer) return cb(null, res) - if (chunkedObjects && buffer) return cb(null, res) - - res.on('data', function (chunk) { - if (!chunkedObjects) { - data += chunk - return data - } - - try { - var obj = JSON.parse(chunk.toString()) - objects.push(obj) - } catch (e) { - chunkedObjects = false - data += chunk - } - }) - res.on('end', function () { - var parsed - - if (!chunkedObjects) { - try { - parsed = JSON.parse(data) - data = parsed - } catch (e) {} - } else { - data = objects - } - - 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) - }) - }) - - req.on('error', function (err) { - return cb(err, null) - }) - - if (stream) { - stream.pipe(req) - } else { - req.end() - } - - return req -} - -},{"./config":106,"./get-files-stream":107,"http":82,"querystring":68}],110:[function(require,module,exports){ -'use strict'; - -module.exports = { - src: require('./lib/src'), - dest: require('./lib/dest'), - symlink: require('./lib/symlink') -}; - -},{"./lib/dest":111,"./lib/src":124,"./lib/symlink":126}],111:[function(require,module,exports){ -(function (process){ -'use strict'; - -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 dest(outFolder, opt) { - if (!opt) { - opt = {}; - } - - function saveFile(file, enc, cb) { - prepareWrite(outFolder, file, opt, function(err, writePath) { - if (err) { - return cb(err); - } - writeContents(writePath, file, cb); - }); - } - - var saveStream = through2.obj(saveFile); - if (!opt.sourcemaps) { - return saveStream; - } - - var mapStream = sourcemaps.write(opt.sourcemaps.path, opt.sourcemaps); - var outputStream = duplexify.obj(mapStream, saveStream); - mapStream.pipe(saveStream); - - return outputStream; -} - -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'); - -function writeContents(writePath, file, cb) { - // if directory then mkdirp it - if (file.isDirectory()) { - return writeDir(writePath, file, written); - } - - // stream it to disk yo - if (file.isStream()) { - return writeStream(writePath, file, written); - } - - // write it as a symlink - if (file.symlink) { - return writeSymbolicLink(writePath, file, written); - } - - // 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); - } - - if (!file.stat || typeof file.stat.mode !== 'number' || file.symlink) { - return complete(); - } - - 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); - }); - } - - 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" - } - - // Otherwise, this is a fatal error - return true; - } -} - -module.exports = writeContents; - -},{"./writeBuffer":113,"./writeDir":114,"./writeStream":115,"./writeSymbolicLink":116}],113:[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); -} - -module.exports = writeBuffer; - -}).call(this,require('_process')) -},{"_process":64,"fs":4,"graceful-fs":185}],114:[function(require,module,exports){ -'use strict'; - -var mkdirp = require('mkdirp'); - -function writeDir(writePath, file, cb) { - mkdirp(writePath, file.stat.mode, cb); -} - -module.exports = writeDir; - -},{"mkdirp":230}],115:[function(require,module,exports){ -(function (process){ -'use strict'; - -var streamFile = require('../../src/getContents/streamFile'); -var fs = process.browser ? require('fs') : require('graceful-fs'); - -function writeStream(writePath, file, cb) { - var opt = { - mode: file.stat.mode, - flag: file.flag - }; - - var outStream = fs.createWriteStream(writePath, opt); - - file.contents.once('error', complete); - outStream.once('error', complete); - outStream.once('finish', success); - - file.contents.pipe(outStream); - - function success() { - streamFile(file, {}, complete); - } - - // cleanup - function complete(err) { - file.contents.removeListener('error', cb); - outStream.removeListener('error', cb); - outStream.removeListener('finish', success); - cb(err); - } -} - -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'; - -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); - }); -} - -module.exports = writeSymbolicLink; - -}).call(this,require('_process')) -},{"_process":64,"fs":4,"graceful-fs":185}],117:[function(require,module,exports){ -'use strict'; - -var filter = require('through2-filter'); - -module.exports = function(d) { - var isValid = typeof d === 'number' || - d instanceof Number || - d instanceof Date; - - 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'; - -var assign = require('object-assign'); -var path = require('path'); -var mkdirp = require('mkdirp'); -var fs = process.browser ? require('fs') : require('graceful-fs'); - -function booleanOrFunc(v, file) { - if (typeof v !== 'boolean' && typeof v !== 'function') { - return null; - } - - return typeof v === 'boolean' ? v : v(file); -} - -function stringOrFunc(v, file) { - if (typeof v !== 'string' && typeof v !== 'function') { - return null; - } - - return typeof v === 'string' ? v : v(file); -} - -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'); - } - - var writePath = path.resolve(basePath, file.relative); - var writeFolder = path.dirname(writePath); - - // 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; - - // mkdirp the folder the file is going in - mkdirp(writeFolder, options.dirMode, function(err){ - if (err) { - return cb(err); - } - cb(null, writePath); - }); -} - -module.exports = prepareWrite; - -}).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'; - -var fs = process.browser ? require('fs') : require('graceful-fs'); -var stripBom = require('strip-bom'); - -function bufferFile(file, opt, cb) { - fs.readFile(file.path, function(err, data) { - if (err) { - return cb(err); - } - - if (opt.stripBOM){ - file.contents = stripBom(data); - } else { - file.contents = data; - } - - cb(null, file); - }); -} - -module.exports = bufferFile; - -}).call(this,require('_process')) -},{"_process":64,"fs":4,"graceful-fs":185,"strip-bom":233}],120:[function(require,module,exports){ -'use strict'; - -var through2 = require('through2'); -var readDir = require('./readDir'); -var readSymbolicLink = require('./readSymbolicLink'); -var bufferFile = require('./bufferFile'); -var streamFile = require('./streamFile'); - -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); - } - - // process symbolic links included with `followSymlinks` option - if (file.stat && file.stat.isSymbolicLink()) { - return readSymbolicLink(file, opt, cb); - } - - // read and pass full contents - if (opt.buffer !== false) { - return bufferFile(file, opt, cb); - } - - // dont buffer anything - just pass streams - return streamFile(file, opt, cb); - }); -} - -module.exports = getContents; - -},{"./bufferFile":119,"./readDir":121,"./readSymbolicLink":122,"./streamFile":123,"through2":248}],121:[function(require,module,exports){ -'use strict'; - -function readDir(file, opt, cb) { - // do nothing for now - cb(null, file); -} - -module.exports = readDir; - -},{}],122:[function(require,module,exports){ -(function (process){ -'use strict'; - -var fs = process.browser ? require('fs') : require('graceful-fs'); - -function readLink(file, opt, cb) { - fs.readlink(file.path, function (err, target) { - if (err) { - return cb(err); - } - - // store the link target path - file.symlink = target; - - return cb(null, file); - }); -} - -module.exports = readLink; - -}).call(this,require('_process')) -},{"_process":64,"fs":4,"graceful-fs":185}],123:[function(require,module,exports){ -(function (process){ -'use strict'; - -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); -} - -module.exports = streamFile; - -}).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 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 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); - } - - var globStream = gs.create(glob, options); - - var outputStream = globStream - .pipe(resolveSymlinks(options)) - .pipe(through.obj(createFile)); - - if (options.since != null) { - outputStream = outputStream - .pipe(filterSince(options.since)); - } - - if (options.read !== false) { - outputStream = outputStream - .pipe(getContents(options)); - } - - 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; -} - -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; - - if (!stat.isSymbolicLink() || !options.followSymlinks) { - return cb(null, globFile); - } - - fs.realpath(globFile.path, function (err, filePath) { - if (err) { - return cb(err); - } - - globFile.base = path.dirname(filePath); - globFile.path = filePath; - - // recurse to get real file stat - resolveFile(globFile, enc, cb); - }); - }); - } - - return through2.obj(resolveFile); -} - -module.exports = resolveSymlinks; - -}).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 through2 = require('through2'); -var fs = process.browser ? require('fs') : require('graceful-fs'); -var prepareWrite = require('../prepareWrite'); - -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); - }); - }); - } - - var stream = through2.obj(linkFile); - // TODO: option for either backpressure or lossy - stream.resume(); - return stream; -} - -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; - -function ctor(options, transform) { - util.inherits(FirstChunk, Transform); - - if (typeof options === 'function') { - transform = options; - options = {}; - } - - if (typeof transform !== 'function') { - throw new Error('transform function required'); - } - - function FirstChunk(options2) { - if (!(this instanceof FirstChunk)) { - return new FirstChunk(options2); - } - - Transform.call(this, options2); - - this._firstChunk = true; - this._transformCalled = false; - this._minSize = options.minSize; - } - - FirstChunk.prototype._transform = function (chunk, enc, cb) { - this._enc = enc; - - if (this._firstChunk) { - this._firstChunk = false; - - if (this._minSize == null) { - transform.call(this, chunk, enc, cb); - this._transformCalled = true; - return; - } - - this._buffer = chunk; - cb(); - return; - } - - if (this._minSize == null) { - this.push(chunk); - cb(); - return; - } - - if (this._buffer.length < this._minSize) { - this._buffer = Buffer.concat([this._buffer, chunk]); - cb(); - return; - } - - 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; - } - - this.push(chunk); - cb(); - }; - - FirstChunk.prototype._flush = function (cb) { - if (!this._buffer) { - cb(); - return; - } - - if (this._transformCalled) { - this.push(this._buffer); - cb(); - } else { - transform.call(this, this._buffer.slice(), this._enc, cb); - } - }; - - return FirstChunk; -} - -module.exports = function () { - return ctor.apply(ctor, arguments)(); -}; - -module.exports.ctor = ctor; - -}).call(this,require("buffer").Buffer) -},{"buffer":6,"stream":81,"util":90}],144:[function(require,module,exports){ -(function (process){ -/*jslint node: true */ - -'use strict'; - -var through2 = require('through2'); -var Combine = require('ordered-read-streams'); -var unique = require('unique-stream'); - -var glob = require('glob'); -var Minimatch = require('minimatch').Minimatch; -var glob2base = require('glob2base'); -var path = require('path'); - -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); - - // create globbing stuff - var globber = new glob.Glob(ourGlob, opt); - - // extract base path from glob - var basePath = opt.base || glob2base(globber); - - // create stream and map events from globber to it - var stream = through2.obj(negatives.length ? filterNegatives : undefined); - - var found = false; - - 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')); - } - - stream.end(); - }); - globber.on('match', function(filename) { - found = true; - - stream.write({ - cwd: opt.cwd, - base: basePath, - path: path.resolve(opt.cwd, filename) - }); - }); - - return stream; - - function filterNegatives(filename, enc, cb) { - var matcha = isMatch.bind(null, filename); - if (negatives.every(matcha)) { - cb(null, filename); // pass - } else { - cb(); // ignore - } - } - }, - - // 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; - - // only one glob no need to aggregate - if (!Array.isArray(globs)) globs = [globs]; - - var positives = []; - var negatives = []; - - globs.forEach(function(glob, index) { - if (typeof glob !== 'string' && !(glob instanceof RegExp)) { - throw new Error('Invalid glob at index ' + index); - } - - var globArray = isNegative(glob) ? negatives : positives; - - // create Minimatch instances for negative glob patterns - if (globArray === negatives && typeof glob === 'string') { - glob = new Minimatch(unrelative(opt.cwd, glob), opt); - } - - globArray.push({ - index: index, - glob: glob - }); - }); - - if (positives.length === 0) throw new Error('Missing positive glob'); - - // 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); - - // 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); - - aggregate.on('error', function (err) { - returnStream.emit('error', err); - }); - - return returnStream; - - function streamFromPositive(positive) { - var negativeGlobs = negatives.filter(indexGreaterThan(positive.index)).map(toGlob); - return gs.createStream(positive.glob, negativeGlobs, opt); - } - } -}; - -function isMatch(file, matcher) { - if (matcher instanceof Minimatch) return matcher.match(file.path); - if (matcher instanceof RegExp) return matcher.test(file.path); -} - -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); -} - -function indexGreaterThan(index) { - return function(obj) { - return obj.index > index; - }; -} - -function toGlob(obj) { - return obj.glob; -} - -function globIsSingular(glob) { - var globSet = glob.minimatch.set; - - if (globSet.length !== 1) { - 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) -} - -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 alphasort (a, b) { - return a.localeCompare(b) -} - -function setupIgnores (self, options) { - self.ignore = options.ignore || [] - - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] - - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) - } -} - -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern) - } - - return { - matcher: new Minimatch(pattern), - gmatcher: gmatcher - } -} - -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) - - 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 - } - - 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 -} - -// 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 finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) - - 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 - }) - } - } - - if (!nou) - all = Object.keys(all) - - if (!self.nosort) - all = all.sort(self.nocase ? alphasorti : alphasort) - - // 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 (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) - - self.found = all -} - -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) === '/' - - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) - - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] - } - } - - 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 -} - - -// 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)) - }) -} - -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false - - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) -} - -}).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 - -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 once = require('once') - -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} - - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) - } - - 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 - - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true - } - - return false -} - -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) - } - - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) - - setopts(this, pattern, options) - this._didRealPath = false - - // process each pattern in the minimatch set - var n = this.minimatch.set.length - - // 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) - - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) - } - - var self = this - var n = this.minimatch.set.length - this._processing = 0 - this.matches = new Array(n) - - this._emitQueue = [] - this._processQueue = [] - this.paused = false - - if (this.noprocess) - return this - - if (n === 0) - return done() - - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) - } - - function done () { - --self._processing - if (self._processing <= 0) - self._finish() - } -} - -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) -} - -Glob.prototype._realpath = function () { - if (this._didRealpath) - return - - this._didRealpath = true - - var n = this.matches.length - if (n === 0) - return this._finish() - - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) - - function next () { - if (--n === 0) - self._finish() - } -} - -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() - - var found = Object.keys(matchset) - var self = this - var n = found.length - - if (n === 0) - return cb() - - 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 - - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) -} - -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} - -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} - -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} - -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } -} - -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]) - } - } - } -} - -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') - - if (this.aborted) - return - - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return - } - - //console.error('PROCESS %d', this._processing, pattern) - - // 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, cb) - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - - 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 - } - - var remain = pattern.slice(n) - - // 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 abs = this._makeAbs(read) - - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() - - 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) -} - -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) - }) -} - -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() - - // 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) === '.' - - 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) - } - } - - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) - - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() - - // 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. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - - 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() - } - - // 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() -} - -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return - - if (this.matches[index][e]) - return - - if (isIgnored(this, e)) - return - - if (this.paused) { - this._emitQueue.push([index, e]) - return - } - - var abs = this._makeAbs(e) - - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } - - if (this.mark) - e = this._mark(e) - - this.matches[index][e] = true - - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) - - this.emit('match', e) -} - -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return - - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) - - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) - - 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) - } -} - -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return - - 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 (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() - - if (Array.isArray(c)) - return cb(null, c) - } - - 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) - else - self._readdirEntries(abs, entries, cb) - } -} - -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 - } - } - - this.cache[abs] = entries - return cb(null, entries) -} - -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 - } - - return cb() -} - -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) - }) -} - - -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() - - // 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 isSym = this.symlinks[abs] - var len = entries.length - - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() - - 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() -} - -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) { - - //console.error('ps2', prefix, exists) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() - - 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 += '/' - } - } - - 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) === '/' - - if (f.length > this.maxLength) - return cb() - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - - if (Array.isArray(c)) - c = 'DIR' - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) - - 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. - } - - 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) - } - } - - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - fs.lstat(abs, statcb) - - 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) - } - } -} - -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er) { - this.statCache[abs] = false - return cb() - } - - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat - - if (abs.slice(-1) === '/' && !stat.isDirectory()) - return cb(null, false, stat) - - var c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c - - if (needDir && c !== 'DIR') - return cb() - - return cb(null, c, stat) -} - -}).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') - -module.exports = wrappy(inflight) - -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) - } -} - -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] - } - }) -} - -function slice (args) { - var length = args.length - var array = [] - - for (var i = 0; i < length; i++) array[i] = args[i] - return array -} - -}).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) !== ':'; - - // 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":64}],153:[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 - -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') - - return new GlobSync(pattern, options).found -} - -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') - - 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 (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) - - setopts(this, pattern, options) - - if (this.noprocess) - return this - - 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() -} - -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) -} - - -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 - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - - 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 - } - - var remain = pattern.slice(n) - - // 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 abs = this._makeAbs(read) - - //if ignored, skip processing - if (childrenIgnored(this, read)) - return - - 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) -} - - -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return - - // 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) === '.' - - 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) - } - } - - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return - - // 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. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - 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 - } - - // 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) - } -} - - -GlobSync.prototype._emitMatch = function (index, e) { - var abs = this._makeAbs(e) - if (this.mark) - e = this._mark(e) - - if (this.matches[index][e]) - return - - 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) -} - - -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) - - var entries - var lstat - var stat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - // lstat failed, doesn't exist - return null - } - - var isSym = lstat.isSymbolicLink() - this.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()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) - - return entries -} - -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries - - 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 - } - - try { - return this._readdirEntries(abs, fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null - } -} - -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 - } - } - - this.cache[abs] = entries - - // mark and cache dir-ness - return entries -} - -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 - - 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 - } -} - -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - - var entries = this._readdir(abs, inGlobStar) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return - - // 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) - - var len = entries.length - var isSym = this.symlinks[abs] - - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return - - 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) - - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } -} - -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 it doesn't exist, then just mark the lack of results - if (!exists) - return - - 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 += '/' - } - } - - 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) === '/' - - if (f.length > this.maxLength) - return false - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - - if (Array.isArray(c)) - c = 'DIR' - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c - - if (needDir && c === 'FILE') - return false - - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - return false - } - - if (lstat.isSymbolicLink()) { - try { - stat = fs.statSync(abs) - } catch (er) { - stat = lstat - } - } else { - stat = lstat - } - } - - this.statCache[abs] = stat - - var c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c - - if (needDir && c !== 'DIR') - return false - - return c -} - -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} - -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} - -}).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'; - -var path = require('path'); -var findIndex = require('find-index'); - -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]); - } - - // last one is a file or specific dir - // so we pop it off - if (flat) { - out.pop(); - } - return out; -}; - -var flattenExpansion = function(set) { - var first = set[0]; - var toCompare = set.slice(1); - - // find index where the diff is - var idx = findIndex(first, function(v, idx){ - if (typeof v !== 'string') { - return true; - } - - var matched = toCompare.every(function(arr){ - return v === arr[idx]; - }); - - 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'); - } - - 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; - } - } - } - - return -1; -} - -module.exports = findIndex - -},{}],156:[function(require,module,exports){ -module.exports = minimatch -minimatch.Minimatch = Minimatch - -var path = { sep: '/' } -try { - path = require('path') -} catch (er) {} - -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = require('brace-expansion') - -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' - -// * => any number of characters -var star = qmark + '*?' - -// ** 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})($|\\\/)).)*?' - -// 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('().*{}+?[]^$\\!') - -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} - -// normalizes slashes. -var slashSplit = /\/+/ - -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} - -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 -} - -minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch - - var orig = minimatch - - var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) - } - - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } - - return m -} - -Minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch - return minimatch.defaults(def).Minimatch -} - -function minimatch (p, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } - - if (!options) options = {} - - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } - - // "" only matches "" - if (pattern.trim() === '') return p === '' - - return new Minimatch(pattern, options).match(p) -} - -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } - - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } - - if (!options) options = {} - pattern = pattern.trim() - - // windows support: need to use /, not \ - if (path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } - - 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 () {} - -Minimatch.prototype.make = make -function make () { - // don't do it more than once. - if (this._made) return - - var pattern = this.pattern - var options = this.options - - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } - - // step 1: figure out negation, etc. - this.parseNegate() - - // step 2: expand braces - var set = this.globSet = this.braceExpand() - - if (options.debug) this.debug = console.error - - this.debug(this.pattern, set) - - // 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) - }) - - this.debug(this.pattern, set) - - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) - - this.debug(this.pattern, set) - - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) - - this.debug(this.pattern, set) - - this.set = set -} - -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 - - if (options.nonegate) return - - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } - - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} - -// 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) -} - -Minimatch.prototype.braceExpand = braceExpand - -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } - - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern - - if (typeof pattern === 'undefined') { - throw new Error('undefined pattern') - } - - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } - - return expand(pattern) -} - -// 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 - - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' - - 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 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 - } - } - - 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) - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } - - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case '\\': - clearStateChar() - escaping = true - continue - - // 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) - - // 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 - } - - 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 - - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } - - 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 - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } - - clearStateChar() - re += '|' - continue - - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() - - if (inClass) { - re += '\\' + c - continue - } - - inClass = true - classStart = i - reClassStart = re.length - re += c - continue - - 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 - } - - // 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 - } - } - - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } - - re += c - - } // switch - } // for - - // 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] - } - - // 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 = '\\' - } - - // 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 + '|' - }) - - this.debug('tail=%j\n %s', tail, tail) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type - - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } - - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } - - // 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 - } - - // 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) - - nlLast += nlAfter - - // 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 dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' - } - 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 - } - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } - - // 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) - - regExp._glob = pattern - regExp._src = re - - return regExp -} - -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} - -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - - // 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 (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') - - // 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 + ').*$' - - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false - } - 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) - } - 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 === '' - - if (f === '/' && partial) return true - - var options = this.options - - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } - - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) - - // 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. - - var set = this.set - this.debug(this.pattern, 'set', set) - - // 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 - } - - 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 - } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} - -// 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 - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) - - this.debug('matchOne', file.length, pattern.length) - - 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] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // 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 - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - - // 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 - } - - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } - - // 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 - } - - // 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 (!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/* - - // 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 - } - - // should be unreachable. - throw new Error('wtf?') -} - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} - -},{"brace-expansion":157,"path":62}],157:[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":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; - - 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; - } -} - -},{}],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); - } - return res; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -},{}],160:[function(require,module,exports){ -var Readable = require('readable-stream').Readable; -var isReadable = require('isstream').isReadable; -var util = require('util'); - - -function addStream(streams, stream) -{ - if(!isReadable(stream)) throw new Error('All input streams must be readable'); - - var self = this; - - stream._buffer = []; - - stream.on('readable', function() - { - var chunk = stream.read(); - if (chunk === null) - return; - - if(this === streams[0]) - self.push(chunk); - - else - this._buffer.push(chunk); - }); - - 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()); - - streams.shift(); - } - - if(!streams.length) self.push(null); - }); - - stream.on('error', this.emit.bind(this, 'error')); - - streams.push(stream); -} - - -function OrderedStreams(streams, options) { - if (!(this instanceof(OrderedStreams))) { - return new OrderedStreams(streams, options); - } - - streams = streams || []; - options = options || {}; - - options.objectMode = true; - - Readable.call(this, options); - - - if(!Array.isArray(streams)) streams = [streams]; - if(!streams.length) return this.push(null); // no streams, close - - - var addStream_bind = addStream.bind(this, []); - - - streams.forEach(function(item) - { - if(Array.isArray(item)) - item.forEach(addStream_bind); - - else - addStream_bind(item); - }); -} -util.inherits(OrderedStreams, Readable); - -OrderedStreams.prototype._read = function () {}; - - -module.exports = OrderedStreams; - -},{"isstream":161,"readable-stream":171,"util":90}],161:[function(require,module,exports){ -var stream = require('stream') - - -function isStream (obj) { - return obj instanceof stream.Stream -} - - -function isReadable (obj) { - return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' -} - - -function isWritable (obj) { - return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' -} - - -function isDuplex (obj) { - return isReadable(obj) && isWritable(obj) -} - - -module.exports = isStream -module.exports.isReadable = isReadable -module.exports.isWritable = isWritable -module.exports.isDuplex = isDuplex - -},{"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. - -// 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; - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -} -/**/ - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -util.inherits(Duplex, Readable); - -forEach(objectKeys(Writable.prototype), function(method) { - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; -}); - -function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) - this.readable = false; - - if (options && options.writable === false) - this.writable = false; - - 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; - - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(this.end.bind(this)); -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -}).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. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -module.exports = PassThrough; - -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); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); -}; - -},{"./_stream_transform":165,"core-util-is":167,"inherits":168}],164:[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. - -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; - - 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 = ''; - } - } - - 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); - - if (state.needReadable) - emitReadable(stream); - } - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - - - -// 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); -} - -// 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; -}; - -// 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; -} - -function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; - - if (state.objectMode) - return n === 0 ? 0 : 1; - - 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; - } - - if (n <= 0) - return 0; - - // 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); - - // 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; - } - - 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; - } - - 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; - } - - // 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 we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // 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); - } - - // 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 (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 _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; - - if (util.isNull(ret)) { - state.needReadable = true; - n = 0; - } - - 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); - - if (!util.isNull(ret)) - this.emit('data', ret); - - return ret; -}; - -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; -} - - -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; - - // 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) - process.nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} - - -// 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); - }); - } -} - -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')); -}; - -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; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - 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(); - } - } - - 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); - - 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); - - // 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(); - } - - 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 (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]; - - - - // 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 unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // 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(); - } - - return dest; -}; - -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; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; - - // 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; - - 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. - - 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; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; -}; - -// 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 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 (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); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -// 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; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(function() { - resume_(stream, state); - }); - } -} - -function resume_(stream, state) { - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) - stream.read(0); -} - -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 flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - if (state.flowing) { - do { - var chunk = stream.read(); - } while (null !== chunk && state.flowing); - } -} - -// 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() { - debug('wrapped end'); - 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) { - debug('wrapped data'); - if (state.decoder) - chunk = state.decoder.write(chunk); - if (!chunk || !state.objectMode && !chunk.length) - return; - - 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 (util.isFunction(stream[i]) && util.isUndefined(this[i])) { - 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) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - - - -// 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); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } - } - } - - 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'); - - 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'); - } - }); - } -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} - -}).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. - - -// 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; - -var Duplex = require('./_stream_duplex'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(Transform, Duplex); - - -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (!util.isNullOrUndefined(data)) - stream.push(data); - - if (cb) - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} - - -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - - Duplex.call(this, options); - - this._transformState = new TransformState(options, this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // 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); - }); - else - done(stream); - }); -} - -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'); -}; - -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 (!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 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; - - 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":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. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, cb), and it'll handle all -// the drain event emission and buffering. - -module.exports = Writable; - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Writable.WritableState = WritableState; - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Stream = require('stream'); - -util.inherits(Writable, Stream); - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} - -function WritableState(options, stream) { - var Duplex = require('./_stream_duplex'); - - options = options || {}; - - // 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; - - // 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, because 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; - - // 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.buffer = []; - - // 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; -} - -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; - - 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, 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; - } - return valid; -} - -Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (util.isFunction(encoding)) { - cb = encoding; - encoding = null; - } - - if (util.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; - - if (!util.isFunction(cb)) - cb = function() {}; - - if (state.ended) - writeAfterEnd(this, state, 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; - - state.corked++; -}; - -Writable.prototype.uncork = function() { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && - !state.corked && - !state.finished && - !state.bufferProcessing && - state.buffer.length) - clearBuffer(this, state); - } -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - util.isString(chunk)) { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} - -// 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; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; - - if (state.writing || state.corked) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - 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) { - if (sync) - process.nextTick(function() { - state.pendingcb--; - cb(er); - }); - else { - state.pendingcb--; - cb(er); - } - - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -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 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 there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - - 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); - - // 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); - } - }); - - // 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); - - // 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 (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; - } - - state.bufferProcessing = false; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); - -}; - -Writable.prototype._writev = null; - -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; - } - - if (!util.isNullOrUndefined(chunk)) - this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // 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 prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } -} - -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; -} - -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; -} - -}).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'); - -},{"./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: -// -// 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 = 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; - -util.inherits(Readable, Stream); - -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" - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = 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; - - // 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; - - // 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; - - // 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) { - if (!(this instanceof Readable)) - return new Readable(options); - - 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 (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } - } - - 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 (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); - - // 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); - } - - if (state.needReadable) - emitReadable(stream); - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - - - -// 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); -} - -// backwards compatibility. -Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; -}; - -// 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; -} - -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; - - // 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); - - // 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; - } - - return n; -} - -// 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; - - 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)) { - emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - ret = null; - - // 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; - } - - if (state.length === 0) - endReadable(this); - - return ret; - } - - // 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 we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; - - // 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; - - 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; - } - - // 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); - - if (n > 0) - ret = fromList(n, state); - else - ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } - - 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 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; -}; - -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; -} - - -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; - - // 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); -} - -// 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; - - state.emittedReadable = true; - if (state.sync) - process.nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); -} - -function emitReadable_(stream) { - stream.emit('readable'); -} - - -// 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); - }); - } -} - -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; -} - -// 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; - } - state.pipesCount += 1; - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - process.nextTick(endFn); - else - src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); - } - - function 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); - - 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(); - } - - // 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]; - - - - // 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); - - function unpipe() { - src.unpipe(dest); - } - - // 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) { - // 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); - - state.flowing = true; - process.nextTick(function() { - flow(src); - }); - } - - return dest; -}; - -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; - - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } - } - - 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); - - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; - } - - // 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; - - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; - } - - // 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 pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } -} - - -Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; - - // 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; - - if (!dest) - dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - 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; - - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; -}; - -// 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 (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); - - 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); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -// 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'); -}; - -Readable.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); -}; - -function emitDataEvents(stream, startPaused) { - var state = stream._readableState; - - 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; - - stream.on('readable', function() { - readable = true; - - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); - - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); - - stream.pause = function() { - paused = true; - this.emit('pause'); - }; - - stream.resume = function() { - paused = false; - if (readable) - process.nextTick(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; - - // 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); - - // 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 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 (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(); - } - }; - - return self; -}; - - - -// 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); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } - } - } - - 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'); - - 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'); - } - }); - } -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} - -}).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){ -// 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. - - -// 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; - -var Duplex = require('./_stream_duplex'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(Transform, Duplex); - - -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) - stream.push(data); - - if (cb) - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} - - -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - - Duplex.call(this, options); - - var ts = this._transformState = new TransformState(options, this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // 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('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); -} - -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'); -}; - -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 rs = stream._readableState; - var ts = stream._transformState; - - 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":172,"core-util-is":176,"inherits":177}],175:[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. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, cb), and it'll handle all -// the drain event emission and buffering. - -module.exports = Writable; - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Writable.WritableState = WritableState; - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Stream = require('stream'); - -util.inherits(Writable, Stream); - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} - -function WritableState(options, stream) { - options = options || {}; - - // 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; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - // 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; - - // 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; - - // 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; - - // 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.buffer = []; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; -} - -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; - - 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, 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 (!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; -} - -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 = function() {}; - - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); - - return ret; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} - -// 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; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; - - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); - - return ret; -} - -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; -} - -function onwriteError(stream, state, sync, er, cb) { - if (sync) - process.nextTick(function() { - cb(er); - }); - else - cb(er); - - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -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.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); - - if (sync) { - process.nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -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 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; - - 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; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); -}; - -Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - 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'); - } - 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); - } - state.ended = true; -} - -}).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') - -function DestroyableTransform(opts) { - Transform.call(this, opts) - this._destroyed = false -} - -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') - }) -} - -// a noop _transform function -function noop (chunk, enc, callback) { - callback(null, chunk) -} - - -// 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) - } -} - - -// 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 - - if (flush) - t2._flush = flush - - return t2 -}) - -}).call(this,require('_process')) -},{"_process":64,"readable-stream/transform":180,"util":90,"xtend":181}],183:[function(require,module,exports){ -(function (global){ -'use strict'; - -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]; - }; -} - -module.exports = unique; -function unique(propName, keyStore) { - keyStore = keyStore || new ES6Set(); - - var keyfn = JSON.stringify; - if (typeof propName === 'string') { - keyfn = prop(propName); - } else if (typeof propName === 'function') { - keyfn = propName; - } - - return filter(function (data) { - var key = keyfn(data); - - if (keyStore.has(key)) { - return false; - } - - keyStore.add(key); - return true; - }); -} - -}).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') - -module.exports = clone(fs) - -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj - - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) - - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) - - return copy -} - -},{"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') - -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) - }) -} - -module.exports = patch(require('./fs.js')) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) { - module.exports = patch(fs) -} - -// 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) - -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 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() - } - }) - } - } - - 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() - } - }) - } - } - - 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() - } - }) - } - } - - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, cb) { - return go$readdir(path, cb) - - function go$readdir () { - return fs$readdir(path, function (err, files) { - if (files && files.sort) - files.sort(); // Backwards compatibility with graceful-fs. - - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [path, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - - - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } - - var fs$ReadStream = fs.ReadStream - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - - 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) - } - - 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 WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } - - 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) - } - }) - } - - function createReadStream (path, options) { - return new ReadStream(path, options) - } - - function createWriteStream (path, options) { - return new WriteStream(path, options) - } - - 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 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() - } - }) - } - } - - return fs -} - -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]) - } -} - -}).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 legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } - - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); - - 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; - - 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]; - } - - if (this.encoding) this.setEncoding(this.encoding); - - 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'); - } - - if (this.start > this.end) { - throw new Error('start must be <= end'); - } - - this.pos = this.start; - } - - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } - - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } - - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } - - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); - - Stream.call(this); - - this.path = path; - this.fd = null; - this.writable = true; - - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; - - 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]; - } - - 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; - } - - this.busy = false; - this._queue = []; - - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } -} - -}).call(this,require('_process')) -},{"_process":64,"stream":81}],187:[function(require,module,exports){ -(function (process){ -var fs = require('./fs.js') -var constants = require('constants') - -var origCwd = process.cwd -var cwd = null -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} - -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) -} - -module.exports = patch - -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) - } - - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } - - // 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) - - // 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 () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - process.nextTick(cb) - } - fs.lchownSync = function () {} - } - - // 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) - } - } - 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 - } - } - }})(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) - }) - }) - }) - } - - 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) - } - } - 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) - }) - }) - }) - } - - 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 - } - - } else { - fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) } - fs.lutimesSync = function () {} - } -} - -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) - }) - } -} - -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 - } - } -} - -// 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 - } - - return false -} - -}).call(this,require('_process')) -},{"./fs.js":184,"_process":64,"constants":10}],188:[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'); - -var PLUGIN_NAME = 'gulp-sourcemap'; -var urlRegex = /^https?:\/\//; - -/** - * Initialize source mapping chain - */ -module.exports.init = function init(options) { - function sourceMapInit(file, encoding, callback) { - /*jshint validthis:true */ - - if (file.isNull()) { - this.push(file); - return callback(); - } - - if (file.isStream()) { - return callback(new Error(PLUGIN_NAME + '-init: Streaming not supported')); - } - - var fileContent = file.contents.toString(); - var sourceMap; - - if (options && options.loadMaps) { - var sourcePath = ''; //root path for the sources in the map - - // 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); - - 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'; - } - - // sources in external map are relative to map file - sourcePath = path.dirname(mapFile); - - try { - sourceMap = JSON.parse(stripBom(fs.readFileSync(mapFile, 'utf8'))); - } catch(e) {} - } - - // 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)); - - 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); - } - - // if current file: use content - if (absPath === file.path) { - sourceContent = fileContent; - - // 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; - } - }); - - // remove source map comment from source - file.contents = new Buffer(fileContent, 'utf8'); - } - } - - if (!sourceMap) { - // Make an empty source map - sourceMap = { - version : 3, - names: [], - mappings: '', - sources: [unixStylePath(file.relative)], - sourcesContent: [fileContent] - }; - } - - sourceMap.file = unixStylePath(file.relative); - file.sourceMap = sourceMap; - - this.push(file); - callback(); - } - - return through.obj(sourceMapInit); -}; - -/** - * 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 || {}; - - // set defaults for options if unset - if (options.includeContent === undefined) - options.includeContent = true; - if (options.addComment === undefined) - options.addComment = true; - - function sourceMapWrite(file, encoding, callback) { - /*jshint validthis:true */ - - if (file.isNull() || !file.sourceMap) { - this.push(file); - return callback(); - } - - if (file.isStream()) { - return callback(new Error(PLUGIN_NAME + '-write: Streaming not supported')); - } - - 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 (options.sourceRoot) { - if (typeof options.sourceRoot === 'function') { - sourceMap.sourceRoot = options.sourceRoot(file); - } else { - sourceMap.sourceRoot = options.sourceRoot; - } - } - - if (options.includeContent) { - sourceMap.sourcesContent = sourceMap.sourcesContent || []; - - // 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/'; - } else { - delete sourceMap.sourcesContent; - } - - var extension = file.relative.split('.').pop(); - var commentFormatter; - - 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 ""; }; - } - - 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); - - comment = commentFormatter(unixStylePath(path.join(path.relative(path.dirname(file.path), file.base), destPath, file.relative) + '.map')); - - if (options.sourceMappingURLPrefix) { - if (typeof options.sourceMappingURLPrefix === 'function') { - sourceMappingURLPrefix = options.sourceMappingURLPrefix(file); - } else { - sourceMappingURLPrefix = options.sourceMappingURLPrefix; - } - comment = comment.replace(/sourceMappingURL=\.*/, 'sourceMappingURL=' + sourceMappingURLPrefix); - } - } - - // append source map comment - if (options.addComment) - file.contents = Buffer.concat([file.contents, new Buffer(comment)]); - - this.push(file); - callback(); - } - - return through.obj(sourceMapWrite); -}; - -function unixStylePath(filePath) { - return filePath.split(path.sep).join('/'); -} - -}).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){ -'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":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 assert = require('assert') - -// fix up some busted stuff, mostly on windows and old nodes -require('./polyfills.js') - -var util = require('util') - -function noop () {} - -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) - } - -if (/\bgfs\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug('fds', fds) - debug(queue) - assert.equal(queue.length, 0) - }) -} - - -var originalOpen = fs.open -fs.open = open - -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) -} - -function OpenReq(path, flags, mode, cb) { - this.path = path - this.flags = flags - this.mode = mode - this.cb = cb - Req.call(this) -} - -util.inherits(OpenReq, Req) - -OpenReq.prototype.process = function() { - originalOpen.call(fs, this.path, this.flags, this.mode, this.done) -} - -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) -} - - -var originalReaddir = fs.readdir -fs.readdir = readdir - -function readdir(path, cb) { - if (typeof cb !== "function") cb = noop - new ReaddirReq(path, cb) -} - -function ReaddirReq(path, cb) { - this.path = path - this.cb = cb - Req.call(this) -} - -util.inherits(ReaddirReq, Req) - -ReaddirReq.prototype.process = function() { - originalReaddir.call(fs, this.path, this.done) -} - -ReaddirReq.prototype.done = function(er, files) { - if (files && files.sort) - files = files.sort() - Req.prototype.done.call(this, er, files) - onclose() -} - - -var originalClose = fs.close -fs.close = close - -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) - }) -} - - -var originalCloseSync = fs.closeSync -fs.closeSync = closeSync - -function closeSync (fd) { - try { - return originalCloseSync(fd) - } finally { - onclose() - } -} - - -// Req class -function Req () { - // start processing - this.done = this.done.bind(this) - this.failures = 0 - this.process() -} - -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" - } - - if (tryAgain) { - this.failures ++ - enqueue(this) - } else { - var cb = this.cb - cb(er, result) - } -} - -var queue = [] - -function enqueue(req) { - queue.push(req) - debug('enqueue %d %s', queue.length, req.constructor.name, req) -} - -function onclose() { - var req = queue.shift() - if (req) { - debug('process', req.constructor.name, req) - req.process() + 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; } -} -}).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 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) -} + 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]; -// (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\./)) { - 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 + // 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); } - // 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) - }) - }) - }) + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } - 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 err, err2 - try { - var ret = fs.fchmodSync(fd, mode) - } catch (er) { - err = er + 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(); + } } - try { - fs.closeSync(fd) - } catch (er) { - err2 = er + 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 (err || err2) throw (err || err2) - return ret + result.href = result.format(); + return result; } -} - - -// 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) - }) - }) - }) - } - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - , err - , err2 - , ret - - try { - var ret = fs.futimesSync(fd, at, mt) - } catch (er) { - err = er - } - try { - fs.closeSync(fd) - } catch (er) { - err2 = er - } - if (err || err2) throw (err || err2) - return ret + 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 { + result.path = null; } + result.href = result.format(); + return result; + } - } 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) - } + // 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 === ''); - fs.lutimesSync = function (path, at, mt) { - return fs.utimensatSync(path, at, mt, constants.AT_SYMLINK_NOFOLLOW) + // 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--; } - - } else { - fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) } - fs.lutimesSync = function () {} } -} + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } -// 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. + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } -fs.chown = chownFix(fs.chown) -fs.fchown = chownFix(fs.fchown) -fs.lchown = chownFix(fs.lchown) + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } -fs.chmod = chownFix(fs.chmod) -fs.fchmod = chownFix(fs.fchmod) -fs.lchmod = chownFix(fs.lchmod) + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); -fs.chownSync = chownFixSync(fs.chownSync) -fs.fchownSync = chownFixSync(fs.fchownSync) -fs.lchownSync = chownFixSync(fs.lchownSync) + // 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(); + } + } -fs.chmodSync = chownFix(fs.chmodSync) -fs.fchmodSync = chownFix(fs.fchmodSync) -fs.lchmodSync = chownFix(fs.lchmodSync) + mustEndAbs = mustEndAbs || (result.host && srcPath.length); -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) - }) + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); } -} -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 - } + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); } -} - -// 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 + //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; +}; - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true +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; +}; - return false +function isString(arg) { + return typeof arg === "string"; } +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} -// 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 () {} +function isNull(arg) { + return arg === null; } -if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - process.nextTick(cb) - } - fs.lchownSync = function () {} +function isNullOrUndefined(arg) { + return arg == null; } - - -// 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) - }) - } +},{"punycode":49,"querystring":52}],59:[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", + "multiaddr": "^1.0.0", + "superagent": "^1.4.0", + "superagent-logger": "^1.0.3" + }, + "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" } +},{}],60:[function(require,module,exports){ +var pkg = require('../package.json') -// 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) - } - } - 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 - } - } +exports = module.exports = { + 'api-path': '/api/v0/', + 'user-agent': '/node-' + pkg.name + '/' + pkg.version + '/', + 'host': 'localhost', + 'port': '5001' } - -}).call(this,require('_process')) -},{"./fs.js":190,"_process":64,"constants":10}],193:[function(require,module,exports){ +},{"../package.json":59}],61:[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; -}; +var multiaddr = require('multiaddr') +var config = require('./config') +var requestAPI = require('./request-api') -stripBom.stream = function () { - var firstChunk = require('first-chunk-stream'); +exports = module.exports = IpfsAPI - return firstChunk({minSize: 3}, function (chunk, enc, cb) { - this.push(stripBom(chunk)); - cb(); - }); -}; +function IpfsAPI (host_or_multiaddr, port) { + var self = this -}).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 (!(self instanceof IpfsAPI)) { + return new IpfsAPI(host_or_multiaddr, port) + } - if( (// non-overlong 2-byte - (0xC2 <= bytes[i] && bytes[i] <= 0xDF) && - (0x80 <= bytes[i+1] && bytes[i+1] <= 0xBF) - ) - ) { - i += 2; - continue; - } + 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 + } - 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; - } + // autoconfigure in browser + if (!config.host && + typeof window !== 'undefined') { + var split = window.location.host.split(':') + config.host = split[0] + config.port = split[1] + } - 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; - } + // -- Internal - return false; + function command (name) { + return function (opts, cb) { + if (typeof (opts) === 'function') { + cb = opts + opts = {} + } + return requestAPI(name, null, opts, null, cb) } + } - return true; -} + function argCommand (name) { + return function (arg, opts, cb) { + if (typeof (opts) === 'function') { + cb = opts + opts = {} + } + return requestAPI(name, arg, opts, null, cb) + } + } -},{}],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){ -(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'); - -function File(file) { - if (!file) file = {}; - - // record path change - 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? - this.stat = file.stat || null; - - // contents = stream, buffer, or null if not read - this.contents = file.contents || null; -} + // -- Interface -File.prototype.isBuffer = function() { - return isBuffer(this.contents); -}; + self.send = requestAPI -File.prototype.isStream = function() { - return isStream(this.contents); -}; + self.add = function (files, opts, cb) { + if (typeof (opts) === 'function' && cb === undefined) { + cb = opts + opts = {} + } -File.prototype.isNull = function() { - return isNull(this.contents); -}; + return requestAPI('add', null, opts, files, cb) + } -// TODO: should this be moved to vinyl-fs? -File.prototype.isDirectory = function() { - return this.isNull() && this.stat && this.stat.isDirectory(); -}; + self.cat = argCommand('cat') + self.ls = argCommand('ls') -File.prototype.clone = function(opt) { - if (typeof opt === 'boolean') { - opt = { - deep: opt, - contents: true - }; - } else if (!opt) { - opt = { - deep: false, - contents: true - }; - } else { - opt.deep = opt.deep === true; - opt.contents = opt.contents !== false; + 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) + } } - // 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; + self.update = { + apply: command('update'), + check: command('update/check'), + log: command('update/log') } - var file = new File({ - cwd: this.cwd, - base: this.base, - stat: (this.stat ? cloneStats(this.stat) : null), - history: this.history.slice(), - contents: contents - }); + self.version = command('version') + self.commands = command('commands') - // 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; + self.mount = function (ipfs, ipns, cb) { + if (typeof ipfs === 'function') { + cb = ipfs + ipfs = null + } else if (typeof ipns === 'function') { + cb = ipns + ipns = null } - 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 opts = {} + if (ipfs) opts.f = ipfs + if (ipns) opts.n = ipns + return requestAPI('mount', null, opts, null, cb) + } - if (this.isStream()) { - return this.contents.pipe(stream, opt); + self.diag = { + net: command('diag/net') } - if (this.isBuffer()) { - if (opt.end) { - stream.end(this.contents); - } else { - stream.write(this.contents); + + 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) } - return stream; } - // isNull - if (opt.end) stream.end(); - return stream; -}; - -File.prototype.inspect = function() { - var inspect = []; - - // use relative path if possible - var filePath = (this.base && this.path) ? this.relative : this.path; - - if (filePath) { - inspect.push('"'+filePath+'"'); + 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') } - if (this.isBuffer()) { - inspect.push(this.contents.inspect()); + self.swarm = { + peers: command('swarm/peers'), + connect: argCommand('swarm/peers') } - if (this.isStream()) { - inspect.push(inspectStream(this.contents)); + 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]) + }) } - return ''; -}; - -// 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.'); + self.id = function (id, cb) { + if (typeof id === 'function') { + cb = id + id = null } - this._contents = val; + return requestAPI('id', id, null, null, cb) } -}); -// 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.'); - } -}); + self.pin = { + add: function (hash, opts, cb) { + if (typeof opts === 'function') { + cb = opts + opts = null + } -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'); + requestAPI('pin/add', hash, opts, null, cb) + }, + remove: function (hash, opts, cb) { + if (typeof opts === 'function') { + cb = opts + opts = null + } - // record history only when path changed - if (path && path !== this.path) { - this.history.push(path); + 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 = File; - -}).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 objectToString(o) { - return Object.prototype.toString.call(o); -} -// 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; + self.gateway = { + enable: command('gateway/enable'), + disable: command('gateway/disable') } -}; - - -if (typeof module === 'object') - module.exports = clone; - -/** - * 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). -*/ - -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 = []; - - var useBuffer = typeof Buffer != 'undefined'; - if (typeof circular == 'undefined') - circular = true; + self.log = { + tail: function (cb) { + return requestAPI('log/tail', null, {enc: 'text'}, null, true, cb) + } + } - if (typeof depth == 'undefined') - depth = Infinity; + self.name = { + publish: argCommand('name/publish'), + resolve: argCommand('name/resolve') + } - // 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.Buffer = Buffer - if (depth == 0) - return parent; + self.refs = argCommand('refs') + self.refs.local = command('refs/local') - var child; - var proto; - if (typeof parent != 'object') { - return parent; - } + self.dht = { + findprovs: argCommand('dht/findprovs'), - 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; + get: function (key, opts, cb) { + if (typeof (opts) === 'function' && !cb) { + cb = opts + opts = null } - } - if (circular) { - var index = allParents.indexOf(parent); + 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')) - if (index != -1) { - return allChildren[index]; - } - allParents.push(parent); - allChildren.push(child); - } + if (res[0].Type === 5) { + cb(null, res[0].Extra) + } else { + cb(res) + } + }) + }, - for (var i in parent) { - var attrs; - if (proto) { - attrs = Object.getOwnPropertyDescriptor(proto, i); - } - - if (attrs && attrs.set == null) { - continue; + put: function (key, value, opts, cb) { + if (typeof (opts) === 'function' && !cb) { + cb = opts + opts = null } - child[i] = _clone(parent[i], depth - 1); - } - return child; + return requestAPI('dht/put', [key, value], opts, null, cb) + } } - - return _clone(parent, depth); } -/** - * 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; +}).call(this,require("buffer").Buffer) +},{"./config":60,"./request-api":62,"buffer":5,"multiaddr":44}],62:[function(require,module,exports){ +(function (Buffer,process){ +var request = require('superagent') +var logger = require('superagent-logger') - var c = function () {}; - c.prototype = parent; - return new c(); -}; +var config = require('./config') -}).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'; +exports = module.exports = requestAPI -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; -}; +function safeJSONParser (buffer, res, done) { + var headers = !!res.headers + var stream = headers && !!res.headers['x-stream-output'] + var chunkedObjects = headers && !!res.headers['x-chunked-output'] -function every(arr) { - var len = arr.length; - while (len--) { - if (typeof arr[len] !== 'string' || arr[len].length <= 0) { - return false; - } - } - return true; -} + // No need to parse + if (stream && !buffer) return done() + if (chunkedObjects && buffer) return done() -},{}],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); + var objects = [] + var data = '' + res.text = '' + res.setEncoding('utf8') -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + res.on('data', function (chunk) { + res.text += chunk -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 (!chunkedObjects) { + data += chunk + return } - 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; - } - }); -} -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()); + try { + var obj = JSON.parse(chunk.toString()) + objects.push(obj) + } catch (e) { + chunkedObjects = false + data += chunk } - if (!made) made = null; + }) - p = path.resolve(p); + res.on('end', function () { + var parsed - 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; - - // 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; - } + if (!chunkedObjects) { + try { + parsed = JSON.parse(data) + data = parsed + } catch (e) {} + } else { + data = objects } - return made; -}; + return done(null, data) + }) +} -}).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; +function prepareFiles (files) { + files = Array.isArray(files) ? files : [files] -function toObject(val) { - if (val === null || val === undefined) { - throw new TypeError('Object.assign cannot be called with null or undefined'); - } + return files.map(function (file) { + if (Buffer.isBuffer(file)) { + // Multipart requests require a filename to not + // trow, but if it's a buffer we don't know the name + return { + contents: file, + opts: {filename: ''} + } + } - return Object(val); + // Just a file path + return {contents: file} + }) } -module.exports = Object.assign || function (target, source) { - var from; - var to = toObject(target); - var symbols; - - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments[s]); - - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } +function requestAPI (path, args, opts, files, buffer, cb) { + if (Array.isArray(path)) path = path.join('/') - 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]]; - } - } - } - } + opts = opts || {} - return to; -}; + if (args && !Array.isArray(args)) args = [args] + if (args) opts.arg = args -},{}],232:[function(require,module,exports){ -'use strict'; -var firstChunk = require('first-chunk-stream'); -var stripBom = require('strip-bom'); + if (typeof buffer === 'function') { + cb = buffer + buffer = false + } -module.exports = function () { - return firstChunk({minSize: 3}, function (chunk, enc, cb) { - this.push(stripBom(chunk)); - cb(); - }); -}; + // this option is only used internally, not passed to daemon + delete opts.followSymlinks -},{"first-chunk-stream":143,"strip-bom":233}],233:[function(require,module,exports){ -(function (Buffer){ -'use strict'; -var isUtf8 = require('is-utf8'); + opts['stream-channels'] = 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); - } + var method = files ? 'POST' : 'GET' + var reqPath = config['api-path'] + path + var url = config.host + ':' + config.port + reqPath - if (Buffer.isBuffer(x) && isUtf8(x) && - x[0] === 0xEF && x[1] === 0xBB && x[2] === 0xBF) { - return x.slice(3); - } + var req = request(method, url) + .set('User-Agent', config['user-agent']) + .query(opts) + .buffer(buffer) + .parse(safeJSONParser.bind(null, buffer)) + .on('error', cb) + .on('response', handle) - return x; -}; + if (process.env.DEBUG) { + req.use(logger) + } -}).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"; + if (files) { + prepareFiles(files).forEach(function (file) { + req.attach('file', file.contents, file.opts) + }) + } -module.exports = make -module.exports.ctor = ctor -module.exports.objCtor = objCtor -module.exports.obj = obj + req.end() -var through2 = require("through2") -var xtend = require("xtend") + function handle (res) { + if (res.error) return cb(res.error, null) -function ctor(options, fn) { - if (typeof options == "function") { - fn = options - options = {} - } + var headers = !!res.headers + var stream = headers && !!res.headers['x-stream-output'] + var chunkedObjects = headers && !!res.headers['x-chunked-output'] - 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 (stream && !buffer) return cb(null, res) + if (chunkedObjects && buffer) return cb(null, res) -function objCtor(options, fn) { - if (typeof options === "function") { - fn = options - options = {} + return cb(null, res.body) } - options = xtend({objectMode: true, highWaterMark: 16}, options) - return ctor(options, fn) -} -function make(options, fn) { - return ctor(options, fn)() -} - -function obj(options, fn) { - if (typeof options === "function") { - fn = options - options = {} - } - options = xtend({objectMode: true, highWaterMark: 16}, options) - return make(options, fn) + return req } -},{"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) +}).call(this,{"isBuffer":require("../node_modules/is-buffer/index.js")},require('_process')) +},{"../node_modules/is-buffer/index.js":13,"./config":60,"_process":48,"superagent":56,"superagent-logger":55}]},{},[61])(61) }); \ No newline at end of file diff --git a/dist/ipfsapi.min.js b/dist/ipfsapi.min.js index 91e4ff59a..fa762951e 100644 --- a/dist/ipfsapi.min.js +++ b/dist/ipfsapi.min.js @@ -1,9 +1,3 @@ -(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(t0){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=0;a--){s=e[a];if(s)break}for(a=0;a>> no match, partial?",e,l,t,h);if(l===o)return true}return false}var d;if(typeof u==="string"){if(n.nocase){d=c.toLowerCase()===u.toLowerCase()}else{d=c===u}this.debug("string match",u,c,d)}else{d=c.match(u);this.debug("pattern match",u,c,d)}if(!d)return false}if(i===o&&a===f){return true}else if(i===o){return r}else if(a===f){var v=i===o-1&&e[i]==="";return v}throw new Error("wtf?")};function O(e){return e.replace(/\\(.)/g,"$1")}function j(e){return e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}},{"brace-expansion":157,path:62}],157:[function(e,t,r){var n=e("concat-map");var i=e("balanced-match");t.exports=d;var s="\x00SLASH"+Math.random()+"\x00";var a="\x00OPEN"+Math.random()+"\x00";var o="\x00CLOSE"+Math.random()+"\x00";var f="\x00COMMA"+Math.random()+"\x00";var u="\x00PERIOD"+Math.random()+"\x00";function c(e){return parseInt(e,10)==e?parseInt(e,10):e.charCodeAt(0)}function l(e){return e.split("\\\\").join(s).split("\\{").join(a).split("\\}").join(o).split("\\,").join(f).split("\\.").join(u)}function h(e){return e.split(s).join("\\").split(a).join("{").split(o).join("}").split(f).join(",").split(u).join(".")}function p(e){if(!e)return[""];var t=[];var r=i("{","}",e);if(!r)return e.split(",");var n=r.pre;var s=r.body;var a=r.post;var o=n.split(",");o[o.length-1]+="{"+s+"}";var f=p(a);if(a.length){o[o.length-1]+=f.shift();o.push.apply(o,f)}t.push.apply(t,o);return t}function d(e){if(!e)return[];return w(l(e),true).map(h)}function v(e){return e}function m(e){return"{"+e+"}"}function g(e){return/^-?0\d/.test(e)}function b(e,t){return e<=t}function y(e,t){return e>=t}function w(e,t){var r=[];var s=i("{","}",e);if(!s||/\$$/.test(s.pre))return[e];var a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body);var f=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body);var u=a||f;var l=/^(.*,)+(.+)?$/.test(s.body);if(!u&&!l){if(s.post.match(/,.*}/)){e=s.pre+"{"+s.body+o+s.post;return w(e)}return[e]}var h;if(u){h=s.body.split(/\.\./)}else{h=p(s.body);if(h.length===1){h=w(h[0],false).map(m);if(h.length===1){var d=s.post.length?w(s.post,false):[""];return d.map(function(e){return s.pre+h[0]+e})}}}var v=s.pre;var d=s.post.length?w(s.post,false):[""];var _;if(u){var S=c(h[0]);var E=c(h[1]);var x=Math.max(h[0].length,h[1].length);var O=h.length==3?Math.abs(c(h[2])):1;var j=b;var k=E0){var T=new Array(I+1).join("0");if(L<0)A="-"+T+A.slice(1);else A=T+A}}}_.push(A)}}else{_=n(h,function(e){return w(e,false)})}for(var C=0;C<_.length;C++){for(var M=0;M1?r.substring(s.start+e.length,s.end):"";s.post=r.slice(s.end+t.length);return s}}}if(i&&a){var f=s.start+e.length;s=n(e,t,r.substr(f));if(s){s.start+=f;s.end+=f;s.pre=r.slice(0,f)+s.pre}return s}}},{}],159:[function(e,t,r){t.exports=function(e,t){var r=[];for(var i=0;i0){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)y(e)}_(e,t)}}else if(!i){t.reading=false}return p(t)}function p(e){return!e.ended&&(e.needReadable||e.length=d){e=d}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function m(e,t){if(t.length===0&&t.ended)return 0;if(t.objectMode)return e===0?0:1;if(isNaN(e)||o.isNull(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=v(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else return t.length}return e}l.prototype.read=function(e){u("read",e);var t=this._readableState;var r=e;if(!o.isNumber(e)||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)R(this);else y(this);return null}e=m(e,t);if(e===0&&t.ended){if(t.length===0)R(this);return null}var n=t.needReadable;u("need readable",n);if(t.length===0||t.length-e0)i=k(e,t);else i=null;if(o.isNull(i)){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)R(this);if(!o.isNull(i))this.emit("data",i);return i};function g(e,t){var r=null;if(!o.isBuffer(t)&&!o.isString(t)&&!o.isNullOrUndefined(t)&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function b(e,t){if(t.decoder&&!t.ended){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;y(e)}function y(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){u("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)r.nextTick(function(){w(e)});else w(e)}}function w(e){u("emit readable");e.emit("readable");j(e)}function _(e,t){if(!t.readingMore){t.readingMore=true;r.nextTick(function(){S(e,t)})}}function S(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length=n){if(s)o=r.join("");else o=i.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted){t.ended=true;r.nextTick(function(){if(!t.endEmitted&&t.length===0){t.endEmitted=true;e.readable=false;e.emit("end")}})}}function L(e,t){for(var r=0,n=e.length;r1){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);t.length+=t.objectMode?1:r.length;if(i){t.buffer.unshift(r)}else{t.reading=false;t.buffer.push(r)}if(t.needReadable)b(e);w(e,t)}}else if(!i){t.reading=false}return h(t)}function h(e){return!e.ended&&(e.needReadable||e.length=p){e=p}else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function v(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=d(e);if(e>t.length){if(!t.ended){t.needReadable=true;return 0}else return t.length}return e}c.prototype.read=function(e){var t=this._readableState;t.calledRead=true;var r=e;var n;if(typeof e!=="number"||e>0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){b(this);return null}e=v(e,t);if(e===0&&t.ended){n=null;if(t.length>0&&t.decoder){n=j(e,t);t.length-=n.length}if(t.length===0)k(this);return n}var i=t.needReadable;if(t.length-e<=t.highWaterMark)i=true;if(t.ended||t.reading)i=false;if(i){t.reading=true;t.sync=true;if(t.length===0)t.needReadable=true;this._read(t.highWaterMark);t.sync=false}if(i&&!t.reading)e=v(r,t);if(e>0)n=j(e,t);else n=null;if(n===null){t.needReadable=true;e=0}t.length-=e;if(t.length===0&&!t.ended)t.needReadable=true;if(t.ended&&!t.endEmitted&&t.length===0)k(this);return n};function m(e,t){var r=null;if(!i.isBuffer(t)&&"string"!==typeof t&&t!==null&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function g(e,t){if(t.decoder&&!t.ended){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;if(t.length>0)b(e);else k(e)}function b(e){var t=e._readableState;t.needReadable=false;if(t.emittedReadable)return;t.emittedReadable=true;if(t.sync)r.nextTick(function(){y(e)});else y(e)}function y(e){e.emit("readable")}function w(e,t){if(!t.readingMore){t.readingMore=true;r.nextTick(function(){_(e,t)})}}function _(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length0)return}if(t.pipesCount===0){t.flowing=false;if(s.listenerCount(e,"data")>0)O(e);return}t.ranOut=true}function x(){if(this._readableState.ranOut){this._readableState.ranOut=false;E(this)}}c.prototype.unpipe=function(e){var t=this._readableState;if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;this.removeListener("readable",x);t.flowing=false;if(e)e.emit("unpipe",this);return this}if(!e){var r=t.pipes;var n=t.pipesCount;t.pipes=null;t.pipesCount=0;this.removeListener("readable",x);t.flowing=false;for(var i=0;i=n){if(s)o=r.join("");else o=i.concat(r,n);r.length=0}else{if(e0)throw new Error("endReadable called on non-empty stream");if(!t.endEmitted&&t.calledRead){t.ended=true;r.nextTick(function(){if(!t.endEmitted&&t.length===0){t.endEmitted=true;e.readable=false;e.emit("end")}})}}function R(e,t){for(var r=0,n=e.length;rthis.end){throw new Error("start must be <= end")}this.pos=this.start}if(this.fd!==null){r.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit("error",e);a.readable=false;return}a.fd=t;a.emit("open",t);a._read()})}function i(t,r){if(!(this instanceof i))return new i(t,r);n.call(this);this.path=t;this.fd=null;this.writable=true;this.flags="w";this.encoding="binary";this.mode=438;this.bytesWritten=0;r=r||{};var s=Object.keys(r);for(var a=0,o=s.length;a= zero")}this.pos=this.start}this.busy=false;this._queue=[];if(this.fd===null){this._open=e.open;this._queue.push([this._open,this.path,this.flags,this.mode,undefined]);this.flush()}}}}).call(this,e("_process"))},{_process:64,stream:81}],187:[function(e,t,r){(function(r){var n=e("./fs.js");var i=e("constants");var s=r.cwd;var a=null;r.cwd=function(){if(!a)a=s.call(r);return a};try{r.cwd()}catch(o){}var f=r.chdir;r.chdir=function(e){a=null;f.call(r,e)};t.exports=u;function u(e){if(i.hasOwnProperty("O_SYMLINK")&&r.version.match(/^v0\.6\.[0-2]|^v0\.5\./)){c(e)}if(!e.lutimes){l(e)}e.chown=h(e.chown);e.fchown=h(e.fchown);e.lchown=h(e.lchown);e.chmod=h(e.chmod);e.fchmod=h(e.fchmod);e.lchmod=h(e.lchmod);e.chownSync=p(e.chownSync);e.fchownSync=p(e.fchownSync);e.lchownSync=p(e.lchownSync);e.chmodSync=h(e.chmodSync);e.fchmodSync=h(e.fchmodSync);e.lchmodSync=h(e.lchmodSync);if(!e.lchmod){e.lchmod=function(e,t,n){r.nextTick(n)};e.lchmodSync=function(){}}if(!e.lchown){e.lchown=function(e,t,n,i){r.nextTick(i)};e.lchownSync=function(){}}if(r.platform==="win32"){e.rename=function(e){return function(t,r,n){var i=Date.now();e(t,r,function s(a){if(a&&(a.code==="EACCES"||a.code==="EPERM")&&Date.now()-i<1e3){return e(t,r,s)}if(n)n(a)})}}(e.rename)}e.read=function(t){return function(r,n,i,s,a,o){var f;if(o&&typeof o==="function"){var u=0;f=function(c,l,h){if(c&&c.code==="EAGAIN"&&u<10){u++;return t.call(e,r,n,i,s,a,f)}o.apply(this,arguments)}}return t.call(e,r,n,i,s,a,f)}}(e.read);e.readSync=function(t){return function(r,n,i,s,a){var o=0;while(true){try{return t.call(e,r,n,i,s,a)}catch(f){if(f.code==="EAGAIN"&&o<10){o++;continue}throw f}}}}(e.readSync)}function c(e){e.lchmod=function(t,r,n){n=n||noop;e.open(t,i.O_WRONLY|i.O_SYMLINK,r,function(t,i){if(t){n(t);return}e.fchmod(i,r,function(t){e.close(i,function(e){n(t||e)})})})};e.lchmodSync=function(t,r){var n=e.openSync(t,i.O_WRONLY|i.O_SYMLINK,r);var s=true;var a;try{a=e.fchmodSync(n,r);s=false}finally{if(s){try{e.closeSync(n)}catch(o){}}else{e.closeSync(n)}}return a}}function l(e){if(i.hasOwnProperty("O_SYMLINK")){e.lutimes=function(t,r,n,s){e.open(t,i.O_SYMLINK,function(t,i){s=s||noop;if(t)return s(t);e.futimes(i,r,n,function(t){e.close(i,function(e){return s(t||e)})})})};e.lutimesSync=function(t,r,n){var s=e.openSync(t,i.O_SYMLINK);var a;var o=true;try{a=e.futimesSync(s,r,n);o=false}finally{if(o){try{e.closeSync(s)}catch(f){}}else{e.closeSync(s)}}return a}}else{e.lutimes=function(e,t,n,i){r.nextTick(i)};e.lutimesSync=function(){}}}function h(e){if(!e)return e;return function(t,r,i,s){return e.call(n,t,r,i,function(e,t){if(d(e))e=null;s(e,t)})}}function p(e){if(!e)return e;return function(t,r,i){try{return e.call(n,t,r,i)}catch(s){if(!d(s))throw s}}}function d(e){if(!e)return true;if(e.code==="ENOSYS")return true;var t=!r.getuid||r.getuid()!==0;if(t){if(e.code==="EINVAL"||e.code==="EPERM")return true}return false}}).call(this,e("_process"))},{"./fs.js":184,_process:64,constants:10}],188:[function(e,t,r){(function(r){"use strict";var n=e("through2");var i=e("graceful-fs");var s=e("path");var a=e("vinyl");var o=e("convert-source-map");var f=e("strip-bom");var u="gulp-sourcemap";var c=/^https?:\/\//;t.exports.init=function h(e){function t(t,n,a){if(t.isNull()){this.push(t);return a()}if(t.isStream()){return a(new Error(u+"-init: Streaming not supported"))}var h=t.contents.toString();var p;if(e&&e.loadMaps){var d="";p=o.fromSource(h);if(p){p=p.toObject();d=s.dirname(t.path);h=o.removeComments(h)}else{var v=o.mapFileCommentRegex.exec(h);var m;if(v){m=s.resolve(s.dirname(t.path),v[1]||v[2]);h=o.removeMapFileComments(h)}else{m=t.path+".map"}d=s.dirname(m);try{p=JSON.parse(f(i.readFileSync(m,"utf8")))}catch(g){}}if(p){p.sourcesContent=p.sourcesContent||[];p.sources.forEach(function(r,n){if(r.match(c)){p.sourcesContent[n]=p.sourcesContent[n]||null;return}var a=s.resolve(d,r);p.sources[n]=l(s.relative(t.base,a));if(!p.sourcesContent[n]){var o=null;if(p.sourceRoot){if(p.sourceRoot.match(c)){p.sourcesContent[n]=null;return}a=s.resolve(d,p.sourceRoot,r)}if(a===t.path){o=h}else{try{if(e.debug)console.log(u+'-init: No source content for "'+r+'". Loading from file.');o=f(i.readFileSync(a,"utf8"))}catch(v){if(e.debug)console.warn(u+"-init: source file not found: "+a)}}p.sourcesContent[n]=o}});t.contents=new r(h,"utf8")}}if(!p){p={version:3,names:[],mappings:"",sources:[l(t.relative)],sourcesContent:[h]}}p.file=l(t.relative);t.sourceMap=p;this.push(t);a()}return n.obj(t)};t.exports.write=function p(e,t){if(t===undefined&&Object.prototype.toString.call(e)==="[object Object]"){t=e;e=undefined}t=t||{};if(t.includeContent===undefined)t.includeContent=true;if(t.addComment===undefined)t.addComment=true;function o(n,o,c){if(n.isNull()||!n.sourceMap){this.push(n);return c()}if(n.isStream()){return c(new Error(u+"-write: Streaming not supported"))}var h=n.sourceMap;h.file=l(n.relative);h.sources=h.sources.map(function(e){return l(e)});if(t.sourceRoot){if(typeof t.sourceRoot==="function"){h.sourceRoot=t.sourceRoot(n)}else{h.sourceRoot=t.sourceRoot}}if(t.includeContent){h.sourcesContent=h.sourcesContent||[];for(var p=0;p0;i--){n=t[i];if(~n.indexOf("sourceMappingURL=data:"))return r.fromComment(n)}}c.prototype.toJSON=function(e){return JSON.stringify(this.sourcemap,null,e)};c.prototype.toBase64=function(){var e=this.toJSON();return new t(e).toString("base64")};c.prototype.toComment=function(e){var t=this.toBase64();var r="sourceMappingURL=data:application/json;base64,"+t;return e&&e.multiline?"/*# "+r+" */":"//# "+r};c.prototype.toObject=function(){return JSON.parse(this.toJSON())};c.prototype.addProperty=function(e,t){if(this.sourcemap.hasOwnProperty(e))throw new Error("property %s already exists on the sourcemap, use set property instead");return this.setProperty(e,t)};c.prototype.setProperty=function(e,t){this.sourcemap[e]=t;return this};c.prototype.getProperty=function(e){return this.sourcemap[e]};r.fromObject=function(e){return new c(e)};r.fromJSON=function(e){return new c(e,{isJSON:true})};r.fromBase64=function(e){return new c(e,{isEncoded:true})};r.fromComment=function(e){e=e.replace(/^\/\*/g,"//").replace(/\*\/$/g,"");return new c(e,{isEncoded:true,hasComment:true})};r.fromMapFileComment=function(e,t){return new c(e,{commentFileDir:t,isFileComment:true,isJSON:true})};r.fromSource=function(e,t){if(t)return l(e);var n=e.match(s);s.lastIndex=0;return n?r.fromComment(n.pop()):null};r.fromMapFileSource=function(e,t){var n=e.match(a);a.lastIndex=0;return n?r.fromMapFileComment(n.pop(),t):null};r.removeComments=function(e){s.lastIndex=0;return e.replace(s,"")};r.removeMapFileComments=function(e){a.lastIndex=0;return e.replace(a,"")};Object.defineProperty(r,"commentRegex",{get:function h(){s.lastIndex=0;return s}});Object.defineProperty(r,"mapFileCommentRegex",{get:function p(){a.lastIndex=0;return a}})}).call(this,e("buffer").Buffer)},{buffer:6,fs:4,path:62}],190:[function(e,t,r){(function(n,i,s){var a=e("module");var o="(function (exports, require, module, __filename, __dirname) { ";var f="});";var u=o+n.binding("natives").fs+f;var c=e("vm");var l=c.runInThisContext(u);l(r,e,t,i,s)}).call(this,e("_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(e,t,r){(function(r){var n=t.exports=e("./fs.js");var i=e("assert");e("./polyfills.js");var s=e("util");function a(){}var o=a;if(s.debuglog)o=s.debuglog("gfs");else if(/\bgfs\b/i.test(r.env.NODE_DEBUG||""))o=function(){var e=s.format.apply(s,arguments);e="GFS: "+e.split(/\n/).join("\nGFS: ");console.error(e)};if(/\bgfs\b/i.test(r.env.NODE_DEBUG||"")){r.on("exit",function(){o("fds",l);o(w);i.equal(w.length,0)})}var f=n.open;n.open=u;function u(e,t,r,n){if(typeof r==="function")n=r,r=null;if(typeof n!=="function")n=a;new c(e,t,r,n)}function c(e,t,r,n){this.path=e;this.flags=t;this.mode=r;this.cb=n;y.call(this)}s.inherits(c,y);c.prototype.process=function(){f.call(n,this.path,this.flags,this.mode,this.done)};var l={};c.prototype.done=function(e,t){o("open done",e,t);if(t)l["fd"+t]=this.path;y.prototype.done.call(this,e,t)};var h=n.readdir;n.readdir=p;function p(e,t){if(typeof t!=="function")t=a;new d(e,t)}function d(e,t){this.path=e;this.cb=t;y.call(this)}s.inherits(d,y);d.prototype.process=function(){h.call(n,this.path,this.done)};d.prototype.done=function(e,t){if(t&&t.sort)t=t.sort();y.prototype.done.call(this,e,t);S()};var v=n.close;n.close=m;function m(e,t){o("close",e);if(typeof t!=="function")t=a;delete l["fd"+e];v.call(n,e,function(e){S();t(e)})}var g=n.closeSync;n.closeSync=b;function b(e){try{return g(e)}finally{S()}}function y(){this.done=this.done.bind(this);this.failures=0;this.process()}y.prototype.done=function(e,t){var n=false;if(e){var i=e.code;var n=i==="EMFILE"||i==="ENFILE";if(r.platform==="win32")n=n||i==="OK"}if(n){this.failures++;_(this)}else{var s=this.cb;s(e,t)}};var w=[];function _(e){w.push(e);o("enqueue %d %s",w.length,e.constructor.name,e)}function S(){var e=w.shift();if(e){o("process",e.constructor.name,e);e.process()}}}).call(this,e("_process"))},{"./fs.js":190,"./polyfills.js":192,_process:64,assert:1,util:90}],192:[function(e,t,r){(function(t){var r=e("./fs.js");var n=e("constants");var i=t.cwd;var s=null;t.cwd=function(){if(!s)s=i.call(t);return s};var a=t.chdir;t.chdir=function(e){s=null;a.call(t,e)};if(n.hasOwnProperty("O_SYMLINK")&&t.version.match(/^v0\.6\.[0-2]|^v0\.5\./)){r.lchmod=function(e,t,i){i=i||noop;r.open(e,n.O_WRONLY|n.O_SYMLINK,t,function(e,n){if(e){i(e);return}r.fchmod(n,t,function(e){r.close(n,function(t){i(e||t)})})})};r.lchmodSync=function(e,t){var i=r.openSync(e,n.O_WRONLY|n.O_SYMLINK,t);var s,a;try{var o=r.fchmodSync(i,t)}catch(f){s=f}try{r.closeSync(i)}catch(f){a=f}if(s||a)throw s||a;return o}}if(!r.lutimes){if(n.hasOwnProperty("O_SYMLINK")){r.lutimes=function(e,t,i,s){r.open(e,n.O_SYMLINK,function(e,n){s=s||noop;if(e)return s(e);r.futimes(n,t,i,function(e){r.close(n,function(t){return s(e||t)})})})};r.lutimesSync=function(e,t,i){var s=r.openSync(e,n.O_SYMLINK),a,o,f;try{var f=r.futimesSync(s,t,i)}catch(u){a=u}try{r.closeSync(s)}catch(u){o=u}if(a||o)throw a||o;return f}}else if(r.utimensat&&n.hasOwnProperty("AT_SYMLINK_NOFOLLOW")){r.lutimes=function(e,t,i,s){r.utimensat(e,t,i,n.AT_SYMLINK_NOFOLLOW,s)};r.lutimesSync=function(e,t,i){return r.utimensatSync(e,t,i,n.AT_SYMLINK_NOFOLLOW)}}else{r.lutimes=function(e,r,n,i){t.nextTick(i)};r.lutimesSync=function(){}}}r.chown=o(r.chown);r.fchown=o(r.fchown);r.lchown=o(r.lchown);r.chmod=o(r.chmod);r.fchmod=o(r.fchmod);r.lchmod=o(r.lchmod);r.chownSync=f(r.chownSync);r.fchownSync=f(r.fchownSync);r.lchownSync=f(r.lchownSync);r.chmodSync=o(r.chmodSync);r.fchmodSync=o(r.fchmodSync);r.lchmodSync=o(r.lchmodSync);function o(e){if(!e)return e;return function(t,n,i,s){return e.call(r,t,n,i,function(e,t){if(u(e))e=null;s(e,t)})}}function f(e){if(!e)return e;return function(t,n,i){try{return e.call(r,t,n,i)}catch(s){if(!u(s))throw s}}}function u(e){if(!e)return true;if(e.code==="ENOSYS")return true;var r=!t.getuid||t.getuid()!==0;if(r){if(e.code==="EINVAL"||e.code==="EPERM")return true}return false}if(!r.lchmod){r.lchmod=function(e,r,n){t.nextTick(n)};r.lchmodSync=function(){}}if(!r.lchown){r.lchown=function(e,r,n,i){t.nextTick(i)};r.lchownSync=function(){}}if(t.platform==="win32"){var c=r.rename;r.rename=function p(e,t,r){var n=Date.now();c(e,t,function i(s){if(s&&(s.code==="EACCES"||s.code==="EPERM")&&Date.now()-n<1e3){return c(e,t,i)}if(r)r(s)})}}var l=r.read;r.read=function(e,t,n,i,s,a){var o;if(a&&typeof a==="function"){var f=0;o=function(u,c,h){if(u&&u.code==="EAGAIN"&&f<10){f++;return l.call(r,e,t,n,i,s,o)}a.apply(this,arguments)}}return l.call(r,e,t,n,i,s,o)};var h=r.readSync;r.readSync=function(e,t,n,i,s){var a=0;while(true){try{return h.call(r,e,t,n,i,s)}catch(o){if(o.code==="EAGAIN"&&a<10){a++;continue}throw o}}}}).call(this,e("_process"))},{"./fs.js":190,_process:64,constants:10}],193:[function(e,t,r){(function(r){"use strict";var n=e("is-utf8");var i=t.exports=function(e){if(typeof e==="string"){return e.replace(/^\ufeff/g,"")}if(r.isBuffer(e)&&n(e)&&e[0]===239&&e[1]===187&&e[2]===191){return e.slice(3)}return e};i.stream=function(){var t=e("first-chunk-stream");return t({minSize:3},function(e,t,r){this.push(i(e));r()})}}).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,"first-chunk-stream":194,"is-utf8":195}],194:[function(e,t,r){arguments[4][143][0].apply(r,arguments)},{buffer:6,dup:143,stream:81,util:90}],195:[function(e,t,r){r=t.exports=function(e){var t=0;while(t"};Object.defineProperty(h.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(h.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(h.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=h}).call(this,e("_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(e,t,r){arguments[4][97][0].apply(r,arguments)},{buffer:6,dup:97}],209:[function(e,t,r){arguments[4][98][0].apply(r,arguments)},{"./isStream":212,dup:98}],210:[function(e,t,r){var n=e("buffer");var i=n.Buffer;t.exports=function(e){return typeof e==="object"&&e instanceof i}},{buffer:6}],211:[function(e,t,r){arguments[4][100][0].apply(r,arguments)},{dup:100}],212:[function(e,t,r){arguments[4][101][0].apply(r,arguments)},{dup:101,stream:81}],213:[function(e,t,r){arguments[4][8][0].apply(r,arguments)},{dup:8,fs:4}],214:[function(e,t,r){(function(e){"use strict";function r(e){return Object.prototype.toString.call(e)}var n={isArray:function(e){return Array.isArray(e)||typeof e==="object"&&r(e)==="[object Array]"},isDate:function(e){return typeof e==="object"&&r(e)==="[object Date]"},isRegExp:function(e){return typeof e==="object"&&r(e)==="[object RegExp]"},getRegExpFlags:function(e){var t="";e.global&&(t+="g");e.ignoreCase&&(t+="i");e.multiline&&(t+="m");return t}};if(typeof t==="object")t.exports=i;function i(t,r,i,s){var a=[];var o=[];var f=typeof e!="undefined";if(typeof r=="undefined")r=true;if(typeof i=="undefined")i=Infinity;function u(t,i){if(t===null)return null;if(i==0)return t;var c;var l;if(typeof t!="object"){return t}if(n.isArray(t)){c=[]}else if(n.isRegExp(t)){c=new RegExp(t.source,n.getRegExpFlags(t));if(t.lastIndex)c.lastIndex=t.lastIndex}else if(n.isDate(t)){c=new Date(t.getTime())}else if(f&&e.isBuffer(t)){c=new e(t.length);t.copy(c);return c}else{if(typeof s=="undefined"){l=Object.getPrototypeOf(t);c=Object.create(l)}else{c=Object.create(s);l=s}}if(r){var h=a.indexOf(t);if(h!=-1){return o[h]}a.push(t);o.push(c)}for(var p in t){var d;if(l){d=Object.getOwnPropertyDescriptor(l,p)}if(d&&d.set==null){continue}c[p]=u(t[p],i-1)}return c}return u(t,i)}i.clonePrototype=function(e){if(e===null)return null;var t=function(){};t.prototype=e;return new t}}).call(this,e("buffer").Buffer)},{buffer:6}],215:[function(e,t,r){arguments[4][195][0].apply(r,arguments)},{dup:195}],216:[function(e,t,r){"use strict";t.exports=function i(e){if(typeof e==="string"&&e.length>0){return true}if(Array.isArray(e)){return e.length!==0&&n(e)}return false};function n(e){var t=e.length;while(t--){if(typeof e[t]!=="string"||e[t].length<=0){return false}}return true}},{}],217:[function(e,t,r){arguments[4][51][0].apply(r,arguments)},{dup:51,"readable-stream/passthrough":229}],218:[function(e,t,r){arguments[4][70][0].apply(r,arguments)},{"./_stream_readable":220,"./_stream_writable":222,"core-util-is":223,dup:70,inherits:224,"process-nextick-args":226}],219:[function(e,t,r){arguments[4][71][0].apply(r,arguments)},{"./_stream_transform":221,"core-util-is":223,dup:71,inherits:224}],220:[function(e,t,r){arguments[4][72][0].apply(r,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(e,t,r){arguments[4][73][0].apply(r,arguments)},{"./_stream_duplex":218,"core-util-is":223,dup:73,inherits:224}],222:[function(e,t,r){arguments[4][74][0].apply(r,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(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}],224:[function(e,t,r){arguments[4][18][0].apply(r,arguments)},{dup:18}],225:[function(e,t,r){arguments[4][22][0].apply(r,arguments)},{dup:22}],226:[function(e,t,r){arguments[4][63][0].apply(r,arguments)},{_process:64,dup:63}],227:[function(e,t,r){arguments[4][86][0].apply(r,arguments)},{buffer:6,dup:86}],228:[function(e,t,r){arguments[4][88][0].apply(r,arguments)},{dup:88}],229:[function(e,t,r){arguments[4][75][0].apply(r,arguments)},{"./lib/_stream_passthrough.js":219,dup:75}],230:[function(e,t,r){(function(r){var n=e("path");var i=e("fs");var s=parseInt("0777",8);t.exports=a.mkdirp=a.mkdirP=a;function a(e,t,o,f){if(typeof t==="function"){o=t;t={}}else if(!t||typeof t!=="object"){t={mode:t}}var u=t.mode;var c=t.fs||i;if(u===undefined){u=s&~r.umask()}if(!f)f=null;var l=o||function(){};e=n.resolve(e);c.mkdir(e,u,function(r){if(!r){f=f||e;return l(null,f)}switch(r.code){case"ENOENT":a(n.dirname(e),t,function(r,n){if(r)l(r,n);else a(e,t,l,n)});break;default:c.stat(e,function(e,t){if(e||!t.isDirectory())l(r,f);else l(null,f)});break}})}a.sync=function o(e,t,a){if(!t||typeof t!=="object"){t={mode:t}}var f=t.mode;var u=t.fs||i;if(f===undefined){f=s&~r.umask()}if(!a)a=null;e=n.resolve(e);try{u.mkdirSync(e,f);a=a||e}catch(c){switch(c.code){case"ENOENT":a=o(n.dirname(e),t,a);o(e,t,a);break;default:var l;try{l=u.statSync(e)}catch(h){throw c}if(!l.isDirectory())throw c;break}}return a}}).call(this,e("_process"))},{_process:64,fs:4,path:62}],231:[function(e,t,r){"use strict";var n=Object.prototype.hasOwnProperty;var i=Object.prototype.propertyIsEnumerable;function s(e){if(e===null||e===undefined){throw new TypeError("Object.assign cannot be called with null or undefined")}return Object(e)}t.exports=Object.assign||function(e,t){var r;var a=s(e);var o;for(var f=1;f<]/g}},{}],2:[function(t,e,r){"use strict";function n(){var t={modifiers:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},colors:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39]},bgColors:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49]}};t.colors.grey=t.colors.gray;Object.keys(t).forEach(function(e){var r=t[e];Object.keys(r).forEach(function(e){var n=r[e];t[e]=r[e]={open:"["+n[0]+"m",close:"["+n[1]+"m"}});Object.defineProperty(t,e,{value:r,enumerable:false})});return t}Object.defineProperty(e,"exports",{enumerable:true,get:n})},{}],3:[function(t,e,r){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(t){"use strict";var e=typeof Uint8Array!=="undefined"?Uint8Array:Array;var r="+".charCodeAt(0);var i="/".charCodeAt(0);var o="0".charCodeAt(0);var s="a".charCodeAt(0);var a="A".charCodeAt(0);var f="-".charCodeAt(0);var u="_".charCodeAt(0);function l(t){var e=t.charCodeAt(0);if(e===r||e===f)return 62;if(e===i||e===u)return 63;if(e0){throw new Error("Invalid string. Length must be a multiple of 4")}var f=t.length;s="="===t.charAt(f-2)?2:"="===t.charAt(f-1)?1:0;a=new e(t.length*3/4-s);i=s>0?t.length-4:t.length;var u=0;function h(t){a[u++]=t}for(r=0,n=0;r>16);h((o&65280)>>8);h(o&255)}if(s===2){o=l(t.charAt(r))<<2|l(t.charAt(r+1))>>4;h(o&255)}else if(s===1){o=l(t.charAt(r))<<10|l(t.charAt(r+1))<<4|l(t.charAt(r+2))>>2;h(o>>8&255);h(o&255)}return a}function c(t){var e,r=t.length%3,i="",o,s;function a(t){return n.charAt(t)}function f(t){return a(t>>18&63)+a(t>>12&63)+a(t>>6&63)+a(t&63)}for(e=0,s=t.length-r;e>2);i+=a(o<<4&63);i+="==";break;case 2:o=(t[t.length-2]<<8)+t[t.length-1];i+=a(o>>10);i+=a(o>>4&63);i+=a(o<<2&63);i+="=";break}return i}t.toByteArray=h;t.fromByteArray=c})(typeof r==="undefined"?this.base64js={}:r)},{}],4:[function(t,e,r){var n=t("buffer").Buffer;e.exports=function(t,e){if(!n.isBuffer(t))return undefined;if(!n.isBuffer(e))return undefined;if(typeof t.equals==="function")return t.equals(e);if(t.length!==e.length)return false;for(var r=0;r1)return new u(t,arguments[1]);return new u(t)}this.length=0;this.parent=undefined;if(typeof t==="number"){return l(this,t)}if(typeof t==="string"){return h(this,t,arguments.length>1?arguments[1]:"utf8")}return c(this,t)}function l(t,e){t=w(t,e<0?0:b(e)|0);if(!u.TYPED_ARRAY_SUPPORT){for(var r=0;r>>1;if(r)t.parent=s;return t}function b(t){if(t>=f()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+f().toString(16)+" bytes")}return t|0}function E(t,e){if(!(this instanceof E))return new E(t,e);var r=new u(t,e);delete r.parent;return r}u.isBuffer=function et(t){return!!(t!=null&&t._isBuffer)};u.compare=function rt(t,e){if(!u.isBuffer(t)||!u.isBuffer(e)){throw new TypeError("Arguments must be Buffers")}if(t===e)return 0;var r=t.length;var n=e.length;var i=0;var o=Math.min(r,n);while(i>>1;case"base64":return Q(t).length;default:if(n)return V(t).length;e=(""+e).toLowerCase();n=true}}}u.byteLength=_;u.prototype.length=undefined;u.prototype.parent=undefined;function x(t,e,r){var n=false;e=e|0;r=r===undefined||r===Infinity?this.length:r|0;if(!t)t="utf8";if(e<0)e=0;if(r>this.length)r=this.length;if(r<=e)return"";while(true){switch(t){case"hex":return C(this,e,r);case"utf8":case"utf-8":return O(this,e,r);case"ascii":return k(this,e,r);case"binary":return L(this,e,r);case"base64":return S(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase();n=true}}}u.prototype.toString=function ot(){var t=this.length|0;if(t===0)return"";if(arguments.length===0)return O(this,0,t);return x.apply(this,arguments)};u.prototype.equals=function st(t){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(this===t)return true;return u.compare(this,t)===0};u.prototype.inspect=function at(){var t="";var e=r.INSPECT_MAX_BYTES;if(this.length>0){t=this.toString("hex",0,e).match(/.{2}/g).join(" ");if(this.length>e)t+=" ... "}return""};u.prototype.compare=function ft(t){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(this===t)return 0;return u.compare(this,t)};u.prototype.indexOf=function ut(t,e){if(e>2147483647)e=2147483647;else if(e<-2147483648)e=-2147483648;e>>=0;if(this.length===0)return-1;if(e>=this.length)return-1;if(e<0)e=Math.max(this.length+e,0);if(typeof t==="string"){if(t.length===0)return-1;return String.prototype.indexOf.call(this,t,e)}if(u.isBuffer(t)){return r(this,t,e)}if(typeof t==="number"){if(u.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,t,e)}return r(this,[t],e)}function r(t,e,r){var n=-1;for(var i=0;r+ii){n=i}}var o=e.length;if(o%2!==0)throw new Error("Invalid hex string");if(n>o/2){n=o/2}for(var s=0;so)r=o;if(t.length>0&&(r<0||e<0)||e>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!n)n="utf8";var s=false;for(;;){switch(n){case"hex":return A(this,t,e,r);case"utf8":case"utf-8":return I(this,t,e,r);case"ascii":return T(this,t,e,r);case"binary":return j(this,t,e,r);case"base64":return B(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase();s=true}}};u.prototype.toJSON=function pt(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function S(t,e,r){if(e===0&&r===t.length){return n.fromByteArray(t)}else{return n.fromByteArray(t.slice(e,r))}}function O(t,e,r){r=Math.min(t.length,r);var n=[];var i=e;while(i239?4:o>223?3:o>191?2:1;if(i+a<=r){var f,u,l,h;switch(a){case 1:if(o<128){s=o}break;case 2:f=t[i+1];if((f&192)===128){h=(o&31)<<6|f&63;if(h>127){s=h}}break;case 3:f=t[i+1];u=t[i+2];if((f&192)===128&&(u&192)===128){h=(o&15)<<12|(f&63)<<6|u&63;if(h>2047&&(h<55296||h>57343)){s=h}}break;case 4:f=t[i+1];u=t[i+2];l=t[i+3];if((f&192)===128&&(u&192)===128&&(l&192)===128){h=(o&15)<<18|(f&63)<<12|(u&63)<<6|l&63;if(h>65535&&h<1114112){s=h}}}}if(s===null){s=65533;a=1}else if(s>65535){s-=65536;n.push(s>>>10&1023|55296);s=56320|s&1023}n.push(s);i+=a}return P(n)}var U=4096;function P(t){var e=t.length;if(e<=U){return String.fromCharCode.apply(String,t)}var r="";var n=0;while(nn)r=n;var i="";for(var o=e;or){t=r}if(e<0){e+=r;if(e<0)e=0}else if(e>r){e=r}if(er)throw new RangeError("Trying to access beyond buffer length")}u.prototype.readUIntLE=function vt(t,e,r){t=t|0;e=e|0;if(!r)q(t,e,this.length);var n=this[t];var i=1;var o=0;while(++o0&&(i*=256)){n+=this[t+--e]*i}return n};u.prototype.readUInt8=function yt(t,e){if(!e)q(t,1,this.length);return this[t]};u.prototype.readUInt16LE=function mt(t,e){if(!e)q(t,2,this.length);return this[t]|this[t+1]<<8};u.prototype.readUInt16BE=function wt(t,e){if(!e)q(t,2,this.length);return this[t]<<8|this[t+1]};u.prototype.readUInt32LE=function bt(t,e){if(!e)q(t,4,this.length);return(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216};u.prototype.readUInt32BE=function Et(t,e){if(!e)q(t,4,this.length);return this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])};u.prototype.readIntLE=function _t(t,e,r){t=t|0;e=e|0;if(!r)q(t,e,this.length);var n=this[t];var i=1;var o=0;while(++o=i)n-=Math.pow(2,8*e);return n};u.prototype.readIntBE=function xt(t,e,r){t=t|0;e=e|0;if(!r)q(t,e,this.length);var n=e;var i=1;var o=this[t+--n];while(n>0&&(i*=256)){o+=this[t+--n]*i}i*=128;if(o>=i)o-=Math.pow(2,8*e);return o};u.prototype.readInt8=function At(t,e){if(!e)q(t,1,this.length);if(!(this[t]&128))return this[t];return(255-this[t]+1)*-1};u.prototype.readInt16LE=function It(t,e){if(!e)q(t,2,this.length);var r=this[t]|this[t+1]<<8;return r&32768?r|4294901760:r};u.prototype.readInt16BE=function Tt(t,e){if(!e)q(t,2,this.length);var r=this[t+1]|this[t]<<8;return r&32768?r|4294901760:r};u.prototype.readInt32LE=function jt(t,e){if(!e)q(t,4,this.length);return this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24};u.prototype.readInt32BE=function Bt(t,e){if(!e)q(t,4,this.length);return this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]};u.prototype.readFloatLE=function Rt(t,e){if(!e)q(t,4,this.length);return i.read(this,t,true,23,4)};u.prototype.readFloatBE=function St(t,e){if(!e)q(t,4,this.length);return i.read(this,t,false,23,4)};u.prototype.readDoubleLE=function Ot(t,e){if(!e)q(t,8,this.length);return i.read(this,t,true,52,8)};u.prototype.readDoubleBE=function Ut(t,e){if(!e)q(t,8,this.length);return i.read(this,t,false,52,8)};function M(t,e,r,n,i,o){if(!u.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");if(e>i||et.length)throw new RangeError("index out of range")}u.prototype.writeUIntLE=function Pt(t,e,r,n){t=+t;e=e|0;r=r|0;if(!n)M(this,t,e,r,Math.pow(2,8*r),0);var i=1;var o=0;this[e]=t&255;while(++o=0&&(o*=256)){this[e+i]=t/o&255}return e+r};u.prototype.writeUInt8=function Lt(t,e,r){t=+t;e=e|0;if(!r)M(this,t,e,1,255,0);if(!u.TYPED_ARRAY_SUPPORT)t=Math.floor(t);this[e]=t&255;return e+1};function Y(t,e,r,n){if(e<0)e=65535+e+1;for(var i=0,o=Math.min(t.length-r,2);i>>(n?i:1-i)*8}}u.prototype.writeUInt16LE=function Ct(t,e,r){t=+t;e=e|0;if(!r)M(this,t,e,2,65535,0);if(u.TYPED_ARRAY_SUPPORT){this[e]=t&255;this[e+1]=t>>>8}else{Y(this,t,e,true)}return e+2};u.prototype.writeUInt16BE=function Dt(t,e,r){t=+t;e=e|0;if(!r)M(this,t,e,2,65535,0);if(u.TYPED_ARRAY_SUPPORT){this[e]=t>>>8;this[e+1]=t&255}else{Y(this,t,e,false)}return e+2};function N(t,e,r,n){if(e<0)e=4294967295+e+1;for(var i=0,o=Math.min(t.length-r,4);i>>(n?i:3-i)*8&255}}u.prototype.writeUInt32LE=function qt(t,e,r){t=+t;e=e|0;if(!r)M(this,t,e,4,4294967295,0);if(u.TYPED_ARRAY_SUPPORT){this[e+3]=t>>>24;this[e+2]=t>>>16;this[e+1]=t>>>8;this[e]=t&255}else{N(this,t,e,true)}return e+4};u.prototype.writeUInt32BE=function Mt(t,e,r){t=+t;e=e|0;if(!r)M(this,t,e,4,4294967295,0);if(u.TYPED_ARRAY_SUPPORT){this[e]=t>>>24;this[e+1]=t>>>16;this[e+2]=t>>>8;this[e+3]=t&255}else{N(this,t,e,false)}return e+4};u.prototype.writeIntLE=function Yt(t,e,r,n){t=+t;e=e|0;if(!n){var i=Math.pow(2,8*r-1);M(this,t,e,r,i-1,-i)}var o=0;var s=1;var a=t<0?1:0;this[e]=t&255;while(++o>0)-a&255}return e+r};u.prototype.writeIntBE=function Nt(t,e,r,n){t=+t;e=e|0;if(!n){var i=Math.pow(2,8*r-1);M(this,t,e,r,i-1,-i)}var o=r-1;var s=1;var a=t<0?1:0;this[e+o]=t&255;while(--o>=0&&(s*=256)){this[e+o]=(t/s>>0)-a&255}return e+r};u.prototype.writeInt8=function Ft(t,e,r){t=+t;e=e|0;if(!r)M(this,t,e,1,127,-128);if(!u.TYPED_ARRAY_SUPPORT)t=Math.floor(t);if(t<0)t=255+t+1;this[e]=t&255;return e+1};u.prototype.writeInt16LE=function Ht(t,e,r){t=+t;e=e|0;if(!r)M(this,t,e,2,32767,-32768);if(u.TYPED_ARRAY_SUPPORT){this[e]=t&255;this[e+1]=t>>>8}else{Y(this,t,e,true)}return e+2};u.prototype.writeInt16BE=function zt(t,e,r){t=+t;e=e|0;if(!r)M(this,t,e,2,32767,-32768);if(u.TYPED_ARRAY_SUPPORT){this[e]=t>>>8;this[e+1]=t&255}else{Y(this,t,e,false)}return e+2};u.prototype.writeInt32LE=function $t(t,e,r){t=+t;e=e|0;if(!r)M(this,t,e,4,2147483647,-2147483648);if(u.TYPED_ARRAY_SUPPORT){this[e]=t&255;this[e+1]=t>>>8;this[e+2]=t>>>16;this[e+3]=t>>>24}else{N(this,t,e,true)}return e+4};u.prototype.writeInt32BE=function Xt(t,e,r){t=+t;e=e|0;if(!r)M(this,t,e,4,2147483647,-2147483648);if(t<0)t=4294967295+t+1;if(u.TYPED_ARRAY_SUPPORT){this[e]=t>>>24;this[e+1]=t>>>16;this[e+2]=t>>>8;this[e+3]=t&255}else{N(this,t,e,false)}return e+4};function F(t,e,r,n,i,o){if(e>i||et.length)throw new RangeError("index out of range");if(r<0)throw new RangeError("index out of range")}function H(t,e,r,n,o){if(!o){F(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38)}i.write(t,e,r,n,23,4);return r+4}u.prototype.writeFloatLE=function Jt(t,e,r){return H(this,t,e,true,r)};u.prototype.writeFloatBE=function Gt(t,e,r){return H(this,t,e,false,r)};function z(t,e,r,n,o){if(!o){F(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308)}i.write(t,e,r,n,52,8);return r+8}u.prototype.writeDoubleLE=function Zt(t,e,r){return z(this,t,e,true,r)};u.prototype.writeDoubleBE=function Vt(t,e,r){return z(this,t,e,false,r)};u.prototype.copy=function Wt(t,e,r,n){if(!r)r=0;if(!n&&n!==0)n=this.length;if(e>=t.length)e=t.length;if(!e)e=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(t.length-e=0;o--){t[o+e]=this[o+r]}}else if(i<1e3||!u.TYPED_ARRAY_SUPPORT){for(o=0;o=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 t==="number"){for(n=e;n55295&&r<57344){if(!i){if(r>56319){if((e-=3)>-1)o.push(239,191,189);continue}else if(s+1===n){if((e-=3)>-1)o.push(239,191,189);continue}i=r;continue}if(r<56320){if((e-=3)>-1)o.push(239,191,189);i=r;continue}r=i-55296<<10|r-56320|65536}else if(i){if((e-=3)>-1)o.push(239,191,189)}i=null;if(r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else{throw new Error("Invalid code point")}}return o}function W(t){var e=[];for(var r=0;r>8;i=r%256;o.push(i);o.push(n)}return o}function Q(t){return n.toByteArray(J(t))}function tt(t,e,r,n){for(var i=0;i=e.length||i>=t.length)break;e[i+r]=t[i]}return i}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":3,ieee754:10,"is-array":12}],6:[function(t,e,r){(function(r){"use strict";var n=t("escape-string-regexp");var i=t("ansi-styles");var o=t("strip-ansi");var s=t("has-ansi");var a=t("supports-color");var f=Object.defineProperties;var u=r.platform==="win32"&&!/^xterm/i.test(r.env.TERM);function l(t){this.enabled=!t||t.enabled===undefined?a:t.enabled}if(u){i.blue.open=""}var h=function(){var t={};Object.keys(i).forEach(function(e){i[e].closeRe=new RegExp(n(i[e].close),"g");t[e]={get:function(){return p.call(this,this._styles.concat(e))}}});return t}();var c=f(function g(){},h);function p(t){var e=function(){return d.apply(e,arguments)};e._styles=t;e.enabled=this.enabled;e.__proto__=c;return e}function d(){var t=arguments;var e=t.length;var r=e!==0&&String(arguments[0]);if(e>1){for(var n=1;n>1;var l=-7;var h=r?i-1:0;var c=r?-1:1;var p=t[e+h];h+=c;o=p&(1<<-l)-1;p>>=-l;l+=a;for(;l>0;o=o*256+t[e+h],h+=c,l-=8){}s=o&(1<<-l)-1;o>>=-l;l+=n;for(;l>0;s=s*256+t[e+h],h+=c,l-=8){}if(o===0){o=1-u}else if(o===f){return s?NaN:(p?-1:1)*Infinity}else{s=s+Math.pow(2,n);o=o-u}return(p?-1:1)*s*Math.pow(2,o-n)};r.write=function(t,e,r,n,i,o){var s,a,f;var u=o*8-i-1;var l=(1<>1;var c=i===23?Math.pow(2,-24)-Math.pow(2,-77):0;var p=n?0:o-1;var d=n?1:-1;var v=e<0||e===0&&1/e<0?1:0;e=Math.abs(e);if(isNaN(e)||e===Infinity){a=isNaN(e)?1:0;s=l}else{s=Math.floor(Math.log(e)/Math.LN2);if(e*(f=Math.pow(2,-s))<1){s--;f*=2}if(s+h>=1){e+=c/f}else{e+=c*Math.pow(2,1-h)}if(e*f>=2){s++;f/=2}if(s+h>=l){a=0;s=l}else if(s+h>=1){a=(e*f-1)*Math.pow(2,i);s=s+h}else{a=e*Math.pow(2,h-1)*Math.pow(2,i);s=0}}for(;i>=8;t[r+p]=a&255,p+=d,a/=256,i-=8){}s=s<0;t[r+p]=s&255,p+=d,s/=256,u-=8){}t[r+p-d]|=v*128}},{}],11:[function(t,e,r){var n=r,i=t("buffer").Buffer,o=t("os");n.toBuffer=function a(t,e,r){r=~~r;var n;if(/^(\d{1,3}\.){3,3}\d{1,3}$/.test(t)){n=e||new i(r+4);t.split(/\./g).map(function(t){n[r++]=parseInt(t,10)&255})}else if(/^[a-f0-9:]+$/.test(t)){var o=t.split(/::/g,2),s=(o[0]||"").split(/:/g,8),a=(o[1]||"").split(/:/g,8);if(a.length===0){while(s.length<8)s.push("0000")}else if(s.length===0){while(a.length<8)a.unshift("0000")}else{while(s.length+a.length<8)s.push("0000")}n=e||new i(r+16);s.concat(a).map(function(t){t=parseInt(t,16);n[r++]=t>>8&255;n[r++]=t&255})}else{throw Error("Invalid ip address: "+t)}return n};n.toString=function f(t,e,r){e=~~e;r=r||t.length-e;var n=[];if(r===4){for(var i=0;i32){e="ipv6"}else{e=s(e)}var r=4;if(e==="ipv6"){r=16}var o=new i(r);for(var a=0,f=o.length;a>u)}return n.toString(o)};n.mask=function l(t,l){t=n.toBuffer(t);l=n.toBuffer(l);var e=new i(Math.max(t.length,l.length));if(t.length===l.length){for(var r=0;rt.length){i=e;o=t}var s=i.length-o.length;for(var r=s;r>>0};n.fromLong=function x(t){return(t>>>24)+"."+(t>>16&255)+"."+(t>>8&255)+"."+(t&255)};function s(t){return t?t.toLowerCase():"ipv4"}},{buffer:5,os:47}],12:[function(t,e,r){var n=Array.isArray;var i=Object.prototype.toString;e.exports=n||function(t){return!!t&&"[object Array]"==i.call(t)}},{}],13:[function(t,e,r){e.exports=function(t){return!!(t!=null&&(t._isBuffer||t.constructor&&typeof t.constructor.isBuffer==="function"&&t.constructor.isBuffer(t))); +}},{}],14:[function(t,e,r){var n=[];e.exports=n},{}],15:[function(t,e,r){var n=t("lodash._basecreate"),i=t("lodash.isobject"),o=t("lodash._setbinddata"),s=t("lodash._slice");var a=[];var f=a.push;function u(t){var e=t[0],r=t[2],a=t[4];function u(){if(r){var t=s(r);f.apply(t,arguments)}if(this instanceof u){var o=n(e.prototype),l=e.apply(o,t||arguments);return i(l)?l:o}return e.apply(a,t||arguments)}o(u,t);return u}e.exports=u},{"lodash._basecreate":16,"lodash._setbinddata":26,"lodash._slice":28,"lodash.isobject":36}],16:[function(t,e,r){(function(r){var n=t("lodash._isnative"),i=t("lodash.isobject"),o=t("lodash.noop");var s=n(s=Object.create)&&s;function a(t,e){return i(t)?s(t):{}}if(!s){a=function(){function t(){}return function(e){if(i(e)){t.prototype=e;var n=new t;t.prototype=null}return n||r.Object()}}()}e.exports=a}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"lodash._isnative":22,"lodash.isobject":36,"lodash.noop":39}],17:[function(t,e,r){var n=t("lodash.bind"),i=t("lodash.identity"),o=t("lodash._setbinddata"),s=t("lodash.support");var a=/^\s*function[ \n\r\t]+\w/;var f=/\bthis\b/;var u=Function.prototype.toString;function l(t,e,r){if(typeof t!="function"){return i}if(typeof e=="undefined"||!("prototype"in t)){return t}var l=t.__bindData__;if(typeof l=="undefined"){if(s.funcNames){l=!t.name}l=l||!s.funcDecomp;if(!l){var h=u.call(t);if(!s.funcNames){l=!a.test(h)}if(!l){l=f.test(h);o(t,l)}}}if(l===false||l!==true&&l[1]&1){return t}switch(r){case 1:return function(r){return t.call(e,r)};case 2:return function(r,n){return t.call(e,r,n)};case 3:return function(r,n,i){return t.call(e,r,n,i)};case 4:return function(r,n,i,o){return t.call(e,r,n,i,o)}}return n(t,e)}e.exports=l},{"lodash._setbinddata":26,"lodash.bind":29,"lodash.identity":34,"lodash.support":41}],18:[function(t,e,r){var n=t("lodash._basecreate"),i=t("lodash.isobject"),o=t("lodash._setbinddata"),s=t("lodash._slice");var a=[];var f=a.push;function u(t){var e=t[0],r=t[1],a=t[2],l=t[3],h=t[4],c=t[5];var p=r&1,d=r&2,v=r&4,g=r&8,y=e;function m(){var t=p?h:this;if(a){var o=s(a);f.apply(o,arguments)}if(l||v){o||(o=s(arguments));if(l){f.apply(o,l)}if(v&&o.length-1}})}}b.pop();E.pop();if(U){a(b);a(E)}return _}e.exports=w},{"lodash._getarray":21,"lodash._objecttypes":24,"lodash._releasearray":25,"lodash.forin":32,"lodash.isfunction":35}],20:[function(t,e,r){var n=t("lodash._basebind"),i=t("lodash._basecreatewrapper"),o=t("lodash.isfunction"),s=t("lodash._slice");var a=[];var f=a.push,u=a.unshift;function l(t,e,r,a,h,c){var p=e&1,d=e&2,v=e&4,g=e&8,y=e&16,m=e&32;if(!d&&!o(t)){throw new TypeError}if(y&&!r.length){e&=~16;y=r=false}if(m&&!a.length){e&=~32;m=a=false}var w=t&&t.__bindData__;if(w&&w!==true){w=s(w);if(w[2]){w[2]=s(w[2])}if(w[3]){w[3]=s(w[3])}if(p&&!(w[1]&1)){w[4]=h}if(!p&&w[1]&1){e|=8}if(v&&!(w[1]&4)){w[5]=c}if(y){f.apply(w[2]||(w[2]=[]),r)}if(m){u.apply(w[3]||(w[3]=[]),a)}w[1]|=e;return l.apply(null,w)}var b=e==1||e===17?n:i;return b([t,e,r,a,h,c])}e.exports=l},{"lodash._basebind":15,"lodash._basecreatewrapper":18,"lodash._slice":28,"lodash.isfunction":35}],21:[function(t,e,r){var n=t("lodash._arraypool");function i(){return n.pop()||[]}e.exports=i},{"lodash._arraypool":14}],22:[function(t,e,r){var n=Object.prototype;var i=n.toString;var o=RegExp("^"+String(i).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");function s(t){return typeof t=="function"&&o.test(t)}e.exports=s},{}],23:[function(t,e,r){var n=40;e.exports=n},{}],24:[function(t,e,r){var n={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};e.exports=n},{}],25:[function(t,e,r){var n=t("lodash._arraypool"),i=t("lodash._maxpoolsize");function o(t){t.length=0;if(n.length2?n(t,17,i(arguments,2),null,e):n(t,1,null,null,e)}e.exports=o},{"lodash._createwrapper":20,"lodash._slice":28}],30:[function(t,e,r){var n=t("lodash._basecreatecallback"),i=t("lodash._baseisequal"),o=t("lodash.isobject"),s=t("lodash.keys"),a=t("lodash.property");function f(t,e,r){var f=typeof t;if(t==null||f=="function"){return n(t,e,r)}if(f!="object"){return a(t)}var u=s(t),l=u[0],h=t[l];if(u.length==1&&h===h&&!o(h)){return function(t){var e=t[l];return h===e&&(h!==0||1/h==1/e)}}return function(e){var r=u.length,n=false;while(r--){if(!(n=i(e[u[r]],t[u[r]],null,true))){break}}return n}}e.exports=f},{"lodash._basecreatecallback":17,"lodash._baseisequal":19,"lodash.isobject":36,"lodash.keys":37,"lodash.property":40}],31:[function(t,e,r){var n=t("lodash.createcallback"),i=t("lodash.forown");function o(t,e,r){var o=[];e=n(e,r,3);var s=-1,a=t?t.length:0;if(typeof a=="number"){while(++s=r.length)throw _("invalid address: "+t);e.push([i,r[n]])}return e}function l(t){var e=[];n(t,function(t){var r=x(t);e.push(r.name);if(t.length>1)e.push(t[1])});return"/"+e.join("/")}function h(t){return n(t,function(t){var e=x(t);if(t.length>1)return[e.code,s.toBuffer(e.code,t[1])];return[e.code]})}function c(t){return n(t,function(t){var e=x(t);if(t.length>1)return[e.code,s.toString(e.code,t[1])];return[e.code]})}function p(t){return m(r.concat(n(t,function(t){var e=x(t);var n=new r([e.code]);if(t.length>1)n=r.concat([n,t[1]]);return n})))}function d(t){var e=[];for(var r=0;rt.length)throw _("Invalid address buffer: "+t.toString("hex"));e.push([n,s])}return e}function v(t){var e=d(t);var r=c(e);return l(r)}function g(t){t=E(t);var e=u(t);var r=h(e);return p(r)}function y(t){return g(t)}function m(t){var e=w(t);if(e)throw e;return new r(t)}function w(t){d(t)}function b(t){try{w(t);return true}catch(e){return false}}function E(t){return"/"+i(t.trim().split("/")).join("/")}function _(t){return new Error("Error parsing address: "+t)}function x(t){var e=a(t[0]);if(t.length>1&&e.size==0)throw _("tuple has address but protocol size is 0");return e}}).call(this,t("buffer").Buffer)},{"./convert":43,"./protocols":46,buffer:5,"lodash.filter":31,"lodash.map":38}],43:[function(t,e,r){(function(r){var n=t("ip");var i=t("./protocols");e.exports=o;function o(t,e){if(e instanceof r)return o.toString(t,e);else return o.toBuffer(t,e)}o.toString=function f(t,e){t=i(t);switch(t.code){case 4:case 41:return n.toString(e);case 6:case 17:case 33:case 132:return a(e)}return e.toString("hex")};o.toBuffer=function u(t,e){t=i(t);switch(t.code){case 4:case 41:return n.toBuffer(e);case 6:case 17:case 33:case 132:return s(parseInt(e,10))}return new r(e,"hex")};function s(t){var e=new r(2);e.writeUInt16BE(t,0);return e}function a(t){return t.readUInt16BE(0)}}).call(this,t("buffer").Buffer)},{"./protocols":46,buffer:5,ip:11}],44:[function(t,e,r){(function(r){var n=t("lodash.map");var i=t("xtend");var o=t("./codec");var s=t("buffer-equal");var a=t("./protocols");var f=new Error("Sorry, Not Implemented Yet.");e.exports=u;function u(t){if(!(this instanceof u))return new u(t);if(!t)t="";if(t instanceof r)this.buffer=o.fromBuffer(t);else if(typeof t=="string"||t instanceof String)this.buffer=o.fromString(t);else if(t.buffer&&t.protos&&t.protoCodes)this.buffer=o.fromBuffer(t.buffer);else throw new Error("addr must be a string, Buffer, or Multiaddr")}u.prototype.toString=function l(){return o.bufferToString(this.buffer)};u.prototype.toOptions=function h(){var t={};var e=this.toString().split("/");t.family=e[1]==="ip4"?"ipv4":"ipv6";t.host=e[2];t.port=e[4];return t};u.prototype.inspect=function c(){return""};u.prototype.protos=function p(){return n(this.protoCodes(),function(t){return i(a(t))})};u.prototype.protos=function d(){return n(this.protoCodes(),function(t){return i(a(t))})};u.prototype.protoCodes=function v(){var t=[];for(var e=0;e1){for(var r=1;r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},_=l-h,x=Math.floor,A=String.fromCharCode,I;function T(t){throw RangeError(E[t])}function j(t,e){var r=t.length;var n=[];while(r--){n[r]=e(t[r])}return n}function B(t,e){var r=t.split("@");var n="";if(r.length>1){n=r[0]+"@";t=r[1]}t=t.replace(b,".");var i=t.split(".");var o=j(i,e).join(".");return n+o}function R(t){var e=[],r=0,n=t.length,i,o;while(r=55296&&i<=56319&&r65535){t-=65536;e+=A(t>>>10&1023|55296);t=56320|t&1023}e+=A(t);return e}).join("")}function O(t){if(t-48<10){return t-22}if(t-65<26){return t-65}if(t-97<26){return t-97}return l}function U(t,e){return t+22+75*(t<26)-((e!=0)<<5)}function P(t,e,r){var n=0;t=r?x(t/d):t>>1;t+=x(t/e);for(;t>_*c>>1;n+=l){t=x(t/_)}return x(n+(_+1)*t/(t+p))}function k(t){var e=[],r=t.length,n,i=0,o=g,s=v,a,f,p,d,m,w,b,E,_;a=t.lastIndexOf(y);if(a<0){a=0}for(f=0;f=128){T("not-basic")}e.push(t.charCodeAt(f))}for(p=a>0?a+1:0;p=r){T("invalid-input")}b=O(t.charCodeAt(p++));if(b>=l||b>x((u-i)/m)){T("overflow")}i+=b*m;E=w<=s?h:w>=s+c?c:w-s;if(bx(u/_)){T("overflow")}m*=_}n=e.length+1;s=P(i-d,n,d==0);if(x(i/n)>u-o){T("overflow")}o+=x(i/n);i%=n;e.splice(i++,0,o)}return S(e)}function L(t){var e,r,n,i,o,s,a,f,p,d,m,w=[],b,E,_,I;t=R(t);b=t.length;e=g;r=0;o=v;for(s=0;s=e&&mx((u-r)/E)){T("overflow")}r+=(a-e)*E;e=a;for(s=0;su){T("overflow")}if(m==e){for(f=r,p=l;;p+=l){d=p<=o?h:p>=o+c?c:p-o;if(f0&&u>f){u=f}for(var l=0;l=0){p=h.substr(0,c);d=h.substr(c+1)}else{p=h;d=""}v=decodeURIComponent(p);g=decodeURIComponent(d);if(!n(s,v)){s[v]=g}else if(i(s[v])){s[v].push(g)}else{s[v]=[s[v],g]}}return s};var i=Array.isArray||function(t){return Object.prototype.toString.call(t)==="[object Array]"}},{}],51:[function(t,e,r){"use strict";var n=function(t){switch(typeof t){case"string":return t;case"boolean":return t?"true":"false";case"number":return isFinite(t)?t:"";default:return""}};e.exports=function(t,e,r,a){e=e||"&";r=r||"=";if(t===null){t=undefined}if(typeof t==="object"){return o(s(t),function(s){var a=encodeURIComponent(n(s))+r;if(i(t[s])){return o(t[s],function(t){return a+encodeURIComponent(n(t))}).join(e)}else{return a+encodeURIComponent(n(t[s]))}}).join(e)}if(!a)return"";return encodeURIComponent(n(a))+r+encodeURIComponent(n(t))};var i=Array.isArray||function(t){return Object.prototype.toString.call(t)==="[object Array]"};function o(t,e){if(t.map)return t.map(e);var r=[];for(var n=0;n=200&&e.status<300){return r.callback(t,e)}var i=new Error(e.statusText||"Unsuccessful HTTP response");i.original=t;i.response=e;i.status=e.status;r.callback(i,e)})}n(g.prototype);g.prototype.use=function(t){t(this);return this};g.prototype.timeout=function(t){this._timeout=t;return this};g.prototype.clearTimeout=function(){this._timeout=0;clearTimeout(this._timer);return this};g.prototype.abort=function(){if(this.aborted)return;this.aborted=true;this.xhr.abort();this.clearTimeout();this.emit("abort");return this};g.prototype.set=function(t,e){if(u(t)){for(var r in t){this.set(r,t[r])}return this}this._header[t.toLowerCase()]=e;this.header[t]=e;return this};g.prototype.unset=function(t){delete this._header[t.toLowerCase()];delete this.header[t];return this};g.prototype.getHeader=function(t){return this._header[t.toLowerCase()]};g.prototype.type=function(t){this.set("Content-Type",y.types[t]||t);return this};g.prototype.accept=function(t){this.set("Accept",y.types[t]||t);return this};g.prototype.auth=function(t,e){var r=btoa(t+":"+e);this.set("Authorization","Basic "+r);return this};g.prototype.query=function(t){if("string"!=typeof t)t=l(t);if(t)this._query.push(t);return this};g.prototype.field=function(t,e){if(!this._formData)this._formData=new o.FormData;this._formData.append(t,e);return this};g.prototype.attach=function(t,e,r){if(!this._formData)this._formData=new o.FormData;this._formData.append(t,e,r);return this};g.prototype.send=function(t){var e=u(t);var r=this.getHeader("Content-Type");if(e&&u(this._data)){for(var n in t){this._data[n]=t[n]}}else if("string"==typeof t){if(!r)this.type("form");r=this.getHeader("Content-Type");if("application/x-www-form-urlencoded"==r){this._data=this._data?this._data+"&"+t:t}else{this._data=(this._data||"")+t}}else{this._data=t}if(!e||a(t))return this;if(!r)this.type("json");return this};g.prototype.callback=function(t,e){var r=this._callback;this.clearTimeout();r(t,e)};g.prototype.crossDomainError=function(){var t=new Error("Origin is not allowed by Access-Control-Allow-Origin");t.crossDomain=true;this.callback(t)};g.prototype.timeoutError=function(){var t=this._timeout;var e=new Error("timeout of "+t+"ms exceeded");e.timeout=t;this.callback(e)};g.prototype.withCredentials=function(){this._withCredentials=true;return this};g.prototype.end=function(t){var e=this;var r=this.xhr=y.getXHR();var n=this._query.join("&");var i=this._timeout;var o=this._formData||this._data;this._callback=t||s;r.onreadystatechange=function(){if(4!=r.readyState)return;var t;try{t=r.status}catch(n){t=0}if(0==t){if(e.timedout)return e.timeoutError();if(e.aborted)return;return e.crossDomainError()}e.emit("end")};var f=function(t){if(t.total>0){t.percent=t.loaded/t.total*100}e.emit("progress",t)};if(this.hasListeners("progress")){r.onprogress=f}try{if(r.upload&&this.hasListeners("progress")){r.upload.onprogress=f}}catch(u){}if(i&&!this._timer){this._timer=setTimeout(function(){e.timedout=true;e.abort()},i)}if(n){n=y.serializeObject(n);this.url+=~this.url.indexOf("?")?"&"+n:"?"+n}r.open(this.method,this.url,true);if(this._withCredentials)r.withCredentials=true;if("GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof o&&!a(o)){var l=this.getHeader("Content-Type");var h=y.serialize[l?l.split(";")[0]:""];if(h)o=h(o)}for(var c in this.header){if(null==this.header[c])continue;r.setRequestHeader(c,this.header[c])}this.emit("request",this);r.send(o);return this};g.prototype.then=function(t,e){return this.end(function(r,n){r?e(r):t(n)})};y.Request=g;function y(t,e){if("function"==typeof e){return new g("GET",t).end(e)}if(1==arguments.length){return new g("GET",t)}return new g(t,e)}y.get=function(t,e,r){var n=y("GET",t);if("function"==typeof e)r=e,e=null;if(e)n.query(e);if(r)n.end(r);return n};y.head=function(t,e,r){var n=y("HEAD",t);if("function"==typeof e)r=e,e=null;if(e)n.send(e);if(r)n.end(r);return n};y.del=function(t,e){var r=y("DELETE",t);if(e)r.end(e);return r};y.patch=function(t,e,r){var n=y("PATCH",t);if("function"==typeof e)r=e,e=null;if(e)n.send(e);if(r)n.end(r);return n};y.post=function(t,e,r){var n=y("POST",t);if("function"==typeof e)r=e,e=null;if(e)n.send(e);if(r)n.end(r);return n};y.put=function(t,e,r){var n=y("PUT",t);if("function"==typeof e)r=e,e=null;if(e)n.send(e);if(r)n.end(r);return n};e.exports=y},{emitter:7,reduce:53}],57:[function(t,e,r){(function(t){"use strict";var r=t.argv;var n=r.indexOf("--");var i=function(t){t="--"+t;var e=r.indexOf(t);return e!==-1&&(n!==-1?e",'"',"`"," ","\r","\n"," "],f=["{","}","|","\\","^","`"].concat(a),u=["'"].concat(f),l=["%","/","?",";","#"].concat(u),h=["/","?","#"],c=255,p=/^[a-z0-9A-Z_-]{0,63}$/,d=/^([a-z0-9A-Z_-]{0,63})(.*)$/,v={javascript:true,"javascript:":true},g={javascript:true,"javascript:":true},y={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},m=t("querystring");function w(t,e,r){if(t&&A(t)&&t instanceof i)return t;var n=new i;n.parse(t,e,r);return n}i.prototype.parse=function(t,e,r){if(!x(t)){throw new TypeError("Parameter 'url' must be a string, not "+typeof t)}var i=t;i=i.trim();var s=o.exec(i);if(s){s=s[0];var a=s.toLowerCase();this.protocol=a;i=i.substr(s.length)}if(r||s||i.match(/^\/\/[^@\/]+@[^@\/]+/)){var f=i.substr(0,2)==="//";if(f&&!(s&&g[s])){i=i.substr(2);this.slashes=true}}if(!g[s]&&(f||s&&!y[s])){var w=-1;for(var b=0;b127){R+="x"}else{R+=B[S]}}if(!R.match(p)){var U=T.slice(0,b);var P=T.slice(b+1);var k=B.match(d);if(k){U.push(k[1]);P.unshift(k[2])}if(P.length){i="/"+P.join(".")+i}this.hostname=U.join(".");break}}}}if(this.hostname.length>c){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!I){var L=this.hostname.split(".");var C=[];for(var b=0;b0?r.host.split("@"):false;if(p){r.auth=p.shift();r.host=r.hostname=p.shift()}}r.search=t.search;r.query=t.query;if(!I(r.pathname)||!I(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.href=r.format();return r}if(!h.length){r.pathname=null;if(r.search){r.path="/"+r.search}else{r.path=null}r.href=r.format();return r}var d=h.slice(-1)[0];var v=(r.host||t.host)&&(d==="."||d==="..")||d==="";var m=0;for(var w=h.length;w>=0;w--){d=h[w];if(d=="."){h.splice(w,1)}else if(d===".."){h.splice(w,1);m++}else if(m){h.splice(w,1);m--}}if(!u&&!l){for(;m--;m){h.unshift("..")}}if(u&&h[0]!==""&&(!h[0]||h[0].charAt(0)!=="/")){h.unshift("")}if(v&&h.join("/").substr(-1)!=="/"){h.push("")}var b=h[0]===""||h[0]&&h[0].charAt(0)==="/";if(c){r.hostname=r.host=b?"":h.length?h.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&&h.length;if(u&&!b){h.unshift("")}if(!h.length){r.pathname=null;r.path=null}else{r.pathname=h.join("/")}if(!I(r.pathname)||!I(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.auth=t.auth||r.auth;r.slashes=r.slashes||t.slashes;r.href=r.format();return r};i.prototype.parseHost=function(){var t=this.host;var e=s.exec(t);if(e){e=e[0];if(e!==":"){this.port=e.substr(1)}t=t.substr(0,t.length-e.length)}if(t)this.hostname=t};function x(t){return typeof t==="string"}function A(t){return typeof t==="object"&&t!==null}function I(t){return t===null}function T(t){return t==null}},{punycode:49,querystring:52}],59:[function(t,e,r){e.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",multiaddr:"^1.0.0",superagent:"^1.4.0","superagent-logger":"^1.0.3"},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"}},{}],60:[function(t,e,r){var n=t("../package.json");r=e.exports={"api-path":"/api/v0/","user-agent":"/node-"+n.name+"/"+n.version+"/",host:"localhost",port:"5001"}},{"../package.json":59}],61:[function(t,e,r){(function(n){var i=t("multiaddr");var o=t("./config");var s=t("./request-api");r=e.exports=a;function a(t,e){var r=this;if(!(r instanceof a)){return new a(t,e)}try{var f=i(t).nodeAddress();o.host=f.address;o.port=f.port}catch(u){o.host=t;o.port=e||o.port}if(!o.host&&typeof window!=="undefined"){var l=window.location.host.split(":");o.host=l[0];o.port=l[1]}function h(t){return function(e,r){if(typeof e==="function"){r=e;e={}}return s(t,null,e,null,r)}}function c(t){return function(e,r,n){if(typeof r==="function"){n=r;r={}}return s(t,e,r,null,n)}}r.send=s;r.add=function(t,e,r){if(typeof e==="function"&&r===undefined){r=e;e={}}return s("add",null,e,t,r)};r.cat=c("cat");r.ls=c("ls");r.config={get:c("config"),set:function(t,e,r,n){if(typeof r==="function"){n=r;r={}}return s("config",[t,e],r,null,n)},show:function(t){return s("config/show",null,null,null,true,t)},replace:function(t,e){return s("config/replace",null,null,t,e)}};r.update={apply:h("update"),check:h("update/check"),log:h("update/log")};r.version=h("version");r.commands=h("commands");r.mount=function(t,e,r){if(typeof t==="function"){r=t;t=null}else if(typeof e==="function"){r=e;e=null}var n={};if(t)n.f=t;if(e)n.n=e;return s("mount",null,n,null,r)};r.diag={net:h("diag/net")};r.block={get:c("block/get"),put:function(t,e){if(Array.isArray(t)){return e(null,new Error("block.put() only accepts 1 file"))}return s("block/put",null,null,t,e)}};r.object={get:c("object/get"),put:function(t,e,r){if(typeof e==="function"){return r(null,new Error("Must specify an object encoding ('json' or 'protobuf')"))}return s("object/put",e,null,t,r)},data:c("object/data"),stat:c("object/stat"),links:c("object/links")};r.swarm={peers:h("swarm/peers"),connect:c("swarm/peers")};r.ping=function(t,e){return s("ping",t,{n:1},null,function(t,r){if(t)return e(t,null);e(null,r[1])})};r.id=function(t,e){if(typeof t==="function"){e=t;t=null}return s("id",t,null,null,e)};r.pin={add:function(t,e,r){if(typeof e==="function"){r=e;e=null}s("pin/add",t,e,null,r)},remove:function(t,e,r){if(typeof e==="function"){r=e;e=null}s("pin/rm",t,e,null,r)},list:function(t,e){if(typeof t==="function"){e=t;t=null}var r=null;if(t)r={type:t};return s("pin/ls",null,r,null,e)}};r.gateway={enable:h("gateway/enable"),disable:h("gateway/disable")};r.log={tail:function(t){return s("log/tail",null,{enc:"text"},null,true,t)}};r.name={publish:c("name/publish"),resolve:c("name/resolve")};r.Buffer=n;r.refs=c("refs");r.refs.local=h("refs/local");r.dht={findprovs:c("dht/findprovs"),get:function(t,e,r){if(typeof e==="function"&&!r){r=e;e=null}return s("dht/get",t,e,null,function(t,e){if(t)return r(t);if(!e)return r(new Error("empty response"));if(e.length===0)return r(new Error("no value returned for key"));if(e[0].Type===5){r(null,e[0].Extra)}else{r(e)}})},put:function(t,e,r,n){if(typeof r==="function"&&!n){n=r;r=null}return s("dht/put",[t,e],r,null,n)}}}}).call(this,t("buffer").Buffer)},{"./config":60,"./request-api":62,buffer:5,multiaddr:44}],62:[function(t,e,r){(function(n,i){var o=t("superagent");var s=t("superagent-logger");var a=t("./config");r=e.exports=l;function f(t,e,r){var n=!!e.headers;var i=n&&!!e.headers["x-stream-output"];var o=n&&!!e.headers["x-chunked-output"];if(i&&!t)return r();if(o&&t)return r();var s=[];var a="";e.text="";e.setEncoding("utf8");e.on("data",function(t){e.text+=t;if(!o){a+=t;return}try{var r=JSON.parse(t.toString());s.push(r)}catch(n){o=false;a+=t}});e.on("end",function(){var t;if(!o){try{t=JSON.parse(a);a=t}catch(e){}}else{a=s}return r(null,a)})}function u(t){t=Array.isArray(t)?t:[t];return t.map(function(t){if(n.isBuffer(t)){return{contents:t,opts:{filename:""}}}return{contents:t}})}function l(t,e,r,n,l,h){if(Array.isArray(t))t=t.join("/");r=r||{};if(e&&!Array.isArray(e))e=[e];if(e)r.arg=e;if(typeof l==="function"){h=l;l=false}delete r.followSymlinks;r["stream-channels"]=true;var c=n?"POST":"GET";var p=a["api-path"]+t;var d=a.host+":"+a.port+p;var v=o(c,d).set("User-Agent",a["user-agent"]).query(r).buffer(l).parse(f.bind(null,l)).on("error",h).on("response",g);if(i.env.DEBUG){v.use(s)}if(n){u(n).forEach(function(t){v.attach("file",t.contents,t.opts)})}v.end();function g(t){if(t.error)return h(t.error,null);var e=!!t.headers;var r=e&&!!t.headers["x-stream-output"];var n=e&&!!t.headers["x-chunked-output"];if(r&&!l)return h(null,t);if(n&&l)return h(null,t);return h(null,t.body)}return v}}).call(this,{isBuffer:t("../node_modules/is-buffer/index.js")},t("_process"))},{"../node_modules/is-buffer/index.js":13,"./config":60,_process:48,superagent:56,"superagent-logger":55}]},{},[61])(61)}); diff --git a/package.json b/package.json index a98d7dc4e..421620efc 100644 --- a/package.json +++ b/package.json @@ -5,12 +5,9 @@ "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" + "superagent": "^1.4.0", + "superagent-logger": "^1.0.3" }, "browserify": { "transform": [ diff --git a/src/get-files-stream.js b/src/get-files-stream.js deleted file mode 100644 index 4ad6d03f9..000000000 --- a/src/get-files-stream.js +++ /dev/null @@ -1,87 +0,0 @@ -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) -} diff --git a/src/request-api.js b/src/request-api.js index 20d5230ec..89799726c 100644 --- a/src/request-api.js +++ b/src/request-api.js @@ -1,14 +1,76 @@ -var http = require('http') -var qs = require('querystring') -var getFilesStream = require('./get-files-stream') +var request = require('superagent') +var logger = require('superagent-logger') + var config = require('./config') exports = module.exports = requestAPI -function requestAPI (path, args, opts, files, buffer, cb) { - var query, stream, contentType - contentType = 'application/json' +function safeJSONParser (buffer, res, done) { + var headers = !!res.headers + var stream = headers && !!res.headers['x-stream-output'] + var chunkedObjects = headers && !!res.headers['x-chunked-output'] + + // No need to parse + if (stream && !buffer) return done() + if (chunkedObjects && buffer) return done() + + var objects = [] + var data = '' + res.text = '' + res.setEncoding('utf8') + + res.on('data', function (chunk) { + res.text += chunk + + if (!chunkedObjects) { + data += chunk + return + } + + try { + var obj = JSON.parse(chunk.toString()) + objects.push(obj) + } catch (e) { + chunkedObjects = false + data += chunk + } + }) + + res.on('end', function () { + var parsed + + if (!chunkedObjects) { + try { + parsed = JSON.parse(data) + data = parsed + } catch (e) {} + } else { + data = objects + } + + return done(null, data) + }) +} + +function prepareFiles (files) { + files = Array.isArray(files) ? files : [files] + + return files.map(function (file) { + if (Buffer.isBuffer(file)) { + // Multipart requests require a filename to not + // trow, but if it's a buffer we don't know the name + return { + contents: file, + opts: {filename: ''} + } + } + + // Just a file path + return {contents: file} + }) +} +function requestAPI (path, args, opts, files, buffer, cb) { if (Array.isArray(path)) path = path.join('/') opts = opts || {} @@ -16,14 +78,6 @@ function requestAPI (path, args, opts, files, buffer, cb) { if (args && !Array.isArray(args)) args = [args] if (args) opts.arg = args - if (files) { - stream = getFilesStream(files, opts) - if (!stream.boundary) { - throw new Error('no boundary in multipart stream') - } - contentType = 'multipart/form-data; boundary=' + stream.boundary - } - if (typeof buffer === 'function') { cb = buffer buffer = false @@ -33,74 +87,42 @@ function requestAPI (path, args, opts, files, buffer, cb) { delete opts.followSymlinks opts['stream-channels'] = true - query = qs.stringify(opts) - - 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 - } - 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'] + var method = files ? 'POST' : 'GET' + var reqPath = config['api-path'] + path + var url = config.host + ':' + config.port + reqPath - if (stream && !buffer) return cb(null, res) - if (chunkedObjects && buffer) return cb(null, res) + var req = request(method, url) + .set('User-Agent', config['user-agent']) + .query(opts) + .buffer(buffer) + .parse(safeJSONParser.bind(null, buffer)) + .on('error', cb) + .on('response', handle) - res.on('data', function (chunk) { - if (!chunkedObjects) { - data += chunk - return data - } + if (process.env.DEBUG) { + req.use(logger) + } - try { - var obj = JSON.parse(chunk.toString()) - objects.push(obj) - } catch (e) { - chunkedObjects = false - data += chunk - } + if (files) { + prepareFiles(files).forEach(function (file) { + req.attach('file', file.contents, file.opts) }) - res.on('end', function () { - var parsed - - if (!chunkedObjects) { - try { - parsed = JSON.parse(data) - data = parsed - } catch (e) {} - } else { - data = objects - } + } - 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) - }) - }) + req.end() - req.on('error', function (err) { - return cb(err, null) - }) + function handle (res) { + if (res.error) return cb(res.error, null) + + var headers = !!res.headers + var stream = headers && !!res.headers['x-stream-output'] + var chunkedObjects = headers && !!res.headers['x-chunked-output'] + + if (stream && !buffer) return cb(null, res) + if (chunkedObjects && buffer) return cb(null, res) - if (stream) { - stream.pipe(req) - } else { - req.end() + return cb(null, res.body) } return req diff --git a/test/test.js b/test/test.js index dba726f5d..c709f868b 100644 --- a/test/test.js +++ b/test/test.js @@ -3,7 +3,6 @@ var ipfsApi = require('../src/index.js') var assert = require('assert') var fs = require('fs') var path = require('path') -var File = require('vinyl') // this comment is used by mocha, do not delete /*global describe, before, it*/ @@ -45,14 +44,7 @@ describe('ipfs node api', function () { it('add file', function (done) { this.timeout(10000) - var file = new File({ - cwd: path.dirname(testfile), - base: path.dirname(testfile), - path: testfile, - contents: fs.createReadStream(testfile) - }) - - ipfs.add(file, function (err, res) { + ipfs.add(testfile, function (err, res) { if (err) throw err var added = res[0] @@ -237,6 +229,7 @@ describe('ipfs node api', function () { this.timeout(10000) ipfs.refs(initDocs, {'format': ' '}, function (err, objs) { if (err) throw err + for (var i in objs) { var ref = objs[i] var refp = ref.Ref.replace('\n', '').split(' ')