From e28e668e630ff62db1ab47c276e1fbaf88b27e29 Mon Sep 17 00:00:00 2001 From: Espen Hovlandsdal Date: Wed, 22 Aug 2018 15:58:52 +0200 Subject: [PATCH] Fix unicode chunking issue, ignore BOM mark --- .travis.yml | 2 +- example/eventsource-polyfill.js | 6407 +++++++++++++++++-------------- lib/eventsource.js | 37 +- package.json | 1 + test/eventsource_test.js | 45 +- 5 files changed, 3553 insertions(+), 2939 deletions(-) diff --git a/.travis.yml b/.travis.yml index 38f47c1..adfbad2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,5 +4,5 @@ node_js: - '0.12' - '4' - '6' - - '7' - '8' + - '10' diff --git a/example/eventsource-polyfill.js b/example/eventsource-polyfill.js index 83ffebf..865f4ee 100644 --- a/example/eventsource-polyfill.js +++ b/example/eventsource-polyfill.js @@ -282,35 +282,6 @@ process.umask = function() { return 0; }; /***/ }), /* 2 */ -/***/ (function(module, exports) { - -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - - -/***/ }), -/* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -324,9 +295,9 @@ if (typeof Object.create === 'function') { -var base64 = __webpack_require__(35) -var ieee754 = __webpack_require__(36) -var isArray = __webpack_require__(12) +var base64 = __webpack_require__(23) +var ieee754 = __webpack_require__(24) +var isArray = __webpack_require__(25) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer @@ -2107,7 +2078,7 @@ function isnan (val) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) /***/ }), -/* 4 */ +/* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -2141,7 +2112,7 @@ function isnan (val) { /**/ -var processNextTick = __webpack_require__(6); +var pna = __webpack_require__(6); /**/ /**/ @@ -2156,8 +2127,8 @@ var objectKeys = Object.keys || function (obj) { module.exports = Duplex; /**/ -var util = __webpack_require__(5); -util.inherits = __webpack_require__(2); +var util = __webpack_require__(4); +util.inherits = __webpack_require__(5); /**/ var Readable = __webpack_require__(15); @@ -2165,10 +2136,13 @@ var Writable = __webpack_require__(18); util.inherits(Duplex, Readable); -var keys = objectKeys(Writable.prototype); -for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } } function Duplex(options) { @@ -2187,6 +2161,16 @@ function Duplex(options) { 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 fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, @@ -2195,7 +2179,7 @@ function onend() { // no more data can be written. // But allow more writes to happen in this tick. - processNextTick(onEndNT, this); + pna.nextTick(onEndNT, this); } function onEndNT(self) { @@ -2227,17 +2211,11 @@ Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); - processNextTick(cb, err); + pna.nextTick(cb, err); }; -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - /***/ }), -/* 5 */ +/* 4 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors. @@ -2348,7 +2326,36 @@ function objectToString(o) { return Object.prototype.toString.call(o); } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3).Buffer)) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + /***/ }), /* 6 */ @@ -2360,9 +2367,9 @@ function objectToString(o) { if (!process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = nextTick; + module.exports = { nextTick: nextTick }; } else { - module.exports = process.nextTick; + module.exports = process } function nextTick(fn, arg1, arg2, arg3) { @@ -2399,12 +2406,14 @@ function nextTick(fn, arg1, arg2, arg3) { } } + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) /***/ }), /* 7 */ -/***/ (function(module, exports) { +/***/ (function(module, exports, __webpack_require__) { +"use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -2426,597 +2435,723 @@ function nextTick(fn, arg1, arg2, arg3) { // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; +var punycode = __webpack_require__(30); +var util = __webpack_require__(32); -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; +exports.Url = Url; -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} - if (!this._events) - this._events = {}; +// Reference: RFC 3986, RFC 1808, RFC 2396 - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - } - } +// 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]*$/, - handler = this._events[type]; + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - if (isUndefined(handler)) - return false; + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - return true; -}; + // 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 = __webpack_require__(33); -EventEmitter.prototype.addListener = function(type, listener) { - var m; +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} - if (!this._events) - this._events = {}; +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); + // 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=25916 + var 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); - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; + var rest = url; - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var 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; } } - return this; -}; + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } -EventEmitter.prototype.on = EventEmitter.prototype.addListener; + // 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; + } + } -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { - var fired = false; + // 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 - function g() { - this.removeListener(type, g); + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. - if (!fired) { - fired = true; - listener.apply(this, arguments); + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; } - } - g.listener = listener; - this.on(type, g); + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } - return this; -}; + // 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); + } -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); - if (!this._events || !this._events[type]) - return this; + // pull out port. + this.parseHost(); - list = this._events[type]; - length = list.length; - position = -1; + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); + // 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] === ']'; - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } } } - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; } else { - list.splice(position, 1); + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); } - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; + 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); + } - if (!this._events) - return this; + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } } - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); + // 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); } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; } - listeners = this._events[type]; - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; } - return 0; -}; -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; }; -function isFunction(arg) { - return typeof arg === 'function'; +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); } -function isNumber(arg) { - return typeof arg === 'number'; -} +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; -function isUndefined(arg) { - return arg === void 0; -} + 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); + } -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { + var search = this.search || (query && ('?' + query)) || ''; -/* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(3) -var Buffer = buffer.Buffer + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] + // 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 (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) -} + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} + return protocol + host + pathname + search + hash; +}; -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 +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); } -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) +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; + } -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { + 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]; + } -"use strict"; + // 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; + } -var required = __webpack_require__(24) - , lolcation = __webpack_require__(25) - , qs = __webpack_require__(26) - , relativere = /^\/(?!\/)/; + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } -/** - * These are the parse instructions for the URL parsers, it informs the parser - * about: - * - * 0. The char it Needs to parse, if it's a string it should be done using - * indexOf, RegExp using exec and NaN means set as current value. - * 1. The property we should set when parsing this value. - * 2. Indication if it's backwards or forward parsing, when set as number it's - * the value of extra chars that should be split off. - * 3. Inherit from location if non existing in the parser. - * 4. `toLowerCase` the resulting value. - */ -var instructions = [ - ['#', 'hash'], // Extract from the back. - ['?', 'query'], // Extract from the back. - ['//', 'protocol', 2, 1, 1], // Extract from the front. - ['/', 'pathname'], // Extract from the back. - ['@', 'auth', 1], // Extract from the front. - [NaN, 'host', undefined, 1, 1], // Set left over value. - [/\:(\d+)$/, 'port'], // RegExp the back. - [NaN, 'hostname', undefined, 1, 1] // Set left over. -]; + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } -/** - * The actual URL instance. Instead of returning an object we've opted-in to - * create an actual constructor as it's much more memory efficient and - * faster and it pleases my CDO. - * - * @constructor - * @param {String} address URL we want to parse. - * @param {Boolean|function} parser Parser for the query string. - * @param {Object} location Location defaults for relative paths. - * @api public - */ -function URL(address, location, parser) { - if (!(this instanceof URL)) { - return new URL(address, location, parser); + result.href = result.format(); + return result; } - var relative = relativere.test(address) - , parse, instruction, index, key - , type = typeof location - , url = this - , i = 0; - - // - // The following if statements allows this module two have compatibility with - // 2 different API: - // - // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments - // where the boolean indicates that the query string should also be parsed. - // - // 2. The `URL` interface of the browser which accepts a URL, object as - // arguments. The supplied object will be used as default values / fall-back - // for relative paths. - // - if ('object' !== type && 'string' !== type) { - parser = location; - location = null; - } - - if (parser && 'function' !== typeof parser) { - parser = qs.parse; - } - - location = lolcation(location); - - for (; i < instructions.length; i++) { - instruction = instructions[i]; - parse = instruction[0]; - key = instruction[1]; - - if (parse !== parse) { - url[key] = address; - } else if ('string' === typeof parse) { - if (~(index = address.indexOf(parse))) { - if ('number' === typeof instruction[2]) { - url[key] = address.slice(0, index); - address = address.slice(index + instruction[2]); - } else { - url[key] = address.slice(index); - address = address.slice(0, index); - } + 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]; } - } else if (index = parse.exec(address)) { - url[key] = index[1]; - address = address.slice(0, address.length - index[0].length); + result.href = result.format(); + return result; } - url[key] = url[key] || (instruction[3] || ('port' === key && relative) ? location[key] || '' : ''); - - // - // Hostname, host and protocol should be lowercased so they can be used to - // create a proper `origin`. - // - if (instruction[4]) { - url[key] = url[key].toLowerCase(); + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; } - // - // Also parse the supplied query string in to an object. If we're supplied - // with a custom parser as function use that instead of the default build-in - // parser. - // - if (parser) url.query = parser(url.query); + 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]; - // - // We should not add port numbers if they are already the default port number - // for a given protocol. As the host also contains the port number we're going - // override it with the hostname which contains no port number. - // - if (!required(url.port, url.protocol)) { - url.host = url.hostname; - url.port = ''; + // 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] === ''); } - // - // Parse down the `auth` for the username and password. - // - url.username = url.password = ''; - if (url.auth) { - instruction = url.auth.split(':'); - url.username = instruction[0] || ''; - url.password = instruction[1] || ''; + 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 booleans + if (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.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; } - // - // The href is just the compiled result. - // - url.href = url.toString(); -} + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } -/** - * This is convenience method for changing properties in the URL instance to - * insure that they all propagate correctly. - * - * @param {String} prop Property we need to adjust. - * @param {Mixed} value The newly assigned value. - * @returns {URL} - * @api public - */ -URL.prototype.set = function set(part, value, fn) { - var url = this; + // 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 === ''); - if ('query' === part) { - if ('string' === typeof value && value.length) { - value = (fn || qs.parse)(value); + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; } + } - url[part] = value; - } else if ('port' === part) { - url[part] = value; - - if (!required(value, url.protocol)) { - url.host = url.hostname; - url[part] = ''; - } else if (value) { - url.host = url.hostname +':'+ value; + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); } - } else if ('hostname' === part) { - url[part] = value; + } - if (url.port) value += ':'+ url.port; - url.host = value; - } else if ('host' === part) { - url[part] = value; + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } - if (/\:\d+/.test(value)) { - value = value.split(':'); - url.hostname = value[0]; - url.port = value[1]; - } - } else { - url[part] = value; + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); } - url.href = url.toString(); - return url; -}; + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); -/** - * Transform the properties back in to a valid and full URL string. - * - * @param {Function} stringify Optional query stringify function. - * @returns {String} - * @api public - */ -URL.prototype.toString = function toString(stringify) { - if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify; - - var query - , url = this - , result = url.protocol +'//'; - - if (url.username) { - result += url.username; - if (url.password) result += ':'+ url.password; - result += '@'; + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this 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 += url.hostname; - if (url.port) result += ':'+ url.port; - - result += url.pathname; + mustEndAbs = mustEndAbs || (result.host && srcPath.length); - query = 'object' === typeof url.query ? stringify(url.query) : url.query; - if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } - if (url.hash) result += url.hash; + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + //to support request.http + if (!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; }; -// -// Expose the URL parser and some additional properties that might be useful for -// others. -// -URL.qs = qs; -URL.location = lolcation; -module.exports = URL; +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; +}; /***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { +/* 8 */ +/***/ (function(module, exports) { -"use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -3038,740 +3173,379 @@ module.exports = URL; // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; -var punycode = __webpack_require__(27); -var util = __webpack_require__(29); +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; -exports.Url = Url; +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; -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; -} +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; -// Reference: RFC 3986, RFC 1808, RFC 2396 + if (!this._events) + this._events = {}; -// 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]*$/, + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } - // Special case for a simple path URL - simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + handler = this._events[type]; - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + if (isUndefined(handler)) + return false; - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } - // 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 = __webpack_require__(30); + return true; +}; -function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && util.isObject(url) && url instanceof Url) return url; +EventEmitter.prototype.addListener = function(type, listener) { + var m; - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; -} + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!util.isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } + if (!this._events) + this._events = {}; - // 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=25916 - var 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); + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); - var rest = url; + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } - if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - var 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 = {}; + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); } - return this; } } - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); - } + return this; +}; - // 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; - } - } +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c + var fired = false; - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. + function g() { + this.removeListener(type, g); - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; + if (!fired) { + fired = true; + listener.apply(this, arguments); } + } - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } + g.listener = listener; + this.on(type, g); - // 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); - } + return this; +}; - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - // pull out port. - this.parseHost(); + if (!this._events || !this._events[type]) + return this; - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; + list = this._events[type]; + length = list.length; + position = -1; - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) continue; - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; } } - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); + list.splice(position, 1); } - 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); - } + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; + return this; +}; - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; } - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { + listeners = this._events[type]; - // 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); - } + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); } + delete this._events[type]; + return this; +}; - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - var qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; - } - if (rest) this.pathname = rest; - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; - } +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; } + return 0; +}; - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); }; -// format a parsed object into a url string -function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (util.isString(obj)) obj = urlParse(obj); - if (!(obj instanceof Url)) return Url.prototype.format.call(obj); - return obj.format(); +function isFunction(arg) { + return typeof arg === 'function'; } -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } +function isNumber(arg) { + return typeof arg === 'number'; +} - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} - if (this.host) { - host = auth + this.host; - } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; - } - } +function isUndefined(arg) { + return arg === void 0; +} - if (this.query && - util.isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); - } - var search = this.search || (query && ('?' + query)) || ''; +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(2) +var Buffer = buffer.Buffer - // 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 = ''; +// alternative to using Object.keys for old browsers +function 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 +} - 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'); +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} - return protocol + host + pathname + search + hash; -}; +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) -function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) } -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); +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 } -Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return Buffer(size) +} - 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]; +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return buffer.SlowBuffer(size) +} - // 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; - } +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - var rkeys = Object.keys(relative); - for (var rk = 0; rk < rkeys.length; rk++) { - var rkey = rkeys[rk]; - if (rkey !== 'protocol') - result[rkey] = relative[rkey]; - } +/* WEBPACK VAR INJECTION */(function(global) {var ClientRequest = __webpack_require__(37) +var response = __webpack_require__(13) +var extend = __webpack_require__(48) +var statusCodes = __webpack_require__(49) +var url = __webpack_require__(7) - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } +var http = exports - result.href = result.format(); - return result; - } +http.request = function (opts, cb) { + if (typeof opts === 'string') + opts = url.parse(opts) + else + opts = extend(opts) - 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.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - } - - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); - } - - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!util.isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this 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.request - if (!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.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; - } - - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host || 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 > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } - } - - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } - - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } - - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this 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.http - if (!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; -}; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {var ClientRequest = __webpack_require__(34) -var extend = __webpack_require__(45) -var statusCodes = __webpack_require__(46) -var url = __webpack_require__(10) - -var http = exports - -http.request = function (opts, cb) { - if (typeof opts === 'string') - opts = url.parse(opts) - else - opts = extend(opts) - - // Normally, the page is loaded from http or https, so not specifying a protocol - // will result in a (valid) protocol-relative url. However, this won't work if - // the protocol is something else, like 'file:' - var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' var protocol = opts.protocol || defaultProtocol var host = opts.hostname || opts.host @@ -3801,9 +3575,14 @@ http.get = function get (opts, cb) { return req } +http.ClientRequest = ClientRequest +http.IncomingMessage = response.IncomingMessage + http.Agent = function () {} http.Agent.defaultMaxSockets = 4 +http.globalAgent = new http.Agent() + http.STATUS_CODES = statusCodes http.METHODS = [ @@ -3837,22 +3616,15 @@ http.METHODS = [ /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) /***/ }), -/* 12 */ -/***/ (function(module, exports) { - -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - - -/***/ }), -/* 13 */ +/* 11 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) +exports.writableStream = isFunction(global.WritableStream) + +exports.abortController = isFunction(global.AbortController) + exports.blobConstructor = false try { new Blob([new ArrayBuffer(1)]) @@ -3924,16 +3696,276 @@ xhr = null // Help gc /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) /***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { +/* 12 */ +/***/ (function(module, exports) { -exports = module.exports = __webpack_require__(15); -exports.Stream = exports; -exports.Readable = exports; -exports.Writable = __webpack_require__(18); -exports.Duplex = __webpack_require__(4); +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process, Buffer, global) {var capability = __webpack_require__(11) +var inherits = __webpack_require__(12) +var stream = __webpack_require__(14) + +var rStates = exports.readyStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 +} + +var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) { + var self = this + stream.Readable.call(self) + + self._mode = mode + self.headers = {} + self.rawHeaders = [] + self.trailers = {} + self.rawTrailers = [] + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function () { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + process.nextTick(function () { + self.emit('close') + }) + }) + + if (mode === 'fetch') { + self._fetchResponse = response + + self.url = response.url + self.statusCode = response.status + self.statusMessage = response.statusText + + response.headers.forEach(function (header, key){ + self.headers[key.toLowerCase()] = header + self.rawHeaders.push(key, header) + }) + + if (capability.writableStream) { + var writable = new WritableStream({ + write: function (chunk) { + return new Promise(function (resolve, reject) { + if (self._destroyed) { + reject() + } else if(self.push(new Buffer(chunk))) { + resolve() + } else { + self._resumeFetch = resolve + } + }) + }, + close: function () { + global.clearTimeout(fetchTimer) + if (!self._destroyed) + self.push(null) + }, + abort: function (err) { + if (!self._destroyed) + self.emit('error', err) + } + }) + + try { + response.body.pipeTo(writable).catch(function (err) { + global.clearTimeout(fetchTimer) + if (!self._destroyed) + self.emit('error', err) + }) + return + } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this + } + // fallback for when writableStream or pipeTo aren't available + var reader = response.body.getReader() + function read () { + reader.read().then(function (result) { + if (self._destroyed) + return + if (result.done) { + global.clearTimeout(fetchTimer) + self.push(null) + return + } + self.push(new Buffer(result.value)) + read() + }).catch(function (err) { + global.clearTimeout(fetchTimer) + if (!self._destroyed) + self.emit('error', err) + }) + } + read() + } else { + self._xhr = xhr + self._pos = 0 + + self.url = xhr.responseURL + self.statusCode = xhr.status + self.statusMessage = xhr.statusText + var headers = xhr.getAllResponseHeaders().split(/\r?\n/) + headers.forEach(function (header) { + var matches = header.match(/^([^:]+):\s*(.*)/) + if (matches) { + var key = matches[1].toLowerCase() + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = [] + } + self.headers[key].push(matches[2]) + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2] + } else { + self.headers[key] = matches[2] + } + self.rawHeaders.push(matches[1], matches[2]) + } + }) + + self._charset = 'x-user-defined' + if (!capability.overrideMimeType) { + var mimeType = self.rawHeaders['mime-type'] + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase() + } + } + if (!self._charset) + self._charset = 'utf-8' // best guess + } + } +} + +inherits(IncomingMessage, stream.Readable) + +IncomingMessage.prototype._read = function () { + var self = this + + var resolve = self._resumeFetch + if (resolve) { + self._resumeFetch = null + resolve() + } +} + +IncomingMessage.prototype._onXHRProgress = function () { + var self = this + + var xhr = self._xhr + + var response = null + switch (self._mode) { + case 'text:vbarray': // For IE9 + if (xhr.readyState !== rStates.DONE) + break + try { + // This fails in IE8 + response = new global.VBArray(xhr.responseBody).toArray() + } catch (e) {} + if (response !== null) { + self.push(new Buffer(response)) + break + } + // Falls through in IE8 + case 'text': + try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 + response = xhr.responseText + } catch (e) { + self._mode = 'text:vbarray' + break + } + if (response.length > self._pos) { + var newData = response.substr(self._pos) + if (self._charset === 'x-user-defined') { + var buffer = new Buffer(newData.length) + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff + + self.push(buffer) + } else { + self.push(newData, self._charset) + } + self._pos = response.length + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response + self.push(new Buffer(new Uint8Array(response))) + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(new Buffer(new Uint8Array(response))) + break + case 'ms-stream': + response = xhr.response + if (xhr.readyState !== rStates.LOADING) + break + var reader = new global.MSStreamReader() + reader.onprogress = function () { + if (reader.result.byteLength > self._pos) { + self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) + self._pos = reader.result.byteLength + } + } + reader.onload = function () { + self.push(null) + } + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response) + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + self.push(null) + } +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(2).Buffer, __webpack_require__(0))) + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +exports = module.exports = __webpack_require__(15); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = __webpack_require__(18); +exports.Duplex = __webpack_require__(3); exports.Transform = __webpack_require__(20); -exports.PassThrough = __webpack_require__(43); +exports.PassThrough = __webpack_require__(46); /***/ }), @@ -3966,13 +3998,13 @@ exports.PassThrough = __webpack_require__(43); /**/ -var processNextTick = __webpack_require__(6); +var pna = __webpack_require__(6); /**/ module.exports = Readable; /**/ -var isArray = __webpack_require__(12); +var isArray = __webpack_require__(38); /**/ /**/ @@ -3982,7 +4014,7 @@ var Duplex; Readable.ReadableState = ReadableState; /**/ -var EE = __webpack_require__(7).EventEmitter; +var EE = __webpack_require__(8).EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; @@ -3993,10 +4025,9 @@ var EElistenerCount = function (emitter, type) { var Stream = __webpack_require__(16); /**/ -// TODO(bmeurer): Change this back to const once hole checks are -// properly optimized away early in Ignition+TurboFan. /**/ -var Buffer = __webpack_require__(8).Buffer; + +var Buffer = __webpack_require__(9).Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); @@ -4004,15 +4035,16 @@ function _uint8ArrayToBuffer(chunk) { function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } + /**/ /**/ -var util = __webpack_require__(5); -util.inherits = __webpack_require__(2); +var util = __webpack_require__(4); +util.inherits = __webpack_require__(5); /**/ /**/ -var debugUtil = __webpack_require__(38); +var debugUtil = __webpack_require__(39); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); @@ -4021,7 +4053,7 @@ if (debugUtil && debugUtil.debuglog) { } /**/ -var BufferList = __webpack_require__(39); +var BufferList = __webpack_require__(40); var destroyImpl = __webpack_require__(17); var StringDecoder; @@ -4032,33 +4064,40 @@ 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); - } else { - // 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]]; - } + 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 || __webpack_require__(4); + Duplex = Duplex || __webpack_require__(3); 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 away this.objectMode = !!options.objectMode; - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + 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; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + 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); @@ -4112,7 +4151,7 @@ function ReadableState(options, stream) { } function Readable(options) { - Duplex = Duplex || __webpack_require__(4); + Duplex = Duplex || __webpack_require__(3); if (!(this instanceof Readable)) return new Readable(options); @@ -4431,7 +4470,7 @@ function emitReadable(stream) { if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } } @@ -4450,7 +4489,7 @@ function emitReadable_(stream) { function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); + pna.nextTick(maybeReadMore_, stream, state); } } @@ -4495,7 +4534,7 @@ Readable.prototype.pipe = function (dest, pipeOpts) { var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { @@ -4685,7 +4724,7 @@ Readable.prototype.on = function (ev, fn) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { - processNextTick(nReadingNextTick, this); + pna.nextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } @@ -4716,7 +4755,7 @@ Readable.prototype.resume = function () { function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; - processNextTick(resume_, stream, state); + pna.nextTick(resume_, stream, state); } } @@ -4753,18 +4792,19 @@ function flow(stream) { // 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; - var self = this; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); + if (chunk && chunk.length) _this.push(chunk); } - self.push(null); + _this.push(null); }); stream.on('data', function (chunk) { @@ -4774,7 +4814,7 @@ Readable.prototype.wrap = function (stream) { // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = self.push(chunk); + var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); @@ -4795,12 +4835,12 @@ Readable.prototype.wrap = function (stream) { // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. - self._read = function (n) { + this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; @@ -4808,9 +4848,19 @@ Readable.prototype.wrap = function (stream) { } }; - return self; + return this; }; +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + // exposed for testing purposes only. Readable._fromList = fromList; @@ -4923,7 +4973,7 @@ function endReadable(stream) { if (!state.endEmitted) { state.ended = true; - processNextTick(endReadableNT, state, stream); + pna.nextTick(endReadableNT, state, stream); } } @@ -4936,12 +4986,6 @@ function endReadableNT(state, stream) { } } -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; @@ -4954,7 +4998,7 @@ function indexOf(xs, x) { /* 16 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(7).EventEmitter; +module.exports = __webpack_require__(8).EventEmitter; /***/ }), @@ -4966,7 +5010,7 @@ module.exports = __webpack_require__(7).EventEmitter; /**/ -var processNextTick = __webpack_require__(6); +var pna = __webpack_require__(6); /**/ // undocumented cb() API, needed for core, not for public API @@ -4980,9 +5024,9 @@ function destroy(err, cb) { if (cb) { cb(err); } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - processNextTick(emitErrorNT, this, err); + pna.nextTick(emitErrorNT, this, err); } - return; + return this; } // we set destroyed to true before firing error callbacks in order @@ -4999,7 +5043,7 @@ function destroy(err, cb) { this._destroy(err || null, function (err) { if (!cb && err) { - processNextTick(emitErrorNT, _this, err); + pna.nextTick(emitErrorNT, _this, err); if (_this._writableState) { _this._writableState.errorEmitted = true; } @@ -5007,6 +5051,8 @@ function destroy(err, cb) { cb(err); } }); + + return this; } function undestroy() { @@ -5069,7 +5115,7 @@ module.exports = { /**/ -var processNextTick = __webpack_require__(6); +var pna = __webpack_require__(6); /**/ module.exports = Writable; @@ -5096,7 +5142,7 @@ function CorkedRequest(state) { /* */ /**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; /**/ /**/ @@ -5106,13 +5152,13 @@ var Duplex; Writable.WritableState = WritableState; /**/ -var util = __webpack_require__(5); -util.inherits = __webpack_require__(2); +var util = __webpack_require__(4); +util.inherits = __webpack_require__(5); /**/ /**/ var internalUtil = { - deprecate: __webpack_require__(42) + deprecate: __webpack_require__(44) }; /**/ @@ -5121,7 +5167,8 @@ var Stream = __webpack_require__(16); /**/ /**/ -var Buffer = __webpack_require__(8).Buffer; + +var Buffer = __webpack_require__(9).Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); @@ -5129,6 +5176,7 @@ function _uint8ArrayToBuffer(chunk) { function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } + /**/ var destroyImpl = __webpack_require__(17); @@ -5138,22 +5186,31 @@ util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { - Duplex = Duplex || __webpack_require__(4); + Duplex = Duplex || __webpack_require__(3); 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 (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + 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; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + 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); @@ -5267,6 +5324,7 @@ if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.protot 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; } @@ -5278,7 +5336,7 @@ if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.protot } function Writable(options) { - Duplex = Duplex || __webpack_require__(4); + Duplex = Duplex || __webpack_require__(3); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` @@ -5318,7 +5376,7 @@ function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); - processNextTick(cb, er); + pna.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular @@ -5335,7 +5393,7 @@ function validChunk(stream, state, chunk, cb) { } if (er) { stream.emit('error', er); - processNextTick(cb, er); + pna.nextTick(cb, er); valid = false; } return valid; @@ -5344,7 +5402,7 @@ function validChunk(stream, state, chunk, cb) { Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; - var isBuf = _isUint8Array(chunk) && !state.objectMode; + var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); @@ -5398,6 +5456,16 @@ function decodeChunk(state, 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 fail + enumerable: 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. @@ -5455,10 +5523,10 @@ function onwriteError(stream, state, sync, er, cb) { if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack - processNextTick(cb, er); + pna.nextTick(cb, er); // this can emit finish, and it will always happen // after error - processNextTick(finishMaybe, stream, state); + pna.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { @@ -5556,6 +5624,7 @@ function clearBuffer(stream, state) { } else { state.corkedRequestsFree = new CorkedRequest(state); } + state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { @@ -5566,6 +5635,7 @@ function clearBuffer(stream, state) { 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 @@ -5578,7 +5648,6 @@ function clearBuffer(stream, state) { if (entry === null) state.lastBufferedRequest = null; } - state.bufferedRequestCount = 0; state.bufferedRequest = entry; state.bufferProcessing = false; } @@ -5632,7 +5701,7 @@ function prefinish(stream, state) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; - processNextTick(callFinal, stream, state); + pna.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); @@ -5656,7 +5725,7 @@ function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { - if (state.finished) processNextTick(cb);else stream.once('finish', cb); + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; @@ -5704,12 +5773,13 @@ Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(40).setImmediate, __webpack_require__(0))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(42).setImmediate, __webpack_require__(0))) /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { +"use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -5731,207 +5801,281 @@ Writable.prototype._destroy = function (err, cb) { // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -var Buffer = __webpack_require__(3).Buffer; -var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } +/**/ -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} +var Buffer = __webpack_require__(45).Buffer; +/**/ + +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; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function 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. CESU-8 is handled as part of the UTF-8 encoding. -// -// @TODO Handling all encodings inside a single object makes it very difficult -// to reason about this code, so it should be split up in the future. -// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code -// points as used by CESU-8. -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; break; case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; + this.text = base64Text; + this.end = base64End; + nb = 3; break; default: - this.write = passThroughWrite; + this.write = simpleWrite; + this.end = simpleEnd; return; } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; -}; - - -// write decodes the given buffer and returns it as JS string that is -// guaranteed to not contain any partial multi-byte characters. Any partial -// character found at the end of the buffer is buffered up, and will be -// returned when calling write again with the remaining bytes. -// -// Note: Converting a Buffer containing an orphan surrogate to a String -// currently works, but converting a String to a Buffer (via `new Buffer`, or -// Buffer#write) will replace incomplete surrogates with the unicode -// replacement character. See https://codereview.chromium.org/121173009/ . -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; +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 || ''; +}; - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } +StringDecoder.prototype.end = utf8End; - charStr += buffer.toString(this.encoding, 0, end); +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.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); } - - // or just emit the charStr - return charStr; + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; }; -// detectIncompleteChar determines if there is an incomplete UTF-8 character at -// the end of the given buffer. If so, it sets this.charLength to the byte -// length that character, and sets this.charReceived to the number of bytes -// that are available for this character. -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } +// 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; +} - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; +// 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'; + } } + } +} - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; +// 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.charReceived = i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); +// 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; +} - return res; -}; - -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); +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 utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; +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; } -function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; +// 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) : ''; +} /***/ }), /* 20 */ @@ -6005,48 +6149,37 @@ function base64DetectIncompleteChar(buffer) { module.exports = Transform; -var Duplex = __webpack_require__(4); +var Duplex = __webpack_require__(3); /**/ -var util = __webpack_require__(5); -util.inherits = __webpack_require__(2); +var util = __webpack_require__(4); +util.inherits = __webpack_require__(5); /**/ util.inherits(Transform, Duplex); -function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; +function afterTransform(er, data) { + var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { - return stream.emit('error', new Error('write callback called multiple times')); + return this.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; - if (data !== null && data !== undefined) stream.push(data); + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); cb(er); - var rs = stream._readableState; + var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); + this._read(rs.highWaterMark); } } @@ -6055,9 +6188,14 @@ function Transform(options) { Duplex.call(this, options); - this._transformState = new TransformState(this); - - var stream = this; + 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; @@ -6074,11 +6212,19 @@ function Transform(options) { } // When the writable side finishes, then flush out anything remaining. - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er, data) { - done(stream, er, data); - });else done(stream); - }); + 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) { @@ -6128,27 +6274,25 @@ Transform.prototype._read = function (n) { }; Transform.prototype._destroy = function (err, cb) { - var _this = this; + var _this2 = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); - _this.emit('close'); + _this2.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); - if (data !== null && data !== undefined) stream.push(data); + 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 provided - var ws = stream._writableState; - var ts = stream._transformState; - - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } @@ -6172,18 +6316,30 @@ if (typeof window === 'object') { /* 22 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(process) {var original = __webpack_require__(23) -var parse = __webpack_require__(10).parse -var events = __webpack_require__(7) -var https = __webpack_require__(33) -var http = __webpack_require__(11) -var util = __webpack_require__(47) +/* WEBPACK VAR INJECTION */(function(process, Buffer) {var original = __webpack_require__(26) +var parse = __webpack_require__(7).parse +var events = __webpack_require__(8) +var https = __webpack_require__(36) +var http = __webpack_require__(10) +var util = __webpack_require__(50) var httpsOptions = [ 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', 'rejectUnauthorized', 'secureProtocol', 'servername' ] +var bom = [239, 187, 191] +var colon = 58 +var space = 32 +var lineFeed = 10 +var carriageReturn = 13 + +function hasBom (buf) { + return bom.every(function (charCode, index) { + return buf[index] === charCode + }) +} + /** * Creates a new EventSource object * @@ -6334,16 +6490,21 @@ function EventSource (url, eventSourceInitDict) { // text/event-stream parser adapted from webkit's // Source/WebCore/page/EventSource.cpp - var buf = '' + var isFirst = true + var buf res.on('data', function (chunk) { - buf += chunk + buf = buf ? Buffer.concat([buf, chunk]) : chunk + if (isFirst && hasBom(buf)) { + buf = buf.slice(bom.length) + } + isFirst = false var pos = 0 var length = buf.length while (pos < length) { if (discardTrailingNewline) { - if (buf[pos] === '\n') { + if (buf[pos] === lineFeed) { ++pos } discardTrailingNewline = false @@ -6355,14 +6516,14 @@ function EventSource (url, eventSourceInitDict) { for (var i = pos; lineLength < 0 && i < length; ++i) { c = buf[i] - if (c === ':') { + if (c === colon) { if (fieldLength < 0) { fieldLength = i - pos } - } else if (c === '\r') { + } else if (c === carriageReturn) { discardTrailingNewline = true lineLength = i - pos - } else if (c === '\n') { + } else if (c === lineFeed) { lineLength = i - pos } } @@ -6377,7 +6538,7 @@ function EventSource (url, eventSourceInitDict) { } if (pos === length) { - buf = '' + buf = void 0 } else if (pos > 0) { buf = buf.slice(pos) } @@ -6419,11 +6580,11 @@ function EventSource (url, eventSourceInitDict) { } else if (fieldLength > 0) { var noValue = fieldLength < 0 var step = 0 - var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)) + var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString() if (noValue) { step = lineLength - } else if (buf[pos + fieldLength + 1] !== ' ') { + } else if (buf[pos + fieldLength + 1] !== space) { step = fieldLength + 1 } else { step = fieldLength + 2 @@ -6431,7 +6592,7 @@ function EventSource (url, eventSourceInitDict) { pos += step var valueLength = lineLength - step - var value = buf.slice(pos, pos + valueLength) + var value = buf.slice(pos, pos + valueLength).toString() if (field === 'data') { data += value + '\n' @@ -6567,7 +6728,7 @@ function MessageEvent (type, eventInitDict) { } } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(2).Buffer)) /***/ }), /* 23 */ @@ -6576,1543 +6737,1689 @@ function MessageEvent (type, eventInitDict) { "use strict"; -var parse = __webpack_require__(9); - -/** - * Transform an URL to a valid origin value. - * - * @param {String|Object} url URL to transform to it's origin. - * @returns {String} The origin. - * @api public - */ -function origin(url) { - if ('string' === typeof url) url = parse(url); +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray - // - // 6.2. ASCII Serialization of an Origin - // http://tools.ietf.org/html/rfc6454#section-6.2 - // - if (!url.protocol || !url.hostname) return 'null'; +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - // - // 4. Origin of a URI - // http://tools.ietf.org/html/rfc6454#section-4 - // - // States that url.scheme, host should be converted to lower case. This also - // makes it easier to match origins as everything is just lower case. - // - return (url.protocol +'//'+ url.host).toLowerCase(); +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i } -/** - * Check if the origins are the same. - * - * @param {String} a URL or origin of a. - * @param {String} b URL or origin of b. - * @returns {Boolean} - * @api public - */ -origin.same = function same(a, b) { - return origin(a) === origin(b); -}; +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 -// -// Expose the origin -// -module.exports = origin; +function getLens (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len -"use strict"; + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + return [validLen, placeHoldersLen] +} -/** - * Check if we're required to add a port number. - * - * @see https://url.spec.whatwg.org/#default-port - * @param {Number|String} port Port number we need to check - * @param {String} protocol Protocol we need to check against. - * @returns {Boolean} Is it a default port for the given protocol - * @api private - */ -module.exports = function required(port, protocol) { - protocol = protocol.split(':')[0]; - port = +port; +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} - if (!port) return false; +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} - switch (protocol) { - case 'http': - case 'ws': - return port !== 80; +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] - case 'https': - case 'wss': - return port !== 443; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - case 'ftp': - return port !== 21; + var curByte = 0 - case 'gopher': - return port !== 70; + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen - case 'file': - return false; + for (var i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF } - return port !== 0; -}; + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { + return arr +} -"use strict"; -/* WEBPACK VAR INJECTION */(function(global) { +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} -/** - * These properties should not be copied or inherited from. This is only needed - * for all non blob URL's as the a blob URL does not include a hash, only the - * origin. - * - * @type {Object} - * @private - */ -var ignore = { hash: 1, query: 1 } - , URL; +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} -/** - * The location object differs when your code is loaded through a normal page, - * Worker or through a worker using a blob. And with the blobble begins the - * trouble as the location object will contain the URL of the blob, not the - * location of the page where our code is loaded in. The actual origin is - * encoded in the `pathname` so we can thankfully generate a good "default" - * location from it so we can generate proper relative URL's again. - * - * @param {Object} loc Optional default location object. - * @returns {Object} lolcation object. - * @api public - */ -module.exports = function lolcation(loc) { - loc = loc || global.location || {}; - URL = URL || __webpack_require__(9); +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 - var finaldestination = {} - , type = typeof loc - , key; + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } - if ('blob:' === loc.protocol) { - finaldestination = new URL(unescape(loc.pathname), {}); - } else if ('string' === type) { - finaldestination = new URL(loc, {}); - for (key in ignore) delete finaldestination[key]; - } else if ('object' === type) for (key in loc) { - if (key in ignore) continue; - finaldestination[key] = loc[key]; + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) } - return finaldestination; -}; + return parts.join('') +} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) /***/ }), -/* 26 */ +/* 24 */ +/***/ (function(module, exports) { + +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), +/* 25 */ +/***/ (function(module, exports) { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), +/* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var has = Object.prototype.hasOwnProperty; +var parse = __webpack_require__(27); /** - * Simple query string parser. + * Transform an URL to a valid origin value. * - * @param {String} query The query string that needs to be parsed. - * @returns {Object} + * @param {String|Object} url URL to transform to it's origin. + * @returns {String} The origin. * @api public */ -function querystring(query) { - var parser = /([^=?&]+)=?([^&]*)/g - , result = {} - , part; +function origin(url) { + if ('string' === typeof url) url = parse(url); // - // Little nifty parsing hack, leverage the fact that RegExp.exec increments - // the lastIndex property so we can continue executing this loop until we've - // parsed all results. + // 6.2. ASCII Serialization of an Origin + // http://tools.ietf.org/html/rfc6454#section-6.2 // - for (; - part = parser.exec(query); - result[decodeURIComponent(part[1])] = decodeURIComponent(part[2]) - ); + if (!url.protocol || !url.hostname) return 'null'; - return result; + // + // 4. Origin of a URI + // http://tools.ietf.org/html/rfc6454#section-4 + // + // States that url.scheme, host should be converted to lower case. This also + // makes it easier to match origins as everything is just lower case. + // + return (url.protocol +'//'+ url.host).toLowerCase(); } /** - * Transform a query string to an object. + * Check if the origins are the same. * - * @param {Object} obj Object that should be transformed. - * @param {String} prefix Optional prefix. - * @returns {String} + * @param {String} a URL or origin of a. + * @param {String} b URL or origin of b. + * @returns {Boolean} * @api public */ -function querystringify(obj, prefix) { - prefix = prefix || ''; - - var pairs = []; - - // - // Optionally prefix with a '?' if needed - // - if ('string' !== typeof prefix) prefix = '?'; - - for (var key in obj) { - if (has.call(obj, key)) { - pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key])); - } - } - - return pairs.length ? prefix + pairs.join('&') : ''; -} +origin.same = function same(a, b) { + return origin(a) === origin(b); +}; // -// Expose the module. +// Expose the origin // -exports.stringify = querystringify; -exports.parse = querystring; +module.exports = origin; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */ -;(function(root) { +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { - /** Detect free variables */ - var freeExports = typeof exports == 'object' && exports && - !exports.nodeType && exports; - var freeModule = typeof module == 'object' && module && - !module.nodeType && module; - var freeGlobal = typeof global == 'object' && global; - if ( - freeGlobal.global === freeGlobal || - freeGlobal.window === freeGlobal || - freeGlobal.self === freeGlobal - ) { - root = freeGlobal; - } +var required = __webpack_require__(28) + , qs = __webpack_require__(29) + , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i + , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//; - /** - * The `punycode` object. - * @name punycode - * @type Object - */ - var punycode, +/** + * These are the parse rules for the URL parser, it informs the parser + * about: + * + * 0. The char it Needs to parse, if it's a string it should be done using + * indexOf, RegExp using exec and NaN means set as current value. + * 1. The property we should set when parsing this value. + * 2. Indication if it's backwards or forward parsing, when set as number it's + * the value of extra chars that should be split off. + * 3. Inherit from location if non existing in the parser. + * 4. `toLowerCase` the resulting value. + */ +var rules = [ + ['#', 'hash'], // Extract from the back. + ['?', 'query'], // Extract from the back. + function sanitize(address) { // Sanitize what is left of the address + return address.replace('\\', '/'); + }, + ['/', 'pathname'], // Extract from the back. + ['@', 'auth', 1], // Extract from the front. + [NaN, 'host', undefined, 1, 1], // Set left over value. + [/:(\d+)$/, 'port', undefined, 1], // RegExp the back. + [NaN, 'hostname', undefined, 1, 1] // Set left over. +]; - /** Highest positive signed 32-bit float value */ - maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 +/** + * These properties should not be copied or inherited from. This is only needed + * for all non blob URL's as a blob URL does not include a hash, only the + * origin. + * + * @type {Object} + * @private + */ +var ignore = { hash: 1, query: 1 }; - /** Bootstring parameters */ - base = 36, - tMin = 1, - tMax = 26, - skew = 38, - damp = 700, - initialBias = 72, - initialN = 128, // 0x80 - delimiter = '-', // '\x2D' +/** + * The location object differs when your code is loaded through a normal page, + * Worker or through a worker using a blob. And with the blobble begins the + * trouble as the location object will contain the URL of the blob, not the + * location of the page where our code is loaded in. The actual origin is + * encoded in the `pathname` so we can thankfully generate a good "default" + * location from it so we can generate proper relative URL's again. + * + * @param {Object|String} loc Optional default location object. + * @returns {Object} lolcation object. + * @public + */ +function lolcation(loc) { + var location = global && global.location || {}; + loc = loc || location; - /** Regular expressions */ - regexPunycode = /^xn--/, - regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars - regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + var finaldestination = {} + , type = typeof loc + , key; - /** Error messages */ - errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }, + if ('blob:' === loc.protocol) { + finaldestination = new Url(unescape(loc.pathname), {}); + } else if ('string' === type) { + finaldestination = new Url(loc, {}); + for (key in ignore) delete finaldestination[key]; + } else if ('object' === type) { + for (key in loc) { + if (key in ignore) continue; + finaldestination[key] = loc[key]; + } - /** Convenience shortcuts */ - baseMinusTMin = base - tMin, - floor = Math.floor, - stringFromCharCode = String.fromCharCode, + if (finaldestination.slashes === undefined) { + finaldestination.slashes = slashes.test(loc.href); + } + } - /** Temporary variable */ - key; + return finaldestination; +} - /*--------------------------------------------------------------------------*/ +/** + * @typedef ProtocolExtract + * @type Object + * @property {String} protocol Protocol matched in the URL, in lowercase. + * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`. + * @property {String} rest Rest of the URL that is not part of the protocol. + */ - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw new RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map(array, fn) { - var length = array.length; - var result = []; - while (length--) { - result[length] = fn(array[length]); - } - return result; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ - function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ - function ucs2encode(array) { - return map(array, function(value) { - var output = ''; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - return output; - }).join(''); - } - - /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ - function basicToDigit(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; - } - - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - } - - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * 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-2 - var output = [], - inputLength = input.length, - out, - i = 0, - n = initialN, - bias = initialBias, - basic, - j, - index, - oldi, - w, - k, - digit, - t, - /** Cached calculation results */ - baseMinusT; +/** + * Extract protocol information from a URL with/without double slash ("//"). + * + * @param {String} address URL we want to extract from. + * @return {ProtocolExtract} Extracted information. + * @private + */ +function extractProtocol(address) { + var match = protocolre.exec(address); - // 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. + return { + protocol: match[1] ? match[1].toLowerCase() : '', + slashes: !!match[2], + rest: match[3] + }; +} - basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } +/** + * Resolve a relative URL pathname against a base URL pathname. + * + * @param {String} relative Pathname of the relative URL. + * @param {String} base Pathname of the base URL. + * @return {String} Resolved pathname. + * @private + */ +function resolve(relative, base) { + var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) + , i = path.length + , last = path[i - 1] + , unshift = false + , up = 0; - for (j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } + while (i--) { + if (path[i] === '.') { + path.splice(i, 1); + } else if (path[i] === '..') { + path.splice(i, 1); + up++; + } else if (up) { + if (i === 0) unshift = true; + path.splice(i, 1); + up--; + } + } - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. + if (unshift) path.unshift(''); + if (last === '.' || last === '..') path.push(''); - for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + return path.join('/'); +} - // `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) { +/** + * The actual URL instance. Instead of returning an object we've opted-in to + * create an actual constructor as it's much more memory efficient and + * faster and it pleases my OCD. + * + * It is worth noting that we should not use `URL` as class name to prevent + * clashes with the global URL instance that got introduced in browsers. + * + * @constructor + * @param {String} address URL we want to parse. + * @param {Object|String} location Location defaults for relative paths. + * @param {Boolean|Function} parser Parser for the query string. + * @private + */ +function Url(address, location, parser) { + if (!(this instanceof Url)) { + return new Url(address, location, parser); + } - if (index >= inputLength) { - error('invalid-input'); - } + var relative, extracted, parse, instruction, index, key + , instructions = rules.slice() + , type = typeof location + , url = this + , i = 0; - digit = basicToDigit(input.charCodeAt(index++)); + // + // The following if statements allows this module two have compatibility with + // 2 different API: + // + // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments + // where the boolean indicates that the query string should also be parsed. + // + // 2. The `URL` interface of the browser which accepts a URL, object as + // arguments. The supplied object will be used as default values / fall-back + // for relative paths. + // + if ('object' !== type && 'string' !== type) { + parser = location; + location = null; + } - if (digit >= base || digit > floor((maxInt - i) / w)) { - error('overflow'); - } + if (parser && 'function' !== typeof parser) parser = qs.parse; - i += digit * w; - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + location = lolcation(location); - if (digit < t) { - break; - } + // + // Extract protocol information before running the instructions. + // + extracted = extractProtocol(address || ''); + relative = !extracted.protocol && !extracted.slashes; + url.slashes = extracted.slashes || relative && location.slashes; + url.protocol = extracted.protocol || location.protocol || ''; + address = extracted.rest; - baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } + // + // When the authority component is absent the URL starts with a path + // component. + // + if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname']; - w *= baseMinusT; + for (; i < instructions.length; i++) { + instruction = instructions[i]; - } + if (typeof instruction === 'function') { + address = instruction(address); + continue; + } - out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); + parse = instruction[0]; + key = instruction[1]; - // `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'); - } + if (parse !== parse) { + url[key] = address; + } else if ('string' === typeof parse) { + if (~(index = address.indexOf(parse))) { + if ('number' === typeof instruction[2]) { + url[key] = address.slice(0, index); + address = address.slice(index + instruction[2]); + } else { + url[key] = address.slice(index); + address = address.slice(0, index); + } + } + } else if ((index = parse.exec(address))) { + url[key] = index[1]; + address = address.slice(0, index.index); + } - n += floor(i / out); - i %= out; + url[key] = url[key] || ( + relative && instruction[3] ? location[key] || '' : '' + ); - // Insert `n` at position `i` of the output - output.splice(i++, 0, n); + // + // Hostname, host and protocol should be lowercased so they can be used to + // create a proper `origin`. + // + if (instruction[4]) url[key] = url[key].toLowerCase(); + } - } + // + // Also parse the supplied query string in to an object. If we're supplied + // with a custom parser as function use that instead of the default build-in + // parser. + // + if (parser) url.query = parser(url.query); - return ucs2encode(output); - } + // + // If the URL is relative, resolve the pathname against the base URL. + // + if ( + relative + && location.slashes + && url.pathname.charAt(0) !== '/' + && (url.pathname !== '' || location.pathname !== '') + ) { + url.pathname = resolve(url.pathname, location.pathname); + } - /** - * 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; + // + // We should not add port numbers if they are already the default port number + // for a given protocol. As the host also contains the port number we're going + // override it with the hostname which contains no port number. + // + if (!required(url.port, url.protocol)) { + url.host = url.hostname; + url.port = ''; + } - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); + // + // Parse down the `auth` for the username and password. + // + url.username = url.password = ''; + if (url.auth) { + instruction = url.auth.split(':'); + url.username = instruction[0] || ''; + url.password = instruction[1] || ''; + } - // Cache the length - inputLength = input.length; + url.origin = url.protocol && url.host && url.protocol !== 'file:' + ? url.protocol +'//'+ url.host + : 'null'; - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; + // + // The href is just the compiled result. + // + url.href = url.toString(); +} - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } +/** + * This is convenience method for changing properties in the URL instance to + * insure that they all propagate correctly. + * + * @param {String} part Property we need to adjust. + * @param {Mixed} value The newly assigned value. + * @param {Boolean|Function} fn When setting the query, it will be the function + * used to parse the query. + * When setting the protocol, double slash will be + * removed from the final url if it is true. + * @returns {URL} URL instance for chaining. + * @public + */ +function set(part, value, fn) { + var url = this; - handledCPCount = basicLength = output.length; + switch (part) { + case 'query': + if ('string' === typeof value && value.length) { + value = (fn || qs.parse)(value); + } - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. + url[part] = value; + break; - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } + case 'port': + url[part] = value; - // Main encoding loop: - while (handledCPCount < inputLength) { + if (!required(value, url.protocol)) { + url.host = url.hostname; + url[part] = ''; + } else if (value) { + url.host = url.hostname +':'+ value; + } - // 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; - } - } + break; - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } + case 'hostname': + url[part] = value; - delta += (m - n) * handledCPCountPlusOne; - n = m; + if (url.port) value += ':'+ url.port; + url.host = value; + break; - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; + case 'host': + url[part] = value; - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } + if (/:\d+$/.test(value)) { + value = value.split(':'); + url.port = value.pop(); + url.hostname = value.join(':'); + } else { + url.hostname = value; + url.port = ''; + } - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } + break; - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } + case 'protocol': + url.protocol = value.toLowerCase(); + url.slashes = !fn; + break; - ++delta; - ++n; + case 'pathname': + case 'hash': + if (value) { + var char = part === 'pathname' ? '/' : '#'; + url[part] = value.charAt(0) !== char ? char + value : value; + } else { + url[part] = value; + } + break; - } - return output.join(''); - } + default: + url[part] = value; + } - /** - * 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; - }); - } + for (var i = 0; i < rules.length; i++) { + var ins = rules[i]; - /** - * 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; - }); - } + if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); + } - /*--------------------------------------------------------------------------*/ + url.origin = url.protocol && url.host && url.protocol !== 'file:' + ? url.protocol +'//'+ url.host + : 'null'; - /** 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 - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode - }; + url.href = url.toString(); - /** Expose `punycode` */ - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - true - ) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { - return punycode; - }.call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } 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 browser - root.punycode = punycode; - } + return url; +} -}(this)); +/** + * Transform the properties back in to a valid and full URL string. + * + * @param {Function} stringify Optional query stringify function. + * @returns {String} Compiled version of the URL. + * @public + */ +function toString(stringify) { + if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(28)(module), __webpack_require__(0))) + var query + , url = this + , protocol = url.protocol; -/***/ }), -/* 28 */ -/***/ (function(module, exports) { + if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; -module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - if(!module.children) module.children = []; - Object.defineProperty(module, "loaded", { - enumerable: true, - get: function() { - return module.l; - } - }); - Object.defineProperty(module, "id", { - enumerable: true, - get: function() { - return module.i; - } - }); - module.webpackPolyfill = 1; - } - return module; -}; + var result = protocol + (url.slashes ? '//' : ''); + if (url.username) { + result += url.username; + if (url.password) result += ':'+ url.password; + result += '@'; + } -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { + result += url.host + url.pathname; -"use strict"; + query = 'object' === typeof url.query ? stringify(url.query) : url.query; + if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; + if (url.hash) result += url.hash; -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; - } -}; + return result; +} +Url.prototype = { set: set, toString: toString }; + +// +// Expose the URL parser and some additional properties that might be useful for +// others or testing. +// +Url.extractProtocol = extractProtocol; +Url.location = lolcation; +Url.qs = qs; + +module.exports = Url; + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) /***/ }), -/* 30 */ +/* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -exports.decode = exports.parse = __webpack_require__(31); -exports.encode = exports.stringify = __webpack_require__(32); +/** + * Check if we're required to add a port number. + * + * @see https://url.spec.whatwg.org/#default-port + * @param {Number|String} port Port number we need to check + * @param {String} protocol Protocol we need to check against. + * @returns {Boolean} Is it a default port for the given protocol + * @api private + */ +module.exports = function required(port, protocol) { + protocol = protocol.split(':')[0]; + port = +port; + + if (!port) return false; + + switch (protocol) { + case 'http': + case 'ws': + return port !== 80; + + case 'https': + case 'wss': + return port !== 443; + + case 'ftp': + return port !== 21; + + case 'gopher': + return port !== 70; + + case 'file': + return false; + } + + return port !== 0; +}; /***/ }), -/* 31 */ +/* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// 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 has = Object.prototype.hasOwnProperty; -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); +/** + * Decode a URI encoded string. + * + * @param {String} input The URI encoded string. + * @returns {String} The decoded string. + * @api private + */ +function decode(input) { + return decodeURIComponent(input.replace(/\+/g, ' ')); } -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } +/** + * Simple query string parser. + * + * @param {String} query The query string that needs to be parsed. + * @returns {Object} + * @api public + */ +function querystring(query) { + var parser = /([^=?&]+)=?([^&]*)/g + , result = {} + , part; - var regexp = /\+/g; - qs = qs.split(sep); + while (part = parser.exec(query)) { + var key = decode(part[1]) + , value = decode(part[2]); - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; + // + // Prevent overriding of existing properties. This ensures that build-in + // methods like `toString` or __proto__ are not overriden by malicious + // querystrings. + // + if (key in result) continue; + result[key] = value; } - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } + return result; +} - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; +/** + * Transform a query string to an object. + * + * @param {Object} obj Object that should be transformed. + * @param {String} prefix Optional prefix. + * @returns {String} + * @api public + */ +function querystringify(obj, prefix) { + prefix = prefix || ''; - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } + var pairs = []; - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); + // + // Optionally prefix with a '?' if needed + // + if ('string' !== typeof prefix) prefix = '?'; - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; + for (var key in obj) { + if (has.call(obj, key)) { + pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key])); } } - return obj; -}; + return pairs.length ? prefix + pairs.join('&') : ''; +} -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; +// +// Expose the module. +// +exports.stringify = querystringify; +exports.parse = querystring; /***/ }), -/* 32 */ +/* 30 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; -// 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. +/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 -var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' - case 'boolean': - return v ? 'true' : 'false'; + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - case 'number': - return isFinite(v) ? v : ''; + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } - default: - return ''; - } -}; + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } - 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); + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } - } + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; + /** + * 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)); + } -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; -} + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; -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; -}; + // 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; + } -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } -var http = __webpack_require__(11); + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. -var https = module.exports; + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { -for (var key in http) { - if (http.hasOwnProperty(key)) https[key] = http[key]; -}; + // `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) { -https.request = function (params, cb) { - if (!params) params = {}; - params.scheme = 'https'; - params.protocol = 'https:'; - return http.request.call(this, params, cb); -} + if (index >= inputLength) { + error('invalid-input'); + } + digit = basicToDigit(input.charCodeAt(index++)); -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } -/* WEBPACK VAR INJECTION */(function(Buffer, global, process) {var capability = __webpack_require__(13) -var inherits = __webpack_require__(2) -var response = __webpack_require__(37) -var stream = __webpack_require__(14) -var toArrayBuffer = __webpack_require__(44) + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); -var IncomingMessage = response.IncomingMessage -var rStates = response.readyStates + if (digit < t) { + break; + } -function decideMode (preferBinary, useFetch) { - if (capability.fetch && useFetch) { - return 'fetch' - } else if (capability.mozchunkedarraybuffer) { - return 'moz-chunked-arraybuffer' - } else if (capability.msstream) { - return 'ms-stream' - } else if (capability.arraybuffer && preferBinary) { - return 'arraybuffer' - } else if (capability.vbArray && preferBinary) { - return 'text:vbarray' - } else { - return 'text' - } -} + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } -var ClientRequest = module.exports = function (opts) { - var self = this - stream.Writable.call(self) + w *= baseMinusT; - self._opts = opts - self._body = [] - self._headers = {} - if (opts.auth) - self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) - Object.keys(opts.headers).forEach(function (name) { - self.setHeader(name, opts.headers[name]) - }) + } - var preferBinary - var useFetch = true - if (opts.mode === 'disable-fetch' || 'timeout' in opts) { - // If the use of XHR should be preferred and includes preserving the 'content-type' header. - // Force XHR to be used since the Fetch API does not yet support timeouts. - useFetch = false - preferBinary = true - } else if (opts.mode === 'prefer-streaming') { - // If streaming is a high priority but binary compatibility and - // the accuracy of the 'content-type' header aren't - preferBinary = false - } else if (opts.mode === 'allow-wrong-content-type') { - // If streaming is more important than preserving the 'content-type' header - preferBinary = !capability.overrideMimeType - } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { - // Use binary if text streaming may corrupt data or the content-type header, or for speed - preferBinary = true - } else { - throw new Error('Invalid value for opts.mode') - } - self._mode = decideMode(preferBinary, useFetch) + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); - self.on('finish', function () { - self._onFinish() - }) -} + // `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'); + } -inherits(ClientRequest, stream.Writable) + n += floor(i / out); + i %= out; -ClientRequest.prototype.setHeader = function (name, value) { - var self = this - var lowerName = name.toLowerCase() - // This check is not necessary, but it prevents warnings from browsers about setting unsafe - // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but - // http-browserify did it, so I will too. - if (unsafeHeaders.indexOf(lowerName) !== -1) - return + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); - self._headers[lowerName] = { - name: name, - value: value + } + + return ucs2encode(output); } -} -ClientRequest.prototype.getHeader = function (name) { - var header = this._headers[name.toLowerCase()] - if (header) - return header.value - return null -} + /** + * 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; -ClientRequest.prototype.removeHeader = function (name) { - var self = this - delete self._headers[name.toLowerCase()] -} + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); -ClientRequest.prototype._onFinish = function () { - var self = this + // Cache the length + inputLength = input.length; - if (self._destroyed) - return - var opts = self._opts + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; - var headersObj = self._headers - var body = null - if (opts.method !== 'GET' && opts.method !== 'HEAD') { - if (capability.blobConstructor) { - body = new global.Blob(self._body.map(function (buffer) { - return toArrayBuffer(buffer) - }), { - type: (headersObj['content-type'] || {}).value || '' - }) - } else { - // get utf8 string - body = Buffer.concat(self._body).toString() + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } } - } - // create flattened list of headers - var headersList = [] - Object.keys(headersObj).forEach(function (keyName) { - var name = headersObj[keyName].name - var value = headersObj[keyName].value - if (Array.isArray(value)) { - value.forEach(function (v) { - headersList.push([name, v]) - }) - } else { - headersList.push([name, value]) - } - }) + handledCPCount = basicLength = output.length; - if (self._mode === 'fetch') { - global.fetch(self._opts.url, { - method: self._opts.method, - headers: headersList, - body: body || undefined, - mode: 'cors', - credentials: opts.withCredentials ? 'include' : 'same-origin' - }).then(function (response) { - self._fetchResponse = response - self._connect() - }, function (reason) { - self.emit('error', reason) - }) - } else { - var xhr = self._xhr = new global.XMLHttpRequest() - try { - xhr.open(self._opts.method, self._opts.url, true) - } catch (err) { - process.nextTick(function () { - self.emit('error', err) - }) - return - } + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. - // Can't set responseType on really old browsers - if ('responseType' in xhr) - xhr.responseType = self._mode.split(':')[0] + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } - if ('withCredentials' in xhr) - xhr.withCredentials = !!opts.withCredentials + // Main encoding loop: + while (handledCPCount < inputLength) { - if (self._mode === 'text' && 'overrideMimeType' in xhr) - xhr.overrideMimeType('text/plain; charset=x-user-defined') + // 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; + } + } - if ('timeout' in opts) { - xhr.timeout = opts.timeout - xhr.ontimeout = function () { - self.emit('timeout') + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); } - } - headersList.forEach(function (header) { - xhr.setRequestHeader(header[0], header[1]) - }) + delta += (m - n) * handledCPCountPlusOne; + n = m; - self._response = null - xhr.onreadystatechange = function () { - switch (xhr.readyState) { - case rStates.LOADING: - case rStates.DONE: - self._onXHRProgress() - break - } - } - // Necessary for streaming in Firefox, since xhr.response is ONLY defined - // in onprogress, not in onreadystatechange with xhr.readyState = 3 - if (self._mode === 'moz-chunked-arraybuffer') { - xhr.onprogress = function () { - self._onXHRProgress() + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } } - } - xhr.onerror = function () { - if (self._destroyed) - return - self.emit('error', new Error('XHR error')) - } + ++delta; + ++n; - try { - xhr.send(body) - } catch (err) { - process.nextTick(function () { - self.emit('error', err) - }) - return } + return output.join(''); } -} -/** - * Checks if xhr.status is readable and non-zero, indicating no error. - * Even though the spec says it should be available in readyState 3, - * accessing it throws an exception in IE8 - */ -function statusValid (xhr) { - try { - var status = xhr.status - return (status !== null && status !== 0) - } catch (e) { - return false + /** + * 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; + }); } -} -ClientRequest.prototype._onXHRProgress = function () { - var self = this + /** + * 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; + }); + } - if (!statusValid(self._xhr) || self._destroyed) - return + /*--------------------------------------------------------------------------*/ - if (!self._response) - self._connect() + /** 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 + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; - self._response._onXHRProgress() -} + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + true + ) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return punycode; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } 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 browser + root.punycode = punycode; + } -ClientRequest.prototype._connect = function () { - var self = this +}(this)); - if (self._destroyed) - return +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(31)(module), __webpack_require__(0))) - self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode) - self._response.on('error', function(err) { - self.emit('error', err) - }) +/***/ }), +/* 31 */ +/***/ (function(module, exports) { - self.emit('response', self._response) -} +module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + if(!module.children) module.children = []; + Object.defineProperty(module, "loaded", { + enumerable: true, + get: function() { + return module.l; + } + }); + Object.defineProperty(module, "id", { + enumerable: true, + get: function() { + return module.i; + } + }); + module.webpackPolyfill = 1; + } + return module; +}; -ClientRequest.prototype._write = function (chunk, encoding, cb) { - var self = this - self._body.push(chunk) - cb() -} +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { -ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { - var self = this - self._destroyed = true - if (self._response) - self._response._destroyed = true - if (self._xhr) - self._xhr.abort() - // Currently, there isn't a way to truly abort a fetch. - // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27 -} +"use strict"; -ClientRequest.prototype.end = function (data, encoding, cb) { - var self = this - if (typeof data === 'function') { - cb = data - data = undefined - } - stream.Writable.prototype.end.call(self, data, encoding, cb) -} +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; + } +}; -ClientRequest.prototype.flushHeaders = function () {} -ClientRequest.prototype.setTimeout = function () {} -ClientRequest.prototype.setNoDelay = function () {} -ClientRequest.prototype.setSocketKeepAlive = function () {} -// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method -var unsafeHeaders = [ - 'accept-charset', - 'accept-encoding', - 'access-control-request-headers', - 'access-control-request-method', - 'connection', - 'content-length', - 'cookie', - 'cookie2', - 'date', - 'dnt', - 'expect', - 'host', - 'keep-alive', - 'origin', - 'referer', - 'te', - 'trailer', - 'transfer-encoding', - 'upgrade', - 'user-agent', - 'via' -] +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.decode = exports.parse = __webpack_require__(34); +exports.encode = exports.stringify = __webpack_require__(35); -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3).Buffer, __webpack_require__(0), __webpack_require__(1))) /***/ }), -/* 35 */ +/* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +// 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. -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); } -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; -function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') + if (typeof qs !== 'string' || qs.length === 0) { + return obj; } - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 -} + var regexp = /\+/g; + qs = qs.split(sep); -function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return (b64.length * 3 / 4) - placeHoldersCount(b64) -} + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } -function toByteArray (b64) { - var i, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } - arr = new Arr((len * 3 / 4) - placeHolders) + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } - var L = 0 + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); - for (i = 0; i < l; i += 4) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } } - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } + return obj; +}; - return arr -} +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 +"use strict"; +// 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. - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } - parts.push(output) +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; - return parts.join('') -} + case 'number': + return isFinite(v) ? v : ''; + default: + return ''; + } +}; -/***/ }), -/* 36 */ -/***/ (function(module, exports) { +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] + 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); - i += d + } - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias +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 (s ? -1 : 1) * m * Math.pow(2, e - mLen) + return res; } -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 +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; +}; - value = Math.abs(value) - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } +var http = __webpack_require__(10) +var url = __webpack_require__(7) - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} +var https = module.exports - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key] +} - buffer[offset + i - d] |= s * 128 +https.request = function (params, cb) { + params = validateParams(params) + return http.request.call(this, params, cb) +} + +https.get = function (params, cb) { + params = validateParams(params) + return http.get.call(this, params, cb) +} + +function validateParams (params) { + if (typeof params === 'string') { + params = url.parse(params) + } + if (!params.protocol) { + params.protocol = 'https:' + } + if (params.protocol !== 'https:') { + throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"') + } + return params } @@ -8120,210 +8427,364 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { /* 37 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(process, Buffer, global) {var capability = __webpack_require__(13) -var inherits = __webpack_require__(2) +/* WEBPACK VAR INJECTION */(function(Buffer, global, process) {var capability = __webpack_require__(11) +var inherits = __webpack_require__(12) +var response = __webpack_require__(13) var stream = __webpack_require__(14) +var toArrayBuffer = __webpack_require__(47) -var rStates = exports.readyStates = { - UNSENT: 0, - OPENED: 1, - HEADERS_RECEIVED: 2, - LOADING: 3, - DONE: 4 +var IncomingMessage = response.IncomingMessage +var rStates = response.readyStates + +function decideMode (preferBinary, useFetch) { + if (capability.fetch && useFetch) { + return 'fetch' + } else if (capability.mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (capability.msstream) { + return 'ms-stream' + } else if (capability.arraybuffer && preferBinary) { + return 'arraybuffer' + } else if (capability.vbArray && preferBinary) { + return 'text:vbarray' + } else { + return 'text' + } } -var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) { +var ClientRequest = module.exports = function (opts) { var self = this - stream.Readable.call(self) + stream.Writable.call(self) - self._mode = mode - self.headers = {} - self.rawHeaders = [] - self.trailers = {} - self.rawTrailers = [] + self._opts = opts + self._body = [] + self._headers = {} + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) + Object.keys(opts.headers).forEach(function (name) { + self.setHeader(name, opts.headers[name]) + }) - // Fake the 'close' event, but only once 'end' fires - self.on('end', function () { - // The nextTick is necessary to prevent the 'request' module from causing an infinite loop - process.nextTick(function () { - self.emit('close') - }) + var preferBinary + var useFetch = true + if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) { + // If the use of XHR should be preferred. Not typically needed. + useFetch = false + preferBinary = true + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !capability.overrideMimeType + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary, useFetch) + self._fetchTimer = null + + self.on('finish', function () { + self._onFinish() }) +} - if (mode === 'fetch') { - self._fetchResponse = response +inherits(ClientRequest, stream.Writable) - self.url = response.url - self.statusCode = response.status - self.statusMessage = response.statusText - - response.headers.forEach(function(header, key){ - self.headers[key.toLowerCase()] = header - self.rawHeaders.push(key, header) - }) +ClientRequest.prototype.setHeader = function (name, value) { + var self = this + var lowerName = name.toLowerCase() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + self._headers[lowerName] = { + name: name, + value: value + } +} - // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed - var reader = response.body.getReader() - function read () { - reader.read().then(function (result) { - if (self._destroyed) - return - if (result.done) { - self.push(null) - return - } - self.push(new Buffer(result.value)) - read() - }).catch(function(err) { - self.emit('error', err) +ClientRequest.prototype.getHeader = function (name) { + var header = this._headers[name.toLowerCase()] + if (header) + return header.value + return null +} + +ClientRequest.prototype.removeHeader = function (name) { + var self = this + delete self._headers[name.toLowerCase()] +} + +ClientRequest.prototype._onFinish = function () { + var self = this + + if (self._destroyed) + return + var opts = self._opts + + var headersObj = self._headers + var body = null + if (opts.method !== 'GET' && opts.method !== 'HEAD') { + if (capability.arraybuffer) { + body = toArrayBuffer(Buffer.concat(self._body)) + } else if (capability.blobConstructor) { + body = new global.Blob(self._body.map(function (buffer) { + return toArrayBuffer(buffer) + }), { + type: (headersObj['content-type'] || {}).value || '' }) + } else { + // get utf8 string + body = Buffer.concat(self._body).toString() + } + } + + // create flattened list of headers + var headersList = [] + Object.keys(headersObj).forEach(function (keyName) { + var name = headersObj[keyName].name + var value = headersObj[keyName].value + if (Array.isArray(value)) { + value.forEach(function (v) { + headersList.push([name, v]) + }) + } else { + headersList.push([name, value]) + } + }) + + if (self._mode === 'fetch') { + var signal = null + var fetchTimer = null + if (capability.abortController) { + var controller = new AbortController() + signal = controller.signal + self._fetchAbortController = controller + + if ('requestTimeout' in opts && opts.requestTimeout !== 0) { + self._fetchTimer = global.setTimeout(function () { + self.emit('requestTimeout') + if (self._fetchAbortController) + self._fetchAbortController.abort() + }, opts.requestTimeout) + } } - read() + global.fetch(self._opts.url, { + method: self._opts.method, + headers: headersList, + body: body || undefined, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin', + signal: signal + }).then(function (response) { + self._fetchResponse = response + self._connect() + }, function (reason) { + global.clearTimeout(self._fetchTimer) + if (!self._destroyed) + self.emit('error', reason) + }) } else { - self._xhr = xhr - self._pos = 0 + var xhr = self._xhr = new global.XMLHttpRequest() + try { + xhr.open(self._opts.method, self._opts.url, true) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } - self.url = xhr.responseURL - self.statusCode = xhr.status - self.statusMessage = xhr.statusText - var headers = xhr.getAllResponseHeaders().split(/\r?\n/) - headers.forEach(function (header) { - var matches = header.match(/^([^:]+):\s*(.*)/) - if (matches) { - var key = matches[1].toLowerCase() - if (key === 'set-cookie') { - if (self.headers[key] === undefined) { - self.headers[key] = [] - } - self.headers[key].push(matches[2]) - } else if (self.headers[key] !== undefined) { - self.headers[key] += ', ' + matches[2] - } else { - self.headers[key] = matches[2] - } - self.rawHeaders.push(matches[1], matches[2]) + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode.split(':')[0] + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined') + + if ('requestTimeout' in opts) { + xhr.timeout = opts.requestTimeout + xhr.ontimeout = function () { + self.emit('requestTimeout') } + } + + headersList.forEach(function (header) { + xhr.setRequestHeader(header[0], header[1]) }) - self._charset = 'x-user-defined' - if (!capability.overrideMimeType) { - var mimeType = self.rawHeaders['mime-type'] - if (mimeType) { - var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) - if (charsetMatch) { - self._charset = charsetMatch[1].toLowerCase() - } + self._response = null + xhr.onreadystatechange = function () { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress() + break } - if (!self._charset) - self._charset = 'utf-8' // best guess } + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function () { + self._onXHRProgress() + } + } + + xhr.onerror = function () { + if (self._destroyed) + return + self.emit('error', new Error('XHR error')) + } + + try { + xhr.send(body) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + } +} + +/** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ +function statusValid (xhr) { + try { + var status = xhr.status + return (status !== null && status !== 0) + } catch (e) { + return false } } -inherits(IncomingMessage, stream.Readable) +ClientRequest.prototype._onXHRProgress = function () { + var self = this -IncomingMessage.prototype._read = function () {} + if (!statusValid(self._xhr) || self._destroyed) + return -IncomingMessage.prototype._onXHRProgress = function () { + if (!self._response) + self._connect() + + self._response._onXHRProgress() +} + +ClientRequest.prototype._connect = function () { var self = this - var xhr = self._xhr + if (self._destroyed) + return - var response = null - switch (self._mode) { - case 'text:vbarray': // For IE9 - if (xhr.readyState !== rStates.DONE) - break - try { - // This fails in IE8 - response = new global.VBArray(xhr.responseBody).toArray() - } catch (e) {} - if (response !== null) { - self.push(new Buffer(response)) - break - } - // Falls through in IE8 - case 'text': - try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 - response = xhr.responseText - } catch (e) { - self._mode = 'text:vbarray' - break - } - if (response.length > self._pos) { - var newData = response.substr(self._pos) - if (self._charset === 'x-user-defined') { - var buffer = new Buffer(newData.length) - for (var i = 0; i < newData.length; i++) - buffer[i] = newData.charCodeAt(i) & 0xff + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer) + self._response.on('error', function(err) { + self.emit('error', err) + }) - self.push(buffer) - } else { - self.push(newData, self._charset) - } - self._pos = response.length - } - break - case 'arraybuffer': - if (xhr.readyState !== rStates.DONE || !xhr.response) - break - response = xhr.response - self.push(new Buffer(new Uint8Array(response))) - break - case 'moz-chunked-arraybuffer': // take whole - response = xhr.response - if (xhr.readyState !== rStates.LOADING || !response) - break - self.push(new Buffer(new Uint8Array(response))) - break - case 'ms-stream': - response = xhr.response - if (xhr.readyState !== rStates.LOADING) - break - var reader = new global.MSStreamReader() - reader.onprogress = function () { - if (reader.result.byteLength > self._pos) { - self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) - self._pos = reader.result.byteLength - } - } - reader.onload = function () { - self.push(null) - } - // reader.onerror = ??? // TODO: this - reader.readAsArrayBuffer(response) - break - } + self.emit('response', self._response) +} - // The ms-stream case handles end separately in reader.onload() - if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { - self.push(null) +ClientRequest.prototype._write = function (chunk, encoding, cb) { + var self = this + + self._body.push(chunk) + cb() +} + +ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { + var self = this + self._destroyed = true + global.clearTimeout(self._fetchTimer) + if (self._response) + self._response._destroyed = true + if (self._xhr) + self._xhr.abort() + else if (self._fetchAbortController) + self._fetchAbortController.abort() +} + +ClientRequest.prototype.end = function (data, encoding, cb) { + var self = this + if (typeof data === 'function') { + cb = data + data = undefined } + + stream.Writable.prototype.end.call(self, data, encoding, cb) } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3).Buffer, __webpack_require__(0))) +ClientRequest.prototype.flushHeaders = function () {} +ClientRequest.prototype.setTimeout = function () {} +ClientRequest.prototype.setNoDelay = function () {} +ClientRequest.prototype.setSocketKeepAlive = function () {} + +// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method +var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'via' +] + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer, __webpack_require__(0), __webpack_require__(1))) /***/ }), /* 38 */ /***/ (function(module, exports) { -/* (ignored) */ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + /***/ }), /* 39 */ +/***/ (function(module, exports) { + +/* (ignored) */ + +/***/ }), +/* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/**/ - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var Buffer = __webpack_require__(8).Buffer; -/**/ +var Buffer = __webpack_require__(9).Buffer; +var util = __webpack_require__(41); function copyBuffer(src, target, offset) { src.copy(target, offset); @@ -8391,19 +8852,35 @@ module.exports = function () { 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; + }; +} + /***/ }), -/* 40 */ +/* 41 */ +/***/ (function(module, exports) { + +/* (ignored) */ + +/***/ }), +/* 42 */ /***/ (function(module, exports, __webpack_require__) { +/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) || + (typeof self !== "undefined" && self) || + window; var apply = Function.prototype.apply; // DOM APIs, for completeness exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); + return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout); }; exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); + return new Timeout(apply.call(setInterval, scope, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { @@ -8418,7 +8895,7 @@ function Timeout(id, clearFn) { } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); + this._clearFn.call(scope, this._id); }; // Does not start the time, just sets up the members needed. @@ -8445,13 +8922,21 @@ exports._unrefActive = exports.active = function(item) { }; // setimmediate attaches itself to the global object -__webpack_require__(41); -exports.setImmediate = setImmediate; -exports.clearImmediate = clearImmediate; +__webpack_require__(43); +// On some exotic environments, it's not clear which object `setimmediate` was +// able to install onto. Search each possibility in the same order as the +// `setimmediate` library. +exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || + (typeof global !== "undefined" && global.setImmediate) || + (this && this.setImmediate); +exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || + (typeof global !== "undefined" && global.clearImmediate) || + (this && this.clearImmediate); +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) /***/ }), -/* 41 */ +/* 43 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { @@ -8644,7 +9129,7 @@ exports.clearImmediate = clearImmediate; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0), __webpack_require__(1))) /***/ }), -/* 42 */ +/* 44 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) { @@ -8718,7 +9203,75 @@ function config (name) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) /***/ }), -/* 43 */ +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(2) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function 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 Buffer +copyProps(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) +} + + +/***/ }), +/* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -8754,8 +9307,8 @@ module.exports = PassThrough; var Transform = __webpack_require__(20); /**/ -var util = __webpack_require__(5); -util.inherits = __webpack_require__(2); +var util = __webpack_require__(4); +util.inherits = __webpack_require__(5); /**/ util.inherits(PassThrough, Transform); @@ -8771,10 +9324,10 @@ PassThrough.prototype._transform = function (chunk, encoding, cb) { }; /***/ }), -/* 44 */ +/* 47 */ /***/ (function(module, exports, __webpack_require__) { -var Buffer = __webpack_require__(3).Buffer +var Buffer = __webpack_require__(2).Buffer module.exports = function (buf) { // If the buffer is backed by a Uint8Array, a faster version will work @@ -8804,7 +9357,7 @@ module.exports = function (buf) { /***/ }), -/* 45 */ +/* 48 */ /***/ (function(module, exports) { module.exports = extend @@ -8829,7 +9382,7 @@ function extend() { /***/ }), -/* 46 */ +/* 49 */ /***/ (function(module, exports) { module.exports = { @@ -8899,7 +9452,7 @@ module.exports = { /***/ }), -/* 47 */ +/* 50 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. @@ -9427,7 +9980,7 @@ function isPrimitive(arg) { } exports.isPrimitive = isPrimitive; -exports.isBuffer = __webpack_require__(48); +exports.isBuffer = __webpack_require__(51); function objectToString(o) { return Object.prototype.toString.call(o); @@ -9471,7 +10024,7 @@ exports.log = function() { * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ -exports.inherits = __webpack_require__(49); +exports.inherits = __webpack_require__(52); exports._extend = function(origin, add) { // Don't do anything if add isn't an object @@ -9492,7 +10045,7 @@ function hasOwnProperty(obj, prop) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0), __webpack_require__(1))) /***/ }), -/* 48 */ +/* 51 */ /***/ (function(module, exports) { module.exports = function isBuffer(arg) { @@ -9503,7 +10056,7 @@ module.exports = function isBuffer(arg) { } /***/ }), -/* 49 */ +/* 52 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { diff --git a/lib/eventsource.js b/lib/eventsource.js index 68d3584..64de7b1 100644 --- a/lib/eventsource.js +++ b/lib/eventsource.js @@ -10,6 +10,18 @@ var httpsOptions = [ 'rejectUnauthorized', 'secureProtocol', 'servername' ] +var bom = [239, 187, 191] +var colon = 58 +var space = 32 +var lineFeed = 10 +var carriageReturn = 13 + +function hasBom (buf) { + return bom.every(function (charCode, index) { + return buf[index] === charCode + }) +} + /** * Creates a new EventSource object * @@ -160,16 +172,21 @@ function EventSource (url, eventSourceInitDict) { // text/event-stream parser adapted from webkit's // Source/WebCore/page/EventSource.cpp - var buf = '' + var isFirst = true + var buf res.on('data', function (chunk) { - buf += chunk + buf = buf ? Buffer.concat([buf, chunk]) : chunk + if (isFirst && hasBom(buf)) { + buf = buf.slice(bom.length) + } + isFirst = false var pos = 0 var length = buf.length while (pos < length) { if (discardTrailingNewline) { - if (buf[pos] === '\n') { + if (buf[pos] === lineFeed) { ++pos } discardTrailingNewline = false @@ -181,14 +198,14 @@ function EventSource (url, eventSourceInitDict) { for (var i = pos; lineLength < 0 && i < length; ++i) { c = buf[i] - if (c === ':') { + if (c === colon) { if (fieldLength < 0) { fieldLength = i - pos } - } else if (c === '\r') { + } else if (c === carriageReturn) { discardTrailingNewline = true lineLength = i - pos - } else if (c === '\n') { + } else if (c === lineFeed) { lineLength = i - pos } } @@ -203,7 +220,7 @@ function EventSource (url, eventSourceInitDict) { } if (pos === length) { - buf = '' + buf = void 0 } else if (pos > 0) { buf = buf.slice(pos) } @@ -245,11 +262,11 @@ function EventSource (url, eventSourceInitDict) { } else if (fieldLength > 0) { var noValue = fieldLength < 0 var step = 0 - var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)) + var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString() if (noValue) { step = lineLength - } else if (buf[pos + fieldLength + 1] !== ' ') { + } else if (buf[pos + fieldLength + 1] !== space) { step = fieldLength + 1 } else { step = fieldLength + 2 @@ -257,7 +274,7 @@ function EventSource (url, eventSourceInitDict) { pos += step var valueLength = lineLength - step - var value = buf.slice(pos, pos + valueLength) + var value = buf.slice(pos, pos + valueLength).toString() if (field === 'data') { data += value + '\n' diff --git a/package.json b/package.json index 1e25f5a..59885a9 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ } ], "devDependencies": { + "buffer-from": "^1.1.1", "express": "^4.15.3", "mocha": "^3.5.3", "nyc": "^11.2.1", diff --git a/test/eventsource_test.js b/test/eventsource_test.js index ea366cc..2227760 100644 --- a/test/eventsource_test.js +++ b/test/eventsource_test.js @@ -1,5 +1,6 @@ /* eslint-disable no-new */ var EventSource = require('../lib/eventsource') +var bufferFrom = require('buffer-from') var path = require('path') var http = require('http') var https = require('https') @@ -167,6 +168,24 @@ describe('Parser', function () { }) }) + it('ignores byte-order mark', function (done) { + createServer(function (err, server) { + if (err) return done(err) + + server.on('request', function (req, res) { + res.writeHead(200, {'Content-Type': 'text/event-stream'}) + res.write('\uFEFF') + res.write('data: foo\n\n') + res.end() + }) + var es = new EventSource(server.url) + es.onmessage = function (m) { + assert.equal('foo', m.data) + server.close(done) + } + }) + }) + it('parses one one-line message in two chunks', function (done) { createServer(function (err, server) { if (err) return done(err) @@ -215,7 +234,7 @@ describe('Parser', function () { }) }) - it('parses really chopped up unicode data', function (done) { + it('parses chopped up unicode data', function (done) { createServer(function (err, server) { if (err) return done(err) @@ -237,6 +256,30 @@ describe('Parser', function () { }) }) + it('parses really chopped up unicode data', function (done) { + createServer(function (err, server) { + if (err) return done(err) + + server.on('request', function (req, res) { + const msg = bufferFrom('data: Aslak Hellesøy is the original author\n\n') + res.writeHead(200, {'Content-Type': 'text/event-stream'}) + + // Slice in the middle of a unicode sequence (ø), making sure that one data + // chunk will contain the first byte and the second chunk will get the other + res.write(msg.slice(0, 19), 'binary', function () { + res.write(msg.slice(19)) + }) + }) + + var es = new EventSource(server.url) + + es.onmessage = function (m) { + assert.equal('Aslak Hellesøy is the original author', m.data) + server.close(done) + } + }) + }) + it('accepts CRLF as separator', function (done) { createServer(function (err, server) { if (err) return done(err)