mqtt.js源码3
由于代码过长博客不支持,故分为了三个部分,这里续接源码2
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;}if (codePoint - 65 < 26) {
return codePoint - 65;}if (codePoint - 97 < 26) {
return codePoint - 97;}return base;}/*** Converts a digit/integer into a basic code point.* @see `basicToDigit()`* @private* @param {Number} digit The numeric value of a basic code point.* @returns {Number} The basic code point whose value (when used for* representing integers) is `digit`, which needs to be in the range* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is* used; else, the lowercase form is used. The behavior is undefined* if `flag` is non-zero and `digit` has no uppercase form.*/function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z// 26..35 map to ASCII 0..9return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);}/*** Bias adaptation function as per section 3.4 of RFC 3492.* https://tools.ietf.org/html/rfc3492#section-3.4* @private*/function adapt(delta, numPoints, firstTime) {
var k = 0;delta = firstTime ? floor(delta / damp) : delta >> 1;delta += floor(delta / numPoints);for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);}return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));}/*** Converts a Punycode string of ASCII-only symbols to a string of Unicode* symbols.* @memberOf punycode* @param {String} input The Punycode string of ASCII-only symbols.* @returns {String} The resulting string of Unicode symbols.*/function decode(input) {
// Don't use UCS-2var output = [],inputLength = input.length,out,i = 0,n = initialN,bias = initialBias,basic,j,index,oldi,w,k,digit,t,/** Cached calculation results */baseMinusT;// Handle the basic code points: let `basic` be the number of input code// points before the last delimiter, or `0` if there is none, then copy// the first basic code points to the output.basic = input.lastIndexOf(delimiter);if (basic < 0) {
basic = 0;}for (j = 0; j < basic; ++j) {
// if it's not a basic code pointif (input.charCodeAt(j) >= 0x80) {
error('not-basic');}output.push(input.charCodeAt(j));}// Main decoding loop: start just after the last delimiter if any basic code// points were copied; start at the beginning otherwise.for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */ ) {
// `index` is the index of the next character to be consumed.// Decode a generalized variable-length integer into `delta`,// which gets added to `i`. The overflow checking is easier// if we increase `i` as we go, then subtract off its starting// value at the end to obtain `delta`.for (oldi = i, w = 1, k = base; /* no condition */ ; k += base) {
if (index >= inputLength) {
error('invalid-input');}digit = basicToDigit(input.charCodeAt(index++));if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');}i += digit * w;t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);if (digit < t) {
break;}baseMinusT = base - t;if (w > floor(maxInt / baseMinusT)) {
error('overflow');}w *= baseMinusT;}out = output.length + 1;bias = adapt(i - oldi, out, oldi == 0);// `i` was supposed to wrap around from `out` to `0`,// incrementing `n` each time, so we'll fix that now:if (floor(i / out) > maxInt - n) {
error('overflow');}n += floor(i / out);i %= out;// Insert `n` at position `i` of the outputoutput.splice(i++, 0, n);}return ucs2encode(output);}/*** Converts a string of Unicode symbols (e.g. a domain name label) to a* Punycode string of ASCII-only symbols.* @memberOf punycode* @param {String} input The string of Unicode symbols.* @returns {String} The resulting Punycode string of ASCII-only symbols.*/function encode(input) {
var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output = [],/** `inputLength` will hold the number of code points in `input`. */inputLength,/** Cached calculation results */handledCPCountPlusOne,baseMinusT,qMinusT;// Convert the input in UCS-2 to Unicodeinput = ucs2decode(input);// Cache the lengthinputLength = input.length;// Initialize the staten = initialN;delta = 0;bias = initialBias;// Handle the basic code pointsfor (j = 0; j < inputLength; ++j) {
currentValue = input[j];if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));}}handledCPCount = basicLength = output.length;// `handledCPCount` is the number of code points that have been handled;// `basicLength` is the number of basic code points.// Finish the basic string - if it is not empty - with a delimiterif (basicLength) {
output.push(delimiter);}// Main encoding loop:while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next// larger one:for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];if (currentValue >= n && currentValue < m) {
m = currentValue;}}// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,// but guard against overflowhandledCPCountPlusOne = handledCPCount + 1;if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');}delta += (m - n) * handledCPCountPlusOne;n = m;for (j = 0; j < inputLength; ++j) {
currentValue = input[j];if (currentValue < n && ++delta > maxInt) {
error('overflow');}if (currentValue == n) {
// Represent delta as a generalized variable-length integerfor (q = delta, k = base; /* no condition */ ; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);if (q < t) {
break;}qMinusT = q - t;baseMinusT = base - t;output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));q = floor(qMinusT / baseMinusT);}output.push(stringFromCharCode(digitToBasic(q, 0)));bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);delta = 0;++handledCPCount;}}++delta;++n;}return output.join('');}/*** Converts a Punycode string representing a domain name or an email address* to Unicode. Only the Punycoded parts of the input will be converted, i.e.* it doesn't matter if you call it on a string that has already been* converted to Unicode.* @memberOf punycode* @param {String} input The Punycoded domain name or email address to* convert to Unicode.* @returns {String} The Unicode representation of the given Punycode* string.*/function toUnicode(input) {
return mapDomain(input, function (string) {
return regexPunycode.test(string) ?decode(string.slice(4).toLowerCase()) :string;});}/*** Converts a Unicode string representing a domain name or an email address to* Punycode. Only the non-ASCII parts of the domain name will be converted,* i.e. it doesn't matter if you call it with a domain that's already in* ASCII.* @memberOf punycode* @param {String} input The domain name or email address to convert, as a* Unicode string.* @returns {String} The Punycode representation of the given domain name or* email address.*/function toASCII(input) {
return mapDomain(input, function (string) {
return regexNonASCII.test(string) ?'xn--' + encode(string) :string;});}/*--------------------------------------------------------------------------*//** Define the public API */punycode = {
/*** A string representing the current Punycode.js version number.* @memberOf punycode* @type String*/'version': '1.4.1',/*** An object of methods to convert from JavaScript's internal character* representation (UCS-2) to Unicode code points, and back.* @see <https://mathiasbynens.be/notes/javascript-encoding>* @memberOf punycode* @type Object*/'ucs2': {
'decode': ucs2decode,'encode': ucs2encode},'decode': decode,'encode': encode,'toASCII': toASCII,'toUnicode': toUnicode};/** Expose `punycode` */// Some AMD build optimizers, like r.js, check for specific condition patterns// like the following:if (typeof define == 'function' &&typeof define.amd == 'object' &&define.amd) {
define('punycode', function () {
return punycode;});} else if (freeExports && freeModule) {
if (module.exports == freeExports) {
// in Node.js, io.js, or RingoJS v0.8.0+freeModule.exports = punycode;} else {
// in Narwhal or RingoJS v0.7.0-for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);}}} else {
// in Rhino or a web browserroot.punycode = punycode;}}(this));}).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {
})}, {
}],94: [function (require, module, exports) {
// Copyright Joyent, Inc. and other Node contributors.//// Permission is hereby granted, free of charge, to any person obtaining a// copy of this software and associated documentation files (the// "Software"), to deal in the Software without restriction, including// without limitation the rights to use, copy, modify, merge, publish,// distribute, sublicense, and/or sell copies of the Software, and to permit// persons to whom the Software is furnished to do so, subject to the// following conditions://// The above copyright notice and this permission notice shall be included// in all copies or substantial portions of the Software.//// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE// USE OR OTHER DEALINGS IN THE SOFTWARE.'use strict';// If obj.hasOwnProperty has been overridden, then calling// obj.hasOwnProperty(prop) will break.// See: https://github.com/joyent/node/issues/1707function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);}module.exports = function (qs, sep, eq, options) {
sep = sep || '&';eq = eq || '=';var obj = {
};if (typeof qs !== 'string' || qs.length === 0) {
return obj;}var regexp = /\+/g;qs = qs.split(sep);var maxKeys = 1000;if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;}var len = qs.length;// maxKeys <= 0 means that we should not limit keys countif (maxKeys > 0 && len > maxKeys) {
len = maxKeys;}for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),idx = x.indexOf(eq),kstr, vstr, k, v;if (idx >= 0) {
kstr = x.substr(0, idx);vstr = x.substr(idx + 1);} else {
kstr = x;vstr = '';}k = decodeURIComponent(kstr);v = decodeURIComponent(vstr);if (!hasOwnProperty(obj, k)) {
obj[k] = v;} else if (isArray(obj[k])) {
obj[k].push(v);} else {
obj[k] = [obj[k], v];}}return obj;};var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';};}, {
}],95: [function (require, module, exports) {
// Copyright Joyent, Inc. and other Node contributors.//// Permission is hereby granted, free of charge, to any person obtaining a// copy of this software and associated documentation files (the// "Software"), to deal in the Software without restriction, including// without limitation the rights to use, copy, modify, merge, publish,// distribute, sublicense, and/or sell copies of the Software, and to permit// persons to whom the Software is furnished to do so, subject to the// following conditions://// The above copyright notice and this permission notice shall be included// in all copies or substantial portions of the Software.//// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE// USE OR OTHER DEALINGS IN THE SOFTWARE.'use strict';var stringifyPrimitive = function (v) {
switch (typeof v) {
case 'string':return v;case 'boolean':return v ? 'true' : 'false';case 'number':return isFinite(v) ? v : '';default:return '';}};module.exports = function (obj, sep, eq, name) {
sep = sep || '&';eq = eq || '=';if (obj === null) {
obj = undefined;}if (typeof obj === 'object') {
return map(objectKeys(obj), function (k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;if (isArray(obj[k])) {
return map(obj[k], function (v) {
return ks + encodeURIComponent(stringifyPrimitive(v));}).join(sep);} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));}}).join(sep);}if (!name) return '';return encodeURIComponent(stringifyPrimitive(name)) + eq +encodeURIComponent(stringifyPrimitive(obj));};var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';};function map(xs, f) {
if (xs.map) return xs.map(f);var res = [];for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));}return res;}var objectKeys = Object.keys || function (obj) {
var res = [];for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);}return res;};}, {
}],96: [function (require, module, exports) {
'use strict';exports.decode = exports.parse = require('./decode');exports.encode = exports.stringify = require('./encode');}, {
"./decode": 94,"./encode": 95}],97: [function (require, module, exports) {
module.exports = require('./lib/_stream_duplex.js');}, {
"./lib/_stream_duplex.js": 98}],98: [function (require, module, exports) {
// Copyright Joyent, Inc. and other Node contributors.//// Permission is hereby granted, free of charge, to any person obtaining a// copy of this software and associated documentation files (the// "Software"), to deal in the Software without restriction, including// without limitation the rights to use, copy, modify, merge, publish,// distribute, sublicense, and/or sell copies of the Software, and to permit// persons to whom the Software is furnished to do so, subject to the// following conditions://// The above copyright notice and this permission notice shall be included// in all copies or substantial portions of the Software.//// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE// USE OR OTHER DEALINGS IN THE SOFTWARE.// a duplex stream is just a stream that is both readable and writable.// Since JS doesn't have multiple prototypal inheritance, this class// prototypally inherits from Readable, and then parasitically from// Writable.'use strict';/*<replacement>*/var pna = require('process-nextick-args');/*</replacement>*//*<replacement>*/var objectKeys = Object.keys || function (obj) {
var keys = [];for (var key in obj) {
keys.push(key);}return keys;};/*</replacement>*/module.exports = Duplex;/*<replacement>*/var util = require('core-util-is');util.inherits = require('inherits');/*</replacement>*/var Readable = require('./_stream_readable');var Writable = require('./_stream_writable');util.inherits(Duplex, Readable);{
// avoid scope creep, the keys array can then be collectedvar keys = objectKeys(Writable.prototype);for (var v = 0; v < keys.length; v++) {
var method = keys[v];if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];}}function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);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);}Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable// because otherwise some prototype manipulation in// userland will failenumerable: false,get: function () {
return this._writableState.highWaterMark;}});// the no-half-open enforcerfunction 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.pna.nextTick(onEndNT, this);}function onEndNT(self) {
self.end();}Object.defineProperty(Duplex.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined || this._writableState === undefined) {
return false;}return this._readableState.destroyed && this._writableState.destroyed;},set: function (value) {
// we ignore the value if the stream// has not been initialized yetif (this._readableState === undefined || this._writableState === undefined) {
return;}// backward compatibility, the user is explicitly// managing destroyedthis._readableState.destroyed = value;this._writableState.destroyed = value;}});Duplex.prototype._destroy = function (err, cb) {
this.push(null);this.end();pna.nextTick(cb, err);};}, {
"./_stream_readable": 100,"./_stream_writable": 102,"core-util-is": 14,"inherits": 80,"process-nextick-args": 91}],99: [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.'use strict';module.exports = PassThrough;var Transform = require('./_stream_transform');/*<replacement>*/var util = require('core-util-is');util.inherits = require('inherits');/*</replacement>*/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": 101,"core-util-is": 14,"inherits": 80}],100: [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.'use strict';/*<replacement>*/var pna = require('process-nextick-args');/*</replacement>*/module.exports = Readable;/*<replacement>*/var isArray = require('isarray');/*</replacement>*//*<replacement>*/var Duplex;/*</replacement>*/Readable.ReadableState = ReadableState;/*<replacement>*/var EE = require('events').EventEmitter;var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;};/*</replacement>*//*<replacement>*/var Stream = require('./internal/streams/stream');/*</replacement>*//*<replacement>*/var Buffer = require('safe-buffer').Buffer;var OurUint8Array = global.Uint8Array || function () {
};function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);}function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;}/*</replacement>*//*<replacement>*/var util = require('core-util-is');util.inherits = require('inherits');/*</replacement>*//*<replacement>*/var debugUtil = require('util');var debug = void 0;if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');} else {
debug = function () {
};}/*</replacement>*/var BufferList = require('./internal/streams/BufferList');var destroyImpl = require('./internal/streams/destroy');var StringDecoder;util.inherits(Readable, Stream);var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own// event emitter implementation with them.if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);// This is a hack to make sure that our error handler is attached before any// userland ones. NEVER DO THIS. This is here only because this code needs// to continue to work with older versions of Node.js that do not include// the prependListener() method. The goal is to eventually remove this hack.if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];}function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');options = options || {
};// Duplex streams are both readable and writable, but share// the same options object.// However, some cases require setting options to different// values for the readable and the writable sides of the duplex stream.// These options can be provided separately as readableXXX and writableXXX.var isDuplex = stream instanceof Duplex;// object stream flag. Used to make read(n) ignore n and to// make all the buffer merging and length checks go awaythis.objectMode = !!options.objectMode;if (isDuplex) 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 readableHwm = options.readableHighWaterMark;var defaultHwm = this.objectMode ? 16 : 16 * 1024;if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;// cast to ints.this.highWaterMark = Math.floor(this.highWaterMark);// A linked list is used to store data chunks instead of an array because the// linked list can remove elements from the beginning faster than// array.shift()this.buffer = new BufferList();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 event 'readable'/'data' is emitted// 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 read 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;this.resumeScheduled = false;// has it been destroyedthis.destroyed = 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';// the number of writers that are awaiting a drain event in .pipe()sthis.awaitDrain = 0;// if true, a maybeReadMore has been scheduledthis.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) {
Duplex = Duplex || require('./_stream_duplex');if (!(this instanceof Readable)) return new Readable(options);this._readableState = new ReadableState(options, this);// legacythis.readable = true;if (options) {
if (typeof options.read === 'function') this._read = options.read;if (typeof options.destroy === 'function') this._destroy = options.destroy;}Stream.call(this);}Object.defineProperty(Readable.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined) {
return false;}return this._readableState.destroyed;},set: function (value) {
// we ignore the value if the stream// has not been initialized yetif (!this._readableState) {
return;}// backward compatibility, the user is explicitly// managing destroyedthis._readableState.destroyed = value;}});Readable.prototype.destroy = destroyImpl.destroy;Readable.prototype._undestroy = destroyImpl.undestroy;Readable.prototype._destroy = function (err, cb) {
this.push(null);cb(err);};// Manually shove something into the read() buffer.// This returns true if the highWaterMark has not been hit yet,// similar to how Writable.write() returns true if you should// write() some more.Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;var skipChunkCheck;if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);encoding = '';}skipChunkCheck = true;}} else {
skipChunkCheck = true;}return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);};// Unshift should *always* be something directly out of read()Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);};function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var state = stream._readableState;if (chunk === null) {
state.reading = false;onEofChunk(stream, state);} else {
var er;if (!skipChunkCheck) er = chunkInvalid(state, chunk);if (er) {
stream.emit('error', er);} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);}if (addToFront) {
if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);} else if (state.ended) {
stream.emit('error', new Error('stream.push() after EOF'));} else {
state.reading = false;if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);} else {
addChunk(stream, state, chunk, false);}}} else if (!addToFront) {
state.reading = false;}}return needMoreData(state);}function addChunk(stream, state, chunk, addToFront) {
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);}function chunkInvalid(state, chunk) {
var er;if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');}return er;}// 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);}Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;};// 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 > 8MBvar MAX_HWM = 0x800000;function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in// tiny amountsn--;n |= n >>> 1;n |= n >>> 2;n |= n >>> 4;n |= n >>> 8;n |= n >>> 16;n++;}return n;}// This function is designed to be inlinable, so please take care when making// changes to the function body.function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;if (state.objectMode) return 1;if (n !== n) {
// Only flow one buffer at a timeif (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;}// If we're asking for more than the current hwm, then raise the hwm.if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);if (n <= state.length) return n;// Don't have enoughif (!state.ended) {
state.needReadable = true;return 0;}return state.length;}// you can override either this method, or the async _read(n) below.Readable.prototype.read = function (n) {
debug('read', n);n = parseInt(n, 10);var state = this._readableState;var nOrig = n;if (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 someif (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);} else 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 methodthis._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 (!state.reading) n = howMuchToRead(nOrig, state);}var ret;if (n > 0) ret = fromList(n, state);else ret = null;if (ret === null) {
state.needReadable = true;n = 0;} else {
state.length -= n;}if (state.length === 0) {
// If we have nothing in the buffer, then we want to know// as soon as we *do* get something into the buffer.if (!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) endReadable(this);}if (ret !== null) this.emit('data', ret);return ret;};function onEofChunk(stream, state) {
if (state.ended) return;if (state.decoder) {
var chunk = state.decoder.end();if (chunk && chunk.length) {
state.buffer.push(chunk);state.length += state.objectMode ? 1 : chunk.length;}}state.ended = true;// emit 'readable' now to make sure it gets picked up.emitReadable(stream);}// Don't emit readable right away in sync mode, because this can trigger// another read() call => stack overflow. This way, it might trigger// a nextTick recursion warning, but that's not so bad.function emitReadable(stream) {
var state = stream._readableState;state.needReadable = false;if (!state.emittedReadable) {
debug('emitReadable', state.flowing);state.emittedReadable = true;if (state.sync) pna.nextTick(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;pna.nextTick(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('_read() is 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 : unpipe;if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);dest.on('unpipe', onunpipe);function onunpipe(readable, unpipeInfo) {
debug('onunpipe');if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;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);var cleanedUp = false;function cleanup() {
debug('cleanup');// cleanup event handlers once the pipe is brokendest.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', unpipe);src.removeListener('data', ondata);cleanedUp = true;// 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 the user pushes more data while we're writing to dest then we'll end up// in ondata again. However, we only want to increase awaitDrain once because// dest will only emit one 'drain' event for the multiple writes.// => Introduce a guard on increasing awaitDrain.var increasedAwaitDrain = false;src.on('data', ondata);function ondata(chunk) {
debug('ondata');increasedAwaitDrain = false;var ret = dest.write(chunk);if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible// to get stuck in a permanently paused state if that write// also returned false.// => Check whether `dest` is still a piping destination.if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain = true;}src.pause();}}// if the dest has an error, then stop piping into it.// however, don't suppress the throwing behavior for this.function onerror(er) {
debug('onerror', er);unpipe();dest.removeListener('error', onerror);if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);}// Make sure our error handler is attached before userland ones.prependListener(dest, 'error', onerror);// 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 todest.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 && EElistenerCount(src, 'data')) {
state.flowing = true;flow(src);}};}Readable.prototype.unpipe = function (dest) {
var state = this._readableState;var unpipeInfo = {
hasUnpiped: false};// 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, unpipeInfo);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, unpipeInfo);}return this;}// try to find the right one.var index = indexOf(state.pipes, dest);if (index === -1) return this;state.pipes.splice(index, 1);state.pipesCount -= 1;if (state.pipesCount === 1) state.pipes = state.pipes[0];dest.emit('unpipe', this, unpipeInfo);return this;};// set up data events if they are asked for// Ensure readable listeners eventually get somethingReadable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly pausedif (this._readableState.flowing !== false) this.resume();} else if (ev === 'readable') {
var state = this._readableState;if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;state.emittedReadable = false;if (!state.reading) {
pna.nextTick(nReadingNextTick, this);} else if (state.length) {
emitReadable(this);}}}return res;};Readable.prototype.addListener = Readable.prototype.on;function nReadingNextTick(self) {
debug('readable nexttick read 0');self.read(0);}// pause() and resume() are remnants of the legacy readable stream API// If the user uses them, then switch into old mode.Readable.prototype.resume = function () {
var state = this._readableState;if (!state.flowing) {
debug('resume');state.flowing = true;resume(this, state);}return this;};function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;pna.nextTick(resume_, stream, state);}}function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');stream.read(0);}state.resumeScheduled = false;state.awaitDrain = 0;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);while (state.flowing && stream.read() !== null) {
}}// 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 _this = this;var state = this._readableState;var paused = false;stream.on('end', function () {
debug('wrapped end');if (state.decoder && !state.ended) {
var chunk = state.decoder.end();if (chunk && chunk.length) _this.push(chunk);}_this.push(null);});stream.on('data', function (chunk) {
debug('wrapped data');if (state.decoder) chunk = state.decoder.write(chunk);// don't skip over falsy values in objectModeif (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;var ret = _this.push(chunk);if (!ret) {
paused = true;stream.pause();}});// proxy all the other methods.// important when wrapping filters and duplexes.for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);};}(i);}}// proxy certain important events.for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));}// when we try to consume some more bytes, simply unpause the// underlying stream.this._read = function (n) {
debug('wrapped _read', n);if (paused) {
paused = false;stream.resume();}};return this;};Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
// making it explicit this property is not enumerable// because otherwise some prototype manipulation in// userland will failenumerable: false,get: function () {
return this._readableState.highWaterMark;}});// 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.// This function is designed to be inlinable, so please take care when making// changes to the function body.function fromList(n, state) {
// nothing bufferedif (state.length === 0) return null;var ret;if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the listif (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);state.buffer.clear();} else {
// read part of listret = fromListPartial(n, state.buffer, state.decoder);}return ret;}// Extracts only enough buffered data to satisfy the amount requested.// This function is designed to be inlinable, so please take care when making// changes to the function body.function fromListPartial(n, list, hasStrings) {
var ret;if (n < list.head.data.length) {
// slice is the same for buffers and stringsret = list.head.data.slice(0, n);list.head.data = list.head.data.slice(n);} else if (n === list.head.data.length) {
// first chunk is a perfect matchret = list.shift();} else {
// result spans more than one bufferret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);}return ret;}// Copies a specified amount of characters from the list of buffered data// chunks.// This function is designed to be inlinable, so please take care when making// changes to the function body.function copyFromBufferString(n, list) {
var p = list.head;var c = 1;var ret = p.data;n -= ret.length;while (p = p.next) {
var str = p.data;var nb = n > str.length ? str.length : n;if (nb === str.length) ret += str;else ret += str.slice(0, n);n -= nb;if (n === 0) {
if (nb === str.length) {
++c;if (p.next) list.head = p.next;else list.head = list.tail = null;} else {
list.head = p;p.data = str.slice(nb);}break;}++c;}list.length -= c;return ret;}// Copies a specified amount of bytes from the list of buffered data chunks.// This function is designed to be inlinable, so please take care when making// changes to the function body.function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);var p = list.head;var c = 1;p.data.copy(ret);n -= p.data.length;while (p = p.next) {
var buf = p.data;var nb = n > buf.length ? buf.length : n;buf.copy(ret, ret.length - n, 0, nb);n -= nb;if (n === 0) {
if (nb === buf.length) {
++c;if (p.next) list.head = p.next;else list.head = list.tail = null;} else {
list.head = p;p.data = buf.slice(nb);}break;}++c;}list.length -= c;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;pna.nextTick(endReadableNT, state, stream);}}function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;stream.readable = false;stream.emit('end');}}function 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'), typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {
})}, {
"./_stream_duplex": 98,"./internal/streams/BufferList": 103,"./internal/streams/destroy": 104,"./internal/streams/stream": 105,"_process": 92,"core-util-is": 14,"events": 13,"inherits": 80,"isarray": 106,"process-nextick-args": 91,"safe-buffer": 110,"string_decoder/": 107,"util": 11}],101: [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.'use strict';module.exports = Transform;var Duplex = require('./_stream_duplex');/*<replacement>*/var util = require('core-util-is');util.inherits = require('inherits');/*</replacement>*/util.inherits(Transform, Duplex);function afterTransform(er, data) {
var ts = this._transformState;ts.transforming = false;var cb = ts.writecb;if (!cb) {
return this.emit('error', new Error('write callback called multiple times'));}ts.writechunk = null;ts.writecb = null;if (data != null) // single equals check for both `null` and `undefined`this.push(data);cb(er);var rs = this._readableState;rs.reading = false;if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);}}function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);Duplex.call(this, options);this._transformState = {
afterTransform: afterTransform.bind(this),needTransform: false,transforming: false,writecb: null,writechunk: null,writeencoding: null};// 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;if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;if (typeof options.flush === 'function') this._flush = options.flush;}// When the writable side finishes, then flush out anything remaining.this.on('prefinish', prefinish);}function prefinish() {
var _this = this;if (typeof this._flush === 'function') {
this._flush(function (er, data) {
done(_this, er, data);});} else {
done(this, null, null);}}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('_transform() is 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;}};Transform.prototype._destroy = function (err, cb) {
var _this2 = this;Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);_this2.emit('close');});};function done(stream, er, data) {
if (er) return stream.emit('error', er);if (data != null) // single equals check for both `null` and `undefined`stream.push(data);// if there's nothing in the write buffer, then that means// that nothing more will ever be providedif (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');return stream.push(null);}}, {
"./_stream_duplex": 98,"core-util-is": 14,"inherits": 80}],102: [function (require, module, exports) {
(function (process, global, setImmediate) {
// 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, encoding, cb), and it'll handle all// the drain event emission and buffering.'use strict';/*<replacement>*/var pna = require('process-nextick-args');/*</replacement>*/module.exports = Writable;/* <replacement> */function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;this.encoding = encoding;this.callback = cb;this.next = null;}// It seems a linked list but it is not// there will be only 2 of these for each streamfunction CorkedRequest(state) {
var _this = this;this.next = null;this.entry = null;this.finish = function () {
onCorkedFinish(_this, state);};}/* </replacement> *//*<replacement>*/var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;/*</replacement>*//*<replacement>*/var Duplex;/*</replacement>*/Writable.WritableState = WritableState;/*<replacement>*/var util = require('core-util-is');util.inherits = require('inherits');/*</replacement>*//*<replacement>*/var internalUtil = {
deprecate: require('util-deprecate')};/*</replacement>*//*<replacement>*/var Stream = require('./internal/streams/stream');/*</replacement>*//*<replacement>*/var Buffer = require('safe-buffer').Buffer;var OurUint8Array = global.Uint8Array || function () {
};function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);}function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;}/*</replacement>*/var destroyImpl = require('./internal/streams/destroy');util.inherits(Writable, Stream);function nop() {
}function WritableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');options = options || {
};// Duplex streams are both readable and writable, but share// the same options object.// However, some cases require setting options to different// values for the readable and the writable sides of the duplex stream.// These options can be provided separately as readableXXX and writableXXX.var isDuplex = stream instanceof Duplex;// object stream flag to indicate whether or not this stream// contains buffers or objects.this.objectMode = !!options.objectMode;if (isDuplex) 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 writableHwm = options.writableHighWaterMark;var defaultHwm = this.objectMode ? 16 : 16 * 1024;if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;// cast to ints.this.highWaterMark = Math.floor(this.highWaterMark);// if _final has been calledthis.finalCalled = false;// drain event flag.this.needDrain = false;// at the start of calling end()this.ending = false;// when end() has been called, and returnedthis.ended = false;// when 'finish' is emittedthis.finished = false;// has it been destroyedthis.destroyed = 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() callthis.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 emittedthis.pendingcb = 0;// emit prefinish if the only thing we're waiting for is _write cbs// This is relevant for synchronous Transform streamsthis.prefinished = false;// True if the error was already emitted and should not be thrown againthis.errorEmitted = false;// count buffered requeststhis.bufferedRequestCount = 0;// allocate the first CorkedRequest, there is always// one allocated and free to use, and we maintain at most twothis.corkedRequestsFree = new CorkedRequest(this);}WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;var out = [];while (current) {
out.push(current);current = current.next;}return out;};(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')});} catch (_) {
}})();// Test _writableState for inheritance to account for Duplex streams,// whose prototype chain only points to Readable.var realHasInstance;if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable, Symbol.hasInstance, {
value: function (object) {
if (realHasInstance.call(this, object)) return true;if (this !== Writable) return false;return object && object._writableState instanceof WritableState;}});} else {
realHasInstance = function (object) {
return object instanceof this;};}function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');// Writable ctor is applied to Duplexes, too.// `realHasInstance` is necessary because using plain `instanceof`// would return false, as no `_writableState` property is attached.// Trying to use the custom `instanceof` for Writable here will also break the// Node.js LazyTransform implementation, which has a non-trivial getter for// `_writableState` that would lead to infinite recursion.if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);}this._writableState = new WritableState(options, this);// legacy.this.writable = true;if (options) {
if (typeof options.write === 'function') this._write = options.write;if (typeof options.writev === 'function') this._writev = options.writev;if (typeof options.destroy === 'function') this._destroy = options.destroy;if (typeof options.final === 'function') this._final = options.final;}Stream.call(this);}// Otherwise people can pipe Writable streams, which is just wrong.Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));};function writeAfterEnd(stream, cb) {
var er = new Error('write after end');// TODO: defer error events consistently everywhere, not just the cbstream.emit('error', er);pna.nextTick(cb, er);}// Checks that a user-supplied chunk is valid, especially for the particular// mode the stream is in. Currently this means that `null` is never accepted// and undefined/non-string values are only allowed in object mode.function validChunk(stream, state, chunk, cb) {
var valid = true;var er = false;if (chunk === null) {
er = new TypeError('May not write null values to stream');} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');}if (er) {
stream.emit('error', er);pna.nextTick(cb, er);valid = false;}return valid;}Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;var ret = false;var isBuf = !state.objectMode && _isUint8Array(chunk);if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);}if (typeof encoding === 'function') {
cb = encoding;encoding = null;}if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;if (typeof cb !== 'function') cb = nop;if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;ret = writeOrBuffer(this, state, isBuf, 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.bufferedRequest) clearBuffer(this, state);}};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;return this;};function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);}return chunk;}Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable// because otherwise some prototype manipulation in// userland will failenumerable: false,get: function () {
return this._writableState.highWaterMark;}});// 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, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);if (chunk !== newChunk) {
isBuf = true;encoding = 'buffer';chunk = newChunk;}}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) {
var last = state.lastBufferedRequest;state.lastBufferedRequest = {
chunk: chunk,encoding: encoding,isBuf: isBuf,callback: cb,next: null};if (last) {
last.next = state.lastBufferedRequest;} else {
state.bufferedRequest = state.lastBufferedRequest;}state.bufferedRequestCount += 1;} else {
doWrite(stream, state, false, len, chunk, encoding, cb);}return ret;}function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;state.writecb = cb;state.writing = true;state.sync = true;if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);state.sync = false;}function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;if (sync) {
// defer the callback if we are being called synchronously// to avoid piling up things on the stackpna.nextTick(cb, er);// this can emit finish, and it will always happen// after errorpna.nextTick(finishMaybe, stream, state);stream._writableState.errorEmitted = true;stream.emit('error', er);} else {
// the caller expect this to happen before if// it is asynccb(er);stream._writableState.errorEmitted = true;stream.emit('error', er);// this can emit finish, but finish must// always follow errorfinishMaybe(stream, state);}}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 yetvar finished = needFinish(state);if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);}if (sync) {
/*<replacement>*/asyncWrite(afterWrite, stream, state, finished, cb);/*</replacement>*/} 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 itfunction clearBuffer(stream, state) {
state.bufferProcessing = true;var entry = state.bufferedRequest;if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()var l = state.bufferedRequestCount;var buffer = new Array(l);var holder = state.corkedRequestsFree;holder.entry = entry;var count = 0;var allBuffers = true;while (entry) {
buffer[count] = entry;if (!entry.isBuf) allBuffers = false;entry = entry.next;count += 1;}buffer.allBuffers = allBuffers;doWrite(stream, state, true, state.length, buffer, '', holder.finish);// doWrite is almost always async, defer these to save a bit of time// as the hot path ends with doWritestate.pendingcb++;state.lastBufferedRequest = null;if (holder.next) {
state.corkedRequestsFree = holder.next;holder.next = null;} else {
state.corkedRequestsFree = new CorkedRequest(state);}state.bufferedRequestCount = 0;} else {
// Slow case, write chunks one-by-onewhile (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;state.bufferedRequestCount--;// 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;}}if (entry === null) state.lastBufferedRequest = null;}state.bufferedRequest = entry;state.bufferProcessing = false;}Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is 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);// .end() fully uncorksif (state.corked) {
state.corked = 1;this.uncork();}// 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 callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;if (err) {
stream.emit('error', err);}state.prefinished = true;stream.emit('prefinish');finishMaybe(stream, state);});}function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function') {
state.pendingcb++;state.finalCalled = true;pna.nextTick(callFinal, stream, state);} else {
state.prefinished = true;stream.emit('prefinish');}}}function finishMaybe(stream, state) {
var need = needFinish(state);if (need) {
prefinish(stream, state);if (state.pendingcb === 0) {
state.finished = true;stream.emit('finish');}}return need;}function endWritable(stream, state, cb) {
state.ending = true;finishMaybe(stream, state);if (cb) {
if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);}state.ended = true;stream.writable = false;}function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;corkReq.entry = null;while (entry) {
var cb = entry.callback;state.pendingcb--;cb(err);entry = entry.next;}if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = corkReq;} else {
state.corkedRequestsFree = corkReq;}}Object.defineProperty(Writable.prototype, 'destroyed', {
get: function () {
if (this._writableState === undefined) {
return false;}return this._writableState.destroyed;},set: function (value) {
// we ignore the value if the stream// has not been initialized yetif (!this._writableState) {
return;}// backward compatibility, the user is explicitly// managing destroyedthis._writableState.destroyed = value;}});Writable.prototype.destroy = destroyImpl.destroy;Writable.prototype._undestroy = destroyImpl.undestroy;Writable.prototype._destroy = function (err, cb) {
this.end();cb(err);};}).call(this, require('_process'), typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {
}, require("timers").setImmediate)}, {
"./_stream_duplex": 98,"./internal/streams/destroy": 104,"./internal/streams/stream": 105,"_process": 92,"core-util-is": 14,"inherits": 80,"process-nextick-args": 91,"safe-buffer": 110,"timers": 112,"util-deprecate": 115}],103: [function (require, module, exports) {
'use strict';function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");}}var Buffer = require('safe-buffer').Buffer;var util = require('util');function copyBuffer(src, target, offset) {
src.copy(target, offset);}module.exports = function () {
function BufferList() {
_classCallCheck(this, BufferList);this.head = null;this.tail = null;this.length = 0;}BufferList.prototype.push = function push(v) {
var entry = {
data: v,next: null};if (this.length > 0) this.tail.next = entry;else this.head = entry;this.tail = entry;++this.length;};BufferList.prototype.unshift = function unshift(v) {
var entry = {
data: v,next: this.head};if (this.length === 0) this.tail = entry;this.head = entry;++this.length;};BufferList.prototype.shift = function shift() {
if (this.length === 0) return;var ret = this.head.data;if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;--this.length;return ret;};BufferList.prototype.clear = function clear() {
this.head = this.tail = null;this.length = 0;};BufferList.prototype.join = function join(s) {
if (this.length === 0) return '';var p = this.head;var ret = '' + p.data;while (p = p.next) {
ret += s + p.data;}return ret;};BufferList.prototype.concat = function concat(n) {
if (this.length === 0) return Buffer.alloc(0);if (this.length === 1) return this.head.data;var ret = Buffer.allocUnsafe(n >>> 0);var p = this.head;var i = 0;while (p) {
copyBuffer(p.data, ret, i);i += p.data.length;p = p.next;}return ret;};return BufferList;}();if (util && util.inspect && util.inspect.custom) {
module.exports.prototype[util.inspect.custom] = function () {
var obj = util.inspect({
length: this.length});return this.constructor.name + ' ' + obj;};}}, {
"safe-buffer": 110,"util": 11}],104: [function (require, module, exports) {
'use strict';/*<replacement>*/var pna = require('process-nextick-args');/*</replacement>*/// undocumented cb() API, needed for core, not for public APIfunction destroy(err, cb) {
var _this = this;var readableDestroyed = this._readableState && this._readableState.destroyed;var writableDestroyed = this._writableState && this._writableState.destroyed;if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);} else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
pna.nextTick(emitErrorNT, this, err);}return this;}// we set destroyed to true before firing error callbacks in order// to make it re-entrance safe in case destroy() is called within callbacksif (this._readableState) {
this._readableState.destroyed = true;}// if this is a duplex stream mark the writable part as destroyed as wellif (this._writableState) {
this._writableState.destroyed = true;}this._destroy(err || null, function (err) {
if (!cb && err) {
pna.nextTick(emitErrorNT, _this, err);if (_this._writableState) {
_this._writableState.errorEmitted = true;}} else if (cb) {
cb(err);}});return this;}function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;this._readableState.reading = false;this._readableState.ended = false;this._readableState.endEmitted = false;}if (this._writableState) {
this._writableState.destroyed = false;this._writableState.ended = false;this._writableState.ending = false;this._writableState.finished = false;this._writableState.errorEmitted = false;}}function emitErrorNT(self, err) {
self.emit('error', err);}module.exports = {
destroy: destroy,undestroy: undestroy};}, {
"process-nextick-args": 91}],105: [function (require, module, exports) {
module.exports = require('events').EventEmitter;}, {
"events": 13}],106: [function (require, module, exports) {
var toString = {
}.toString;module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';};}, {
}],107: [function (require, module, exports) {
// Copyright Joyent, Inc. and other Node contributors.//// Permission is hereby granted, free of charge, to any person obtaining a// copy of this software and associated documentation files (the// "Software"), to deal in the Software without restriction, including// without limitation the rights to use, copy, modify, merge, publish,// distribute, sublicense, and/or sell copies of the Software, and to permit// persons to whom the Software is furnished to do so, subject to the// following conditions://// The above copyright notice and this permission notice shall be included// in all copies or substantial portions of the Software.//// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE// USE OR OTHER DEALINGS IN THE SOFTWARE.'use strict';/*<replacement>*/var Buffer = require('safe-buffer').Buffer;/*</replacement>*/var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + 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 _normalizeEncoding(enc) {
if (!enc) return 'utf8';var retried;while (true) {
switch (enc) {
case 'utf8':case 'utf-8':return 'utf8';case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':return 'utf16le';case 'latin1':case 'binary':return 'latin1';case 'base64':case 'ascii':case 'hex':return enc;default:if (retried) return; // undefinedenc = ('' + enc).toLowerCase();retried = true;}}};// Do not cache `Buffer.isEncoding` when checking encoding names as some// modules monkey-patch it to support additional encodingsfunction normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);return nenc || enc;}// StringDecoder provides an interface for efficiently splitting a series of// buffers into a series of JS strings without breaking apart multi-byte// characters.exports.StringDecoder = StringDecoder;function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);var nb;switch (this.encoding) {
case 'utf16le':this.text = utf16Text;this.end = utf16End;nb = 4;break;case 'utf8':this.fillLast = utf8FillLast;nb = 4;break;case 'base64':this.text = base64Text;this.end = base64End;nb = 3;break;default:this.write = simpleWrite;this.end = simpleEnd;return;}this.lastNeed = 0;this.lastTotal = 0;this.lastChar = Buffer.allocUnsafe(nb);}StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';var r;var i;if (this.lastNeed) {
r = this.fillLast(buf);if (r === undefined) return '';i = this.lastNeed;this.lastNeed = 0;} else {
i = 0;}if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);return r || '';};StringDecoder.prototype.end = utf8End;// Returns only complete characters in a BufferStringDecoder.prototype.text = utf8Text;// Attempts to complete a partial non-UTF-8 character using bytes from a BufferStringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);return this.lastChar.toString(this.encoding, 0, this.lastTotal);}buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);this.lastNeed -= buf.length;};// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a// continuation byte. If an invalid byte is detected, -2 is returned.function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;return byte >> 6 === 0x02 ? -1 : -2;}// Checks at most 3 bytes at the end of a Buffer in order to detect an// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)// needed to complete the UTF-8 character (if applicable) are returned.function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;if (j < i) return 0;var nb = utf8CheckByte(buf[j]);if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;return nb;}if (--j < i || nb === -2) return 0;nb = utf8CheckByte(buf[j]);if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;return nb;}if (--j < i || nb === -2) return 0;nb = utf8CheckByte(buf[j]);if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;}return nb;}return 0;}// Validates as many continuation bytes for a multi-byte UTF-8 character as// needed or are available. If we see a non-continuation byte where we expect// one, we "replace" the validated continuation bytes we've seen so far with// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding// behavior. The continuation byte check is included three times in the case// where all of the continuation bytes for a character exist in the same buffer.// It is also done this way as a slight performance increase instead of using a// loop.function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;return '\ufffd';}if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;return '\ufffd';}if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;return '\ufffd';}}}}// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;var r = utf8CheckExtraBytes(this, buf, p);if (r !== undefined) return r;if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);return this.lastChar.toString(this.encoding, 0, this.lastTotal);}buf.copy(this.lastChar, p, 0, buf.length);this.lastNeed -= buf.length;}// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a// partial character, the character's bytes are buffered until the required// number of bytes are available.function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);if (!this.lastNeed) return buf.toString('utf8', i);this.lastTotal = total;var end = buf.length - (total - this.lastNeed);buf.copy(this.lastChar, 0, end);return buf.toString('utf8', i, end);}// For UTF-8, a replacement character is added when ending on a partial// character.function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';if (this.lastNeed) return r + '\ufffd';return r;}// UTF-16LE typically needs two bytes per character, but even if we have an even// number of bytes available, we need to check if we end on a leading/high// surrogate. In that case, we need to wait for the next two bytes in order to// decode the last character properly.function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);if (r) {
var c = r.charCodeAt(r.length - 1);if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;this.lastTotal = 4;this.lastChar[0] = buf[buf.length - 2];this.lastChar[1] = buf[buf.length - 1];return r.slice(0, -1);}}return r;}this.lastNeed = 1;this.lastTotal = 2;this.lastChar[0] = buf[buf.length - 1];return buf.toString('utf16le', i, buf.length - 1);}// For UTF-16LE we do not explicitly append special replacement characters if we// end on a partial character, we simply let v8 handle that.function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;return r + this.lastChar.toString('utf16le', 0, end);}return r;}function base64Text(buf, i) {
var n = (buf.length - i) % 3;if (n === 0) return buf.toString('base64', i);this.lastNeed = 3 - n;this.lastTotal = 3;if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];} else {
this.lastChar[0] = buf[buf.length - 2];this.lastChar[1] = buf[buf.length - 1];}return buf.toString('base64', i, buf.length - n);}function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);return r;}// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)function simpleWrite(buf) {
return buf.toString(this.encoding);}function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';}}, {
"safe-buffer": 110}],108: [function (require, module, exports) {
exports = module.exports = require('./lib/_stream_readable.js');exports.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": 98,"./lib/_stream_passthrough.js": 99,"./lib/_stream_readable.js": 100,"./lib/_stream_transform.js": 101,"./lib/_stream_writable.js": 102}],109: [function (require, module, exports) {
'use strict'function ReInterval(callback, interval, args) {
var self = this;this._callback = callback;this._args = args;this._interval = setInterval(callback, interval, this._args);this.reschedule = function (interval) {
// if no interval entered, use the interval passed in on creationif (!interval)interval = self._interval;if (self._interval)clearInterval(self._interval);self._interval = setInterval(self._callback, interval, self._args);};this.clear = function () {
if (self._interval) {
clearInterval(self._interval);self._interval = undefined;}};this.destroy = function () {
if (self._interval) {
clearInterval(self._interval);}self._callback = undefined;self._interval = undefined;self._args = undefined;};}function reInterval() {
if (typeof arguments[0] !== 'function')throw new Error('callback needed');if (typeof arguments[1] !== 'number')throw new Error('interval needed');var args;if (arguments.length > 0) {
args = new Array(arguments.length - 2);for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 2];}}return new ReInterval(arguments[0], arguments[1], args);}module.exports = reInterval;}, {
}],110: [function (require, module, exports) {
/* eslint-disable node/no-deprecated-api */var buffer = require('buffer')var Buffer = buffer.Buffer// alternative to using Object.keys for old browsersfunction copyProps(src, dst) {
for (var key in src) {
dst[key] = src[key]}}if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer} else {
// Copy properties from require('buffer')copyProps(buffer, exports)exports.Buffer = SafeBuffer}function SafeBuffer(arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)}// Copy static methods from BuffercopyProps(Buffer, SafeBuffer)SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')}return Buffer(arg, encodingOrOffset, length)}SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')}var buf = Buffer(size)if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)} else {
buf.fill(fill)}} else {
buf.fill(0)}return buf}SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')}return Buffer(size)}SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')}return buffer.SlowBuffer(size)}}, {
"buffer": 12}],111: [function (require, module, exports) {
module.exports = shiftfunction shift(stream) {
var rs = stream._readableStateif (!rs) return nullreturn rs.objectMode ? stream.read() : stream.read(getStateLength(rs))}function getStateLength(state) {
if (state.buffer.length) {
// Since node 6.3.0 state.buffer is a BufferList not an arrayif (state.buffer.head) {
return state.buffer.head.data.length}return state.buffer[0].length}return state.length}}, {
}],112: [function (require, module, exports) {
(function (setImmediate, clearImmediate) {
var nextTick = require('process/browser.js').nextTick;var apply = Function.prototype.apply;var slice = Array.prototype.slice;var immediateIds = {
};var nextImmediateId = 0;// DOM APIs, for completenessexports.setTimeout = function () {
return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);};exports.setInterval = function () {
return new Timeout(apply.call(setInterval, window, arguments), clearInterval);};exports.clearTimeout =exports.clearInterval = function (timeout) {
timeout.close();};function Timeout(id, clearFn) {
this._id = id;this._clearFn = clearFn;}Timeout.prototype.unref = Timeout.prototype.ref = function () {
};Timeout.prototype.close = function () {
this._clearFn.call(window, this._id);};// Does not start the time, just sets up the members needed.exports.enroll = function (item, msecs) {
clearTimeout(item._idleTimeoutId);item._idleTimeout = msecs;};exports.unenroll = function (item) {
clearTimeout(item._idleTimeoutId);item._idleTimeout = -1;};exports._unrefActive = exports.active = function (item) {
clearTimeout(item._idleTimeoutId);var msecs = item._idleTimeout;if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)item._onTimeout();}, msecs);}};// That's not how node.js implements it but the exposed api is the same.exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function (fn) {
var id = nextImmediateId++;var args = arguments.length < 2 ? false : slice.call(arguments, 1);immediateIds[id] = true;nextTick(function onNextTick() {
if (immediateIds[id]) {
// fn.call() is faster so we optimize for the common use-case// @see http://jsperf.com/call-apply-seguif (args) {
fn.apply(null, args);} else {
fn.call(null);}// Prevent ids from leakingexports.clearImmediate(id);}});return id;};exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function (id) {
delete immediateIds[id];};}).call(this, require("timers").setImmediate, require("timers").clearImmediate)}, {
"process/browser.js": 92,"timers": 112}],113: [function (require, module, exports) {
// Copyright Joyent, Inc. and other Node contributors.//// Permission is hereby granted, free of charge, to any person obtaining a// copy of this software and associated documentation files (the// "Software"), to deal in the Software without restriction, including// without limitation the rights to use, copy, modify, merge, publish,// distribute, sublicense, and/or sell copies of the Software, and to permit// persons to whom the Software is furnished to do so, subject to the// following conditions://// The above copyright notice and this permission notice shall be included// in all copies or substantial portions of the Software.//// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE// USE OR OTHER DEALINGS IN THE SOFTWARE.'use strict';var punycode = require('punycode');var util = require('./util');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]*$/,// Special case for a simple path URLsimplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,// 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 && util.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 (!util.isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);}// Copy chrome, IE, opera backslash-handling behavior.// Back slashes before the query string get converted to forward slashes// See: https://code.google.com/p/chromium/issues/detail?id=25916var queryIndex = url.indexOf('?'),splitter =(queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',uSplit = url.split(splitter),slashRegex = /\\/g;uSplit[0] = uSplit[0].replace(slashRegex, '/');url = uSplit.join(splitter);var rest = url;// trim before proceeding.// This is to support parse stuff like " http://foo.com \n"rest = rest.trim();if (!slashesDenoteHost && url.split('#').length === 1) {
// Try fast path regexpvar simplePath = simplePathPattern.exec(rest);if (simplePath) {
this.path = rest;this.href = rest;this.pathname = simplePath[1];if (simplePath[2]) {
this.search = simplePath[2];if (parseQueryString) {
this.query = querystring.parse(this.search.substr(1));} else {
this.query = this.search.substr(1);}} else if (parseQueryString) {
this.search = '';this.query = {
};}return this;}}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 hostEndingCharsvar 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@datSign = 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 charhostEnd = -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 nothingnewpart += 'x';} else {
newpart += part[j];}}// we test again with ASCII char onlyif (!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 punycoded representation of "domain".// It only converts parts of the domain name that// have non-ASCII characters, i.e. it doesn't matter if// you call it with a domain that already is ASCII-only.this.hostname = punycode.toASCII(this.hostname);}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, thoughif (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];if (rest.indexOf(ae) === -1)continue;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 requestedthis.search = '';this.query = {
};}if (rest) this.pathname = rest;if (slashedProtocol[lowerProto] &&this.hostname && !this.pathname) {
this.pathname = '/';}//to support http.requestif (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 stringfunction 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 (util.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 &&util.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 (util.isString(relative)) {
var rel = new Url();rel.parse(relative, false, true);relative = rel;}var result = new Url();var tkeys = Object.keys(this);for (var tk = 0; tk < tkeys.length; tk++) {
var tkey = tkeys[tk];result[tkey] = this[tkey];}// 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 relativevar rkeys = Object.keys(relative);for (var rk = 0; rk < rkeys.length; rk++) {
var rkey = rkeys[rk];if (rkey !== 'protocol')result[rkey] = relative[rkey];}//urlParse appends trailing / to urls like http://www.example.comif (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]) {
var keys = Object.keys(relative);for (var v = 0; v < keys.length; v++) {
var k = keys[v];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.requestif (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 (!util.isNullOrUndefined(relative.search)) {
// just pull out the search.// like href='?foo'.// Put this after the other two cases because it simplifies the booleansif (psychotic) {
result.hostname = result.host = srcPath.shift();//occationaly the auth can get stuck only in host//this especially 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.requestif (!util.isNull(result.pathname) || !util.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.requestif (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 || srcPath.length > 1) &&(last === '.' || last === '..') || last === '');// strip single dots, resolve double dots to parent dir// if the path tries to go above the root, `up` ends up > 0var 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 ..sif (!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 backif (psychotic) {
result.hostname = result.host = isAbsolute ? '' :srcPath.length ? srcPath.shift() : '';//occationaly the auth can get stuck only in host//this especially 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.httpif (!util.isNull(result.pathname) || !util.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;};}, {
"./util": 114,"punycode": 93,"querystring": 96}],114: [function (require, module, exports) {
'use strict';module.exports = {
isString: function (arg) {
return typeof (arg) === 'string';},isObject: function (arg) {
return typeof (arg) === 'object' && arg !== null;},isNull: function (arg) {
return arg === null;},isNullOrUndefined: function (arg) {
return arg == null;}};}, {
}],115: [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) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframestry {
if (!global.localStorage) return false;} catch (_) {
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 : {
})}, {
}],116: [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';}}, {
}],117: [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 optionsvar 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" objectexports._extend(ctx, opts);}// set default optionsif (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#graphicsinspect.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.exeinspect.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 itif (ctx.customInspect &&value &&isFunction(value.inspect) &&// Filter out the util module, it's inspect function is specialvalue.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 propertiesvar 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).aspxif (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 Arrayif (isArray(value)) {
array = true;braces = ['[', ']'];}// Make functions say that they are functionsif (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';base = ' [Function' + n + ']';}// Make RegExps say that they are RegExpsif (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);}// Make dates with properties first say the dateif (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);}// Make error with message first say the errorif (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 symboltypeof 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:34function 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 timestampexports.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 objectif (!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": 116,"_process": 92,"inherits": 80}],118: [function (require, module, exports) {
(function (process, global) {
'use strict'var Transform = require('readable-stream').Transformvar duplexify = require('duplexify')var WS = require('ws')var Buffer = require('safe-buffer').Buffermodule.exports = WebSocketStreamfunction buildProxy(options, socketWrite, socketEnd) {
var proxy = new Transform({
objectMode: options.objectMode})proxy._write = socketWriteproxy._flush = socketEndreturn proxy}function WebSocketStream(target, protocols, options) {
var stream, socketvar isBrowser = process.title === 'browser'var isNative = !!global.WebSocketvar socketWrite = isBrowser ? socketWriteBrowser : socketWriteNodeif (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {
// accept the "options" Object as the 2nd argumentoptions = protocolsprotocols = nullif (typeof options.protocol === 'string' || Array.isArray(options.protocol)) {
protocols = options.protocol;}}if (!options) options = {
}if (options.objectMode === undefined) {
options.objectMode = !(options.binary === true || options.binary === undefined)}var proxy = buildProxy(options, socketWrite, socketEnd)if (!options.objectMode) {
proxy._writev = writev}// browser only: sets the maximum socket buffer size before throttlingvar bufferSize = options.browserBufferSize || 1024 * 512// browser only: how long to wait when throttlingvar bufferTimeout = options.browserBufferTimeout || 1000// use existing WebSocket object that was passed inif (typeof target === 'object') {
socket = target// otherwise make a new one} else {
// special constructor treatment for native websockets in browsers, see// https://github.com/maxogden/websocket-stream/issues/82if (isNative && isBrowser) {
socket = new WS(target, protocols)} else {
socket = new WS(target, protocols, options)}socket.binaryType = 'arraybuffer'}// was already open when passed inif (socket.readyState === socket.OPEN) {
stream = proxy} else {
stream = duplexify.obj()socket.onopen = onopen}stream.socket = socketsocket.onclose = onclosesocket.onerror = onerrorsocket.onmessage = onmessageproxy.on('close', destroy)var coerceToBuffer = !options.objectModefunction socketWriteNode(chunk, enc, next) {
// avoid errors, this never happens unless// destroy() is calledif (socket.readyState !== socket.OPEN) {
next()return}if (coerceToBuffer && typeof chunk === 'string') {
chunk = Buffer.from(chunk, 'utf8')}socket.send(chunk, next)}function socketWriteBrowser(chunk, enc, next) {
if (socket.bufferedAmount > bufferSize) {
setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)return}if (coerceToBuffer && typeof chunk === 'string') {
chunk = Buffer.from(chunk, 'utf8')}try {
socket.send(chunk)} catch (err) {
return next(err)}next()}function socketEnd(done) {
socket.close()done()}function onopen() {
stream.setReadable(proxy)stream.setWritable(proxy)stream.emit('connect')}function onclose() {
stream.end()stream.destroy()}function onerror(err) {
stream.destroy(err)}function onmessage(event) {
var data = event.dataif (data instanceof ArrayBuffer) data = Buffer.from(data)else data = Buffer.from(data, 'utf8')proxy.push(data)}function destroy() {
socket.close()}// this is to be enabled only if objectMode is falsefunction writev(chunks, cb) {
var buffers = new Array(chunks.length)for (var i = 0; i < chunks.length; i++) {
if (typeof chunks[i].chunk === 'string') {
buffers[i] = Buffer.from(chunks[i], 'utf8')} else {
buffers[i] = chunks[i].chunk}}this._write(Buffer.concat(buffers), 'binary', cb)}return stream}}).call(this, require('_process'), typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {
})}, {
"_process": 92,"duplexify": 17,"readable-stream": 108,"safe-buffer": 110,"ws": 119}],119: [function (require, module, exports) {
var ws = nullif (typeof WebSocket !== 'undefined') {
ws = WebSocket} else if (typeof MozWebSocket !== 'undefined') {
ws = MozWebSocket} else if (typeof window !== 'undefined') {
ws = window.WebSocket || window.MozWebSocket}module.exports = ws}, {
}],120: [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 = wrappyfunction 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 wrapperfunction 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}}}, {
}],121: [function (require, module, exports) {
module.exports = extendvar hasOwnProperty = Object.prototype.hasOwnProperty;function extend() {
var target = {
}for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key]}}}return target}}, {
}]}, {
}, [9])(9)
});