diff --git a/dist/opentmi-client.js b/dist/opentmi-client.js index 552ea94..c3f74f0 100644 --- a/dist/opentmi-client.js +++ b/dist/opentmi-client.js @@ -1,139 +1,54 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.opentmiClient = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i bytes) { end = bytes; } - - if (start >= bytes || start >= end || bytes === 0) { - return new ArrayBuffer(0); - } - - var abv = new Uint8Array(arraybuffer); - var result = new Uint8Array(end - start); - for (var i = start, ii = 0; i < end; i++, ii++) { - result[ii] = abv[i]; - } - return result.buffer; -}; - -},{}],3:[function(require,module,exports){ module.exports = require('./lib/axios'); -},{"./lib/axios":5}],4:[function(require,module,exports){ -(function (process){ +},{"./lib/axios":3}],2:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); var settle = require('./../core/settle'); +var cookies = require('./../helpers/cookies'); var buildURL = require('./../helpers/buildURL'); +var buildFullPath = require('../core/buildFullPath'); var parseHeaders = require('./../helpers/parseHeaders'); var isURLSameOrigin = require('./../helpers/isURLSameOrigin'); var createError = require('../core/createError'); -var btoa = (typeof window !== 'undefined' && window.btoa && window.btoa.bind(window)) || require('./../helpers/btoa'); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; + var responseType = config.responseType; if (utils.isFormData(requestData)) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); - var loadEvent = 'onreadystatechange'; - var xDomain = false; - - // For IE 8/9 CORS support - // Only supports POST and GET calls and doesn't returns the response headers. - // DON'T do this for testing b/c XMLHttpRequest is mocked, not XDomainRequest. - if (process.env.NODE_ENV !== 'test' && - typeof window !== 'undefined' && - window.XDomainRequest && !('withCredentials' in request) && - !isURLSameOrigin(config.url)) { - request = new window.XDomainRequest(); - loadEvent = 'onload'; - xDomain = true; - request.onprogress = function handleProgress() {}; - request.ontimeout = function handleTimeout() {}; - } // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; - var password = config.auth.password || ''; + var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } - request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true); + var fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; - // Listen for ready state - request[loadEvent] = function handleLoad() { - if (!request || (request.readyState !== 4 && !xDomain)) { + function onloadend() { + if (!request) { return; } - - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } - // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; + var responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; var response = { data: responseData, - // IE sends 1223 instead of 204 (https://github.com/axios/axios/issues/201) - status: request.status === 1223 ? 204 : request.status, - statusText: request.status === 1223 ? 'No Content' : request.statusText, + status: request.status, + statusText: request.statusText, headers: responseHeaders, config: config, request: request @@ -141,6 +56,41 @@ module.exports = function xhrAdapter(config) { settle(resolve, reject, response); + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(createError('Request aborted', config, 'ECONNABORTED', request)); + // Clean up request request = null; }; @@ -157,7 +107,14 @@ module.exports = function xhrAdapter(config) { // Handle timeout request.ontimeout = function handleTimeout() { - reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', + var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(createError( + timeoutErrorMessage, + config, + config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', request)); // Clean up request @@ -168,12 +125,10 @@ module.exports = function xhrAdapter(config) { // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { - var cookies = require('./../helpers/cookies'); - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ? - cookies.read(config.xsrfCookieName) : - undefined; + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; @@ -194,21 +149,13 @@ module.exports = function xhrAdapter(config) { } // Add withCredentials to request if needed - if (config.withCredentials) { - request.withCredentials = true; + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; } // Add responseType to request if needed - if (config.responseType) { - try { - request.responseType = config.responseType; - } catch (e) { - // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. - // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. - if (config.responseType !== 'json') { - throw e; - } - } + if (responseType && responseType !== 'json') { + request.responseType = config.responseType; } // Handle progress if needed @@ -235,7 +182,7 @@ module.exports = function xhrAdapter(config) { }); } - if (requestData === undefined) { + if (!requestData) { requestData = null; } @@ -244,13 +191,13 @@ module.exports = function xhrAdapter(config) { }); }; -}).call(this,require('_process')) -},{"../core/createError":11,"./../core/settle":14,"./../helpers/btoa":18,"./../helpers/buildURL":19,"./../helpers/cookies":21,"./../helpers/isURLSameOrigin":23,"./../helpers/parseHeaders":25,"./../utils":27,"_process":69}],5:[function(require,module,exports){ +},{"../core/buildFullPath":9,"../core/createError":10,"./../core/settle":14,"./../helpers/buildURL":18,"./../helpers/cookies":20,"./../helpers/isURLSameOrigin":23,"./../helpers/parseHeaders":25,"./../utils":28}],3:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var bind = require('./helpers/bind'); var Axios = require('./core/Axios'); +var mergeConfig = require('./core/mergeConfig'); var defaults = require('./defaults'); /** @@ -280,7 +227,7 @@ axios.Axios = Axios; // Factory for creating new instances axios.create = function create(instanceConfig) { - return createInstance(utils.merge(defaults, instanceConfig)); + return createInstance(mergeConfig(axios.defaults, instanceConfig)); }; // Expose Cancel & CancelToken @@ -294,12 +241,15 @@ axios.all = function all(promises) { }; axios.spread = require('./helpers/spread'); +// Expose isAxiosError +axios.isAxiosError = require('./helpers/isAxiosError'); + module.exports = axios; // Allow use of default import syntax in TypeScript module.exports.default = axios; -},{"./cancel/Cancel":6,"./cancel/CancelToken":7,"./cancel/isCancel":8,"./core/Axios":9,"./defaults":16,"./helpers/bind":17,"./helpers/spread":26,"./utils":27}],6:[function(require,module,exports){ +},{"./cancel/Cancel":4,"./cancel/CancelToken":5,"./cancel/isCancel":6,"./core/Axios":7,"./core/mergeConfig":13,"./defaults":16,"./helpers/bind":17,"./helpers/isAxiosError":22,"./helpers/spread":26,"./utils":28}],4:[function(require,module,exports){ 'use strict'; /** @@ -320,7 +270,7 @@ Cancel.prototype.__CANCEL__ = true; module.exports = Cancel; -},{}],7:[function(require,module,exports){ +},{}],5:[function(require,module,exports){ 'use strict'; var Cancel = require('./Cancel'); @@ -379,21 +329,24 @@ CancelToken.source = function source() { module.exports = CancelToken; -},{"./Cancel":6}],8:[function(require,module,exports){ +},{"./Cancel":4}],6:[function(require,module,exports){ 'use strict'; module.exports = function isCancel(value) { return !!(value && value.__CANCEL__); }; -},{}],9:[function(require,module,exports){ +},{}],7:[function(require,module,exports){ 'use strict'; -var defaults = require('./../defaults'); var utils = require('./../utils'); +var buildURL = require('../helpers/buildURL'); var InterceptorManager = require('./InterceptorManager'); var dispatchRequest = require('./dispatchRequest'); +var mergeConfig = require('./mergeConfig'); +var validator = require('../helpers/validator'); +var validators = validator.validators; /** * Create a new instance of Axios * @@ -416,40 +369,106 @@ Axios.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { - config = utils.merge({ - url: arguments[0] - }, arguments[1]); + config = arguments[1] || {}; + config.url = arguments[0]; + } else { + config = config || {}; } - config = utils.merge(defaults, {method: 'get'}, this.defaults, config); - config.method = config.method.toLowerCase(); + config = mergeConfig(this.defaults, config); - // Hook up interceptors middleware - var chain = [dispatchRequest, undefined]; - var promise = Promise.resolve(config); + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; + } + + var transitional = config.transitional; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'), + forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'), + clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0') + }, false); + } + // filter out skipped interceptors + var requestInterceptorChain = []; + var synchronousRequestInterceptors = true; this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - chain.unshift(interceptor.fulfilled, interceptor.rejected); + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); }); + var responseInterceptorChain = []; this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - chain.push(interceptor.fulfilled, interceptor.rejected); + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); }); - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); + var promise; + + if (!synchronousRequestInterceptors) { + var chain = [dispatchRequest, undefined]; + + Array.prototype.unshift.apply(chain, requestInterceptorChain); + chain = chain.concat(responseInterceptorChain); + + promise = Promise.resolve(config); + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } + + return promise; + } + + + var newConfig = config; + while (requestInterceptorChain.length) { + var onFulfilled = requestInterceptorChain.shift(); + var onRejected = requestInterceptorChain.shift(); + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected(error); + break; + } + } + + try { + promise = dispatchRequest(newConfig); + } catch (error) { + return Promise.reject(error); + } + + while (responseInterceptorChain.length) { + promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); } return promise; }; +Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); +}; + // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { - return this.request(utils.merge(config || {}, { + return this.request(mergeConfig(config || {}, { method: method, - url: url + url: url, + data: (config || {}).data })); }; }); @@ -457,7 +476,7 @@ utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { - return this.request(utils.merge(config || {}, { + return this.request(mergeConfig(config || {}, { method: method, url: url, data: data @@ -467,7 +486,7 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { module.exports = Axios; -},{"./../defaults":16,"./../utils":27,"./InterceptorManager":10,"./dispatchRequest":12}],10:[function(require,module,exports){ +},{"../helpers/buildURL":18,"../helpers/validator":27,"./../utils":28,"./InterceptorManager":8,"./dispatchRequest":11,"./mergeConfig":13}],8:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); @@ -484,10 +503,12 @@ function InterceptorManager() { * * @return {Number} An ID used to remove interceptor later */ -InterceptorManager.prototype.use = function use(fulfilled, rejected) { +InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { this.handlers.push({ fulfilled: fulfilled, - rejected: rejected + rejected: rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null }); return this.handlers.length - 1; }; @@ -521,7 +542,29 @@ InterceptorManager.prototype.forEach = function forEach(fn) { module.exports = InterceptorManager; -},{"./../utils":27}],11:[function(require,module,exports){ +},{"./../utils":28}],9:[function(require,module,exports){ +'use strict'; + +var isAbsoluteURL = require('../helpers/isAbsoluteURL'); +var combineURLs = require('../helpers/combineURLs'); + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path + */ +module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +}; + +},{"../helpers/combineURLs":19,"../helpers/isAbsoluteURL":21}],10:[function(require,module,exports){ 'use strict'; var enhanceError = require('./enhanceError'); @@ -541,15 +584,13 @@ module.exports = function createError(message, config, code, request, response) return enhanceError(error, config, code, request, response); }; -},{"./enhanceError":13}],12:[function(require,module,exports){ +},{"./enhanceError":12}],11:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); var transformData = require('./transformData'); var isCancel = require('../cancel/isCancel'); var defaults = require('../defaults'); -var isAbsoluteURL = require('./../helpers/isAbsoluteURL'); -var combineURLs = require('./../helpers/combineURLs'); /** * Throws a `Cancel` if cancellation has been requested. @@ -569,16 +610,12 @@ function throwIfCancellationRequested(config) { module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); - // Support baseURL config - if (config.baseURL && !isAbsoluteURL(config.url)) { - config.url = combineURLs(config.baseURL, config.url); - } - // Ensure headers exist config.headers = config.headers || {}; // Transform request data - config.data = transformData( + config.data = transformData.call( + config, config.data, config.headers, config.transformRequest @@ -588,7 +625,7 @@ module.exports = function dispatchRequest(config) { config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, - config.headers || {} + config.headers ); utils.forEach( @@ -604,7 +641,8 @@ module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); // Transform response data - response.data = transformData( + response.data = transformData.call( + config, response.data, response.headers, config.transformResponse @@ -617,7 +655,8 @@ module.exports = function dispatchRequest(config) { // Transform response data if (reason && reason.response) { - reason.response.data = transformData( + reason.response.data = transformData.call( + config, reason.response.data, reason.response.headers, config.transformResponse @@ -629,7 +668,7 @@ module.exports = function dispatchRequest(config) { }); }; -},{"../cancel/isCancel":8,"../defaults":16,"./../helpers/combineURLs":20,"./../helpers/isAbsoluteURL":22,"./../utils":27,"./transformData":15}],13:[function(require,module,exports){ +},{"../cancel/isCancel":6,"../defaults":16,"./../utils":28,"./transformData":15}],12:[function(require,module,exports){ 'use strict'; /** @@ -647,12 +686,122 @@ module.exports = function enhanceError(error, config, code, request, response) { if (code) { error.code = code; } + error.request = request; error.response = response; + error.isAxiosError = true; + + error.toJSON = function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code + }; + }; return error; }; -},{}],14:[function(require,module,exports){ +},{}],13:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils'); + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 + */ +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; + + var valueFromConfig2Keys = ['url', 'method', 'data']; + var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; + var defaultToConfig2Keys = [ + 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', + 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', + 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', + 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', + 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' + ]; + var directMergeKeys = ['validateStatus']; + + function getMergedValue(target, source) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge(target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + } + + utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } + }); + + utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); + + utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); + + utils.forEach(directMergeKeys, function merge(prop) { + if (prop in config2) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (prop in config1) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); + + var axiosKeys = valueFromConfig2Keys + .concat(mergeDeepPropertiesKeys) + .concat(defaultToConfig2Keys) + .concat(directMergeKeys); + + var otherKeys = Object + .keys(config1) + .concat(Object.keys(config2)) + .filter(function filterAxiosKeys(key) { + return axiosKeys.indexOf(key) === -1; + }); + + utils.forEach(otherKeys, mergeDeepProperties); + + return config; +}; + +},{"../utils":28}],14:[function(require,module,exports){ 'use strict'; var createError = require('./createError'); @@ -666,7 +815,6 @@ var createError = require('./createError'); */ module.exports = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; - // Note: status is not exposed by XDomainRequest if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { @@ -680,10 +828,11 @@ module.exports = function settle(resolve, reject, response) { } }; -},{"./createError":11}],15:[function(require,module,exports){ +},{"./createError":10}],15:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); +var defaults = require('./../defaults'); /** * Transform the data for a request or a response @@ -694,20 +843,22 @@ var utils = require('./../utils'); * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { + var context = this || defaults; /*eslint no-param-reassign:0*/ utils.forEach(fns, function transform(fn) { - data = fn(data, headers); + data = fn.call(context, data, headers); }); return data; }; -},{"./../utils":27}],16:[function(require,module,exports){ +},{"./../defaults":16,"./../utils":28}],16:[function(require,module,exports){ (function (process){ 'use strict'; var utils = require('./utils'); var normalizeHeaderName = require('./helpers/normalizeHeaderName'); +var enhanceError = require('./core/enhanceError'); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' @@ -724,7 +875,7 @@ function getDefaultAdapter() { if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = require('./adapters/xhr'); - } else if (typeof process !== 'undefined') { + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = require('./adapters/http'); } @@ -732,10 +883,19 @@ function getDefaultAdapter() { } var defaults = { + + transitional: { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false + }, + adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); + if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || @@ -752,20 +912,32 @@ var defaults = { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } - if (utils.isObject(data)) { - setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); + if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) { + setContentTypeIfUnset(headers, 'application/json'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { - /*eslint no-param-reassign:0*/ - if (typeof data === 'string') { + var transitional = this.transitional; + var silentJSONParsing = transitional && transitional.silentJSONParsing; + var forcedJSONParsing = transitional && transitional.forcedJSONParsing; + var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; + + if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { try { - data = JSON.parse(data); - } catch (e) { /* Ignore */ } + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw enhanceError(e, this, 'E_JSON_PARSE'); + } + throw e; + } + } } + return data; }], @@ -779,6 +951,7 @@ var defaults = { xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, + maxBodyLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; @@ -802,7 +975,7 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { module.exports = defaults; }).call(this,require('_process')) -},{"./adapters/http":4,"./adapters/xhr":4,"./helpers/normalizeHeaderName":24,"./utils":27,"_process":69}],17:[function(require,module,exports){ +},{"./adapters/http":2,"./adapters/xhr":2,"./core/enhanceError":12,"./helpers/normalizeHeaderName":24,"./utils":28,"_process":64}],17:[function(require,module,exports){ 'use strict'; module.exports = function bind(fn, thisArg) { @@ -818,49 +991,10 @@ module.exports = function bind(fn, thisArg) { },{}],18:[function(require,module,exports){ 'use strict'; -// btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js - -var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - -function E() { - this.message = 'String contains an invalid character'; -} -E.prototype = new Error; -E.prototype.code = 5; -E.prototype.name = 'InvalidCharacterError'; - -function btoa(input) { - var str = String(input); - var output = ''; - for ( - // initialize result and counter - var block, charCode, idx = 0, map = chars; - // if the next str index does not exist: - // change the mapping table to "=" - // check if d has no fractional digits - str.charAt(idx | 0) || (map = '=', idx % 1); - // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 - output += map.charAt(63 & block >> 8 - idx % 1 * 8) - ) { - charCode = str.charCodeAt(idx += 3 / 4); - if (charCode > 0xFF) { - throw new E(); - } - block = block << 8 | charCode; - } - return output; -} - -module.exports = btoa; - -},{}],19:[function(require,module,exports){ -'use strict'; - var utils = require('./../utils'); function encode(val) { return encodeURIComponent(val). - replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). @@ -915,13 +1049,18 @@ module.exports = function buildURL(url, params, paramsSerializer) { } if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; -},{"./../utils":27}],20:[function(require,module,exports){ +},{"./../utils":28}],19:[function(require,module,exports){ 'use strict'; /** @@ -937,7 +1076,7 @@ module.exports = function combineURLs(baseURL, relativeURL) { : baseURL; }; -},{}],21:[function(require,module,exports){ +},{}],20:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); @@ -946,53 +1085,53 @@ module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie - (function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); - if (utils.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } - if (utils.isString(path)) { - cookie.push('path=' + path); - } + if (utils.isString(path)) { + cookie.push('path=' + path); + } - if (utils.isString(domain)) { - cookie.push('domain=' + domain); - } + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } - if (secure === true) { - cookie.push('secure'); - } + if (secure === true) { + cookie.push('secure'); + } - document.cookie = cookie.join('; '); - }, + document.cookie = cookie.join('; '); + }, - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - })() : + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); + } + }; + })() : // Non standard browser env (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { return null; }, - remove: function remove() {} - }; - })() + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} + }; + })() ); -},{"./../utils":27}],22:[function(require,module,exports){ +},{"./../utils":28}],21:[function(require,module,exports){ 'use strict'; /** @@ -1008,6 +1147,19 @@ module.exports = function isAbsoluteURL(url) { return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; +},{}],22:[function(require,module,exports){ +'use strict'; + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +module.exports = function isAxiosError(payload) { + return (typeof payload === 'object') && (payload.isAxiosError === true); +}; + },{}],23:[function(require,module,exports){ 'use strict'; @@ -1018,67 +1170,67 @@ module.exports = ( // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. - (function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; - /** + /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ - function resolveURL(url) { - var href = url; + function resolveURL(url) { + var href = url; - if (msie) { + if (msie) { // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } - urlParsingNode.setAttribute('href', href); + urlParsingNode.setAttribute('href', href); - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') ? - urlParsingNode.pathname : - '/' + urlParsingNode.pathname - }; - } + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } - originURL = resolveURL(window.location.href); + originURL = resolveURL(window.location.href); - /** + /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ - return function isURLSameOrigin(requestURL) { - var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; - return (parsed.protocol === originURL.protocol && + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); - }; - })() : + }; + })() : // Non standard browser envs (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - })() + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })() ); -},{"./../utils":27}],24:[function(require,module,exports){ +},{"./../utils":28}],24:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -1092,7 +1244,7 @@ module.exports = function normalizeHeaderName(headers, normalizedName) { }); }; -},{"../utils":27}],25:[function(require,module,exports){ +},{"../utils":28}],25:[function(require,module,exports){ 'use strict'; var utils = require('./../utils'); @@ -1147,7 +1299,7 @@ module.exports = function parseHeaders(headers) { return parsed; }; -},{"./../utils":27}],26:[function(require,module,exports){ +},{"./../utils":28}],26:[function(require,module,exports){ 'use strict'; /** @@ -1179,10 +1331,114 @@ module.exports = function spread(callback) { },{}],27:[function(require,module,exports){ 'use strict'; -var bind = require('./helpers/bind'); -var isBuffer = require('is-buffer'); +var pkg = require('./../../package.json'); -/*global toString:true*/ +var validators = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { + validators[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +var deprecatedWarnings = {}; +var currentVerArr = pkg.version.split('.'); + +/** + * Compare package versions + * @param {string} version + * @param {string?} thanVersion + * @returns {boolean} + */ +function isOlderVersion(version, thanVersion) { + var pkgVersionArr = thanVersion ? thanVersion.split('.') : currentVerArr; + var destVer = version.split('.'); + for (var i = 0; i < 3; i++) { + if (pkgVersionArr[i] > destVer[i]) { + return true; + } else if (pkgVersionArr[i] < destVer[i]) { + return false; + } + } + return false; +} + +/** + * Transitional option validator + * @param {function|boolean?} validator + * @param {string?} version + * @param {string} message + * @returns {function} + */ +validators.transitional = function transitional(validator, version, message) { + var isDeprecated = version && isOlderVersion(version); + + function formatMessage(opt, desc) { + return '[Axios v' + pkg.version + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return function(value, opt, opts) { + if (validator === false) { + throw new Error(formatMessage(opt, ' has been removed in ' + version)); + } + + if (isDeprecated && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +/** + * Assert object's properties type + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new TypeError('options must be an object'); + } + var keys = Object.keys(options); + var i = keys.length; + while (i-- > 0) { + var opt = keys[i]; + var validator = schema[opt]; + if (validator) { + var value = options[opt]; + var result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new TypeError('option ' + opt + ' must be ' + result); + } + continue; + } + if (allowUnknown !== true) { + throw Error('Unknown option ' + opt); + } + } +} + +module.exports = { + isOlderVersion: isOlderVersion, + assertOptions: assertOptions, + validators: validators +}; + +},{"./../../package.json":29}],28:[function(require,module,exports){ +'use strict'; + +var bind = require('./helpers/bind'); // utils is a library of generic helper functions non-specific to axios @@ -1198,6 +1454,27 @@ function isArray(val) { return toString.call(val) === '[object Array]'; } +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} + +/** + * Determine if a value is a Buffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +} + /** * Determine if a value is an ArrayBuffer * @@ -1255,23 +1532,28 @@ function isNumber(val) { } /** - * Determine if a value is undefined + * Determine if a value is an Object * * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false + * @returns {boolean} True if value is an Object, otherwise false */ -function isUndefined(val) { - return typeof val === 'undefined'; +function isObject(val) { + return val !== null && typeof val === 'object'; } /** - * Determine if a value is an Object + * Determine if a value is a plain Object * * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false + * @return {boolean} True if value is a plain Object, otherwise false */ -function isObject(val) { - return val !== null && typeof val === 'object'; +function isPlainObject(val) { + if (toString.call(val) !== '[object Object]') { + return false; + } + + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; } /** @@ -1341,7 +1623,7 @@ function isURLSearchParams(val) { * @returns {String} The String freed of excess whitespace */ function trim(str) { - return str.replace(/^\s*/, '').replace(/\s*$/, ''); + return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); } /** @@ -1356,9 +1638,13 @@ function trim(str) { * * react-native: * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { - if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { return false; } return ( @@ -1426,8 +1712,12 @@ function forEach(obj, fn) { function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { - if (typeof result[key] === 'object' && typeof val === 'object') { + if (isPlainObject(result[key]) && isPlainObject(val)) { result[key] = merge(result[key], val); + } else if (isPlainObject(val)) { + result[key] = merge({}, val); + } else if (isArray(val)) { + result[key] = val.slice(); } else { result[key] = val; } @@ -1458,6 +1748,19 @@ function extend(a, b, thisArg) { return a; } +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * @return {string} content value without BOM + */ +function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} + module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, @@ -1467,6 +1770,7 @@ module.exports = { isString: isString, isNumber: isNumber, isObject: isObject, + isPlainObject: isPlainObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, @@ -1478,10 +1782,127 @@ module.exports = { forEach: forEach, merge: merge, extend: extend, - trim: trim -}; + trim: trim, + stripBOM: stripBOM +}; + +},{"./helpers/bind":17}],29:[function(require,module,exports){ +module.exports={ + "_args": [ + [ + "axios@0.21.3", + "/Users/jussiva/git/github/opentmi/opentmi-jsclient" + ] + ], + "_from": "axios@0.21.3", + "_id": "axios@0.21.3", + "_inBundle": false, + "_integrity": "sha512-JtoZ3Ndke/+Iwt5n+BgSli/3idTvpt5OjKyoCmz4LX5+lPiY5l7C1colYezhlxThjNa/NhngCUWZSZFypIFuaA==", + "_location": "/axios", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "axios@0.21.3", + "name": "axios", + "escapedName": "axios", + "rawSpec": "0.21.3", + "saveSpec": null, + "fetchSpec": "0.21.3" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/axios/-/axios-0.21.3.tgz", + "_spec": "0.21.3", + "_where": "/Users/jussiva/git/github/opentmi/opentmi-jsclient", + "author": { + "name": "Matt Zabriskie" + }, + "browser": { + "./lib/adapters/http.js": "./lib/adapters/xhr.js" + }, + "bugs": { + "url": "https://github.com/axios/axios/issues" + }, + "bundlesize": [ + { + "path": "./dist/axios.min.js", + "threshold": "5kB" + } + ], + "dependencies": { + "follow-redirects": "^1.14.0" + }, + "description": "Promise based HTTP client for the browser and node.js", + "devDependencies": { + "coveralls": "^3.0.0", + "es6-promise": "^4.2.4", + "grunt": "^1.3.0", + "grunt-banner": "^0.6.0", + "grunt-cli": "^1.2.0", + "grunt-contrib-clean": "^1.1.0", + "grunt-contrib-watch": "^1.0.0", + "grunt-eslint": "^23.0.0", + "grunt-karma": "^4.0.0", + "grunt-mocha-test": "^0.13.3", + "grunt-ts": "^6.0.0-beta.19", + "grunt-webpack": "^4.0.2", + "istanbul-instrumenter-loader": "^1.0.0", + "jasmine-core": "^2.4.1", + "karma": "^6.3.2", + "karma-chrome-launcher": "^3.1.0", + "karma-firefox-launcher": "^2.1.0", + "karma-jasmine": "^1.1.1", + "karma-jasmine-ajax": "^0.1.13", + "karma-safari-launcher": "^1.0.0", + "karma-sauce-launcher": "^4.3.6", + "karma-sinon": "^1.0.5", + "karma-sourcemap-loader": "^0.3.8", + "karma-webpack": "^4.0.2", + "load-grunt-tasks": "^3.5.2", + "minimist": "^1.2.0", + "mocha": "^8.2.1", + "sinon": "^4.5.0", + "terser-webpack-plugin": "^4.2.3", + "typescript": "^4.0.5", + "url-search-params": "^0.10.0", + "webpack": "^4.44.2", + "webpack-dev-server": "^3.11.0" + }, + "homepage": "https://axios-http.com", + "jsdelivr": "dist/axios.min.js", + "keywords": [ + "xhr", + "http", + "ajax", + "promise", + "node" + ], + "license": "MIT", + "main": "index.js", + "name": "axios", + "repository": { + "type": "git", + "url": "git+https://github.com/axios/axios.git" + }, + "scripts": { + "build": "NODE_ENV=production grunt build", + "coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js", + "examples": "node ./examples/server.js", + "fix": "eslint --fix lib/**/*.js", + "postversion": "git push && git push --tags", + "preversion": "npm test", + "start": "node ./sandbox/server.js", + "test": "grunt test", + "version": "npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json" + }, + "typings": "./index.d.ts", + "unpkg": "dist/axios.min.js", + "version": "0.21.3" +} -},{"./helpers/bind":17,"is-buffer":60}],28:[function(require,module,exports){ +},{}],30:[function(require,module,exports){ /** * Expose `Backoff`. @@ -1568,7 +1989,7 @@ Backoff.prototype.setJitter = function(jitter){ }; -},{}],29:[function(require,module,exports){ +},{}],31:[function(require,module,exports){ /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer @@ -1576,17 +1997,9 @@ Backoff.prototype.setJitter = function(jitter){ * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ -(function(){ +(function(chars){ "use strict"; - var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - // Use a lookup table to find the index. - var lookup = new Uint8Array(256); - for (var i = 0; i < chars.length; i++) { - lookup[chars.charCodeAt(i)] = i; - } - exports.encode = function(arraybuffer) { var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ""; @@ -1623,10 +2036,10 @@ Backoff.prototype.setJitter = function(jitter){ bytes = new Uint8Array(arraybuffer); for (i = 0; i < len; i+=4) { - encoded1 = lookup[base64.charCodeAt(i)]; - encoded2 = lookup[base64.charCodeAt(i+1)]; - encoded3 = lookup[base64.charCodeAt(i+2)]; - encoded4 = lookup[base64.charCodeAt(i+3)]; + encoded1 = chars.indexOf(base64[i]); + encoded2 = chars.indexOf(base64[i+1]); + encoded3 = chars.indexOf(base64[i+2]); + encoded4 = chars.indexOf(base64[i+3]); bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); @@ -1635,9 +2048,9 @@ Backoff.prototype.setJitter = function(jitter){ return arraybuffer; }; -})(); +})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); -},{}],30:[function(require,module,exports){ +},{}],32:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -1790,109 +2203,7 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],31:[function(require,module,exports){ -/** - * Create a blob builder even when vendor prefixes exist - */ - -var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : - typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder : - typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : - typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : - false; - -/** - * Check if Blob constructor is supported - */ - -var blobSupported = (function() { - try { - var a = new Blob(['hi']); - return a.size === 2; - } catch(e) { - return false; - } -})(); - -/** - * Check if Blob constructor supports ArrayBufferViews - * Fails in Safari 6, so we need to map to ArrayBuffers there. - */ - -var blobSupportsArrayBufferView = blobSupported && (function() { - try { - var b = new Blob([new Uint8Array([1,2])]); - return b.size === 2; - } catch(e) { - return false; - } -})(); - -/** - * Check if BlobBuilder is supported - */ - -var blobBuilderSupported = BlobBuilder - && BlobBuilder.prototype.append - && BlobBuilder.prototype.getBlob; - -/** - * Helper function that maps ArrayBufferViews to ArrayBuffers - * Used by BlobBuilder constructor and old browsers that didn't - * support it in the Blob constructor. - */ - -function mapArrayBufferViews(ary) { - return ary.map(function(chunk) { - if (chunk.buffer instanceof ArrayBuffer) { - var buf = chunk.buffer; - - // if this is a subarray, make a copy so we only - // include the subarray region from the underlying buffer - if (chunk.byteLength !== buf.byteLength) { - var copy = new Uint8Array(chunk.byteLength); - copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); - buf = copy.buffer; - } - - return buf; - } - - return chunk; - }); -} - -function BlobBuilderConstructor(ary, options) { - options = options || {}; - - var bb = new BlobBuilder(); - mapArrayBufferViews(ary).forEach(function(part) { - bb.append(part); - }); - - return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); -}; - -function BlobConstructor(ary, options) { - return new Blob(mapArrayBufferViews(ary), options || {}); -}; - -if (typeof Blob !== 'undefined') { - BlobBuilderConstructor.prototype = Blob.prototype; - BlobConstructor.prototype = Blob.prototype; -} - -module.exports = (function() { - if (blobSupported) { - return blobSupportsArrayBufferView ? Blob : BlobConstructor; - } else if (blobBuilderSupported) { - return BlobBuilderConstructor; - } else { - return undefined; - } -})(); - -},{}],32:[function(require,module,exports){ +},{}],33:[function(require,module,exports){ (function (process,global,setImmediate){ /* @preserve * The MIT License (MIT) @@ -1919,7 +2230,7 @@ module.exports = (function() { * */ /** - * bluebird build version 3.5.2 + * bluebird build version 3.7.2 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { @@ -2112,7 +2378,7 @@ Async.prototype._reset = function () { module.exports = Async; module.exports.firstLineError = firstLineError; -},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ +},{"./queue":26,"./schedule":29}],3:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { var calledBind = false; @@ -2567,8 +2833,8 @@ return Context; },{}],9:[function(_dereq_,module,exports){ "use strict"; -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; +module.exports = function(Promise, Context, + enableAsyncHooks, disableAsyncHooks) { var async = Promise._async; var Warning = _dereq_("./errors").Warning; var util = _dereq_("./util"); @@ -2598,6 +2864,34 @@ var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); +var deferUnhandledRejectionCheck; +(function() { + var promises = []; + + function unhandledRejectionCheck() { + for (var i = 0; i < promises.length; ++i) { + promises[i]._notifyUnhandledRejection(); + } + unhandledRejectionClear(); + } + + function unhandledRejectionClear() { + promises.length = 0; + } + + deferUnhandledRejectionCheck = function(promise) { + promises.push(promise); + setTimeout(unhandledRejectionCheck, 1); + }; + + es5.defineProperty(Promise, "_unhandledRejectionCheck", { + value: unhandledRejectionCheck + }); + es5.defineProperty(Promise, "_unhandledRejectionClear", { + value: unhandledRejectionClear + }); +})(); + Promise.prototype.suppressUnhandledRejections = function() { var target = this._target(); target._bitField = ((target._bitField & (~1048576)) | @@ -2607,10 +2901,7 @@ Promise.prototype.suppressUnhandledRejections = function() { Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 524288) !== 0) return; this._setRejectionIsUnhandled(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); + deferUnhandledRejectionCheck(this); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { @@ -2668,19 +2959,13 @@ Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { }; Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; + var context = Promise._getContext(); + possiblyUnhandledRejection = util.contextBind(context, fn); }; Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; + var context = Promise._getContext(); + unhandledRejectionHandled = util.contextBind(context, fn); }; var disableLongStackTraces = function() {}; @@ -2701,14 +2986,12 @@ Promise.longStackTraces = function () { Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; Context.deactivateLongStackTraces(); - async.enableTrampoline(); config.longStackTraces = false; }; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); } }; @@ -2716,43 +2999,85 @@ Promise.hasLongStackTraces = function () { return config.longStackTraces && longStackTracesIsSupported(); }; + +var legacyHandlers = { + unhandledrejection: { + before: function() { + var ret = util.global.onunhandledrejection; + util.global.onunhandledrejection = null; + return ret; + }, + after: function(fn) { + util.global.onunhandledrejection = fn; + } + }, + rejectionhandled: { + before: function() { + var ret = util.global.onrejectionhandled; + util.global.onrejectionhandled = null; + return ret; + }, + after: function(fn) { + util.global.onrejectionhandled = fn; + } + } +}; + var fireDomEvent = (function() { + var dispatch = function(legacy, e) { + if (legacy) { + var fn; + try { + fn = legacy.before(); + return !util.global.dispatchEvent(e); + } finally { + legacy.after(fn); + } + } else { + return !util.global.dispatchEvent(e); + } + }; try { if (typeof CustomEvent === "function") { var event = new CustomEvent("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { + name = name.toLowerCase(); var eventData = { detail: event, cancelable: true }; + var domEvent = new CustomEvent(name, eventData); + es5.defineProperty( + domEvent, "promise", {value: event.promise}); es5.defineProperty( - eventData, "promise", {value: event.promise}); - es5.defineProperty(eventData, "reason", {value: event.reason}); - var domEvent = new CustomEvent(name.toLowerCase(), eventData); - return !util.global.dispatchEvent(domEvent); + domEvent, "reason", {value: event.reason}); + + return dispatch(legacyHandlers[name], domEvent); }; } else if (typeof Event === "function") { var event = new Event("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { + name = name.toLowerCase(); + var domEvent = new Event(name, { cancelable: true }); domEvent.detail = event; es5.defineProperty(domEvent, "promise", {value: event.promise}); es5.defineProperty(domEvent, "reason", {value: event.reason}); - return !util.global.dispatchEvent(domEvent); + return dispatch(legacyHandlers[name], domEvent); }; } else { var event = document.createEvent("CustomEvent"); event.initCustomEvent("testingtheevent", false, true, {}); util.global.dispatchEvent(event); return function(name, event) { + name = name.toLowerCase(); var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, + domEvent.initCustomEvent(name, false, true, event); - return !util.global.dispatchEvent(domEvent); + return dispatch(legacyHandlers[name], domEvent); }; } } catch (e) {} @@ -2870,6 +3195,18 @@ Promise.config = function(opts) { Promise.prototype._fireEvent = defaultFireEvent; } } + if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) { + var prev = config.asyncHooks; + var cur = !!opts.asyncHooks; + if (prev !== cur) { + config.asyncHooks = cur; + if (cur) { + enableAsyncHooks(); + } else { + disableAsyncHooks(); + } + } + } return Promise; }; @@ -3257,8 +3594,8 @@ function parseLineInfo(line) { function setBounds(firstLineError, lastLineError) { if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); + var firstStackLines = (firstLineError.stack || "").split("\n"); + var lastStackLines = (lastLineError.stack || "").split("\n"); var firstIndex = -1; var lastIndex = -1; var firstFileName; @@ -3467,12 +3804,16 @@ var config = { warnings: warnings, longStackTraces: false, cancellation: false, - monitoring: false + monitoring: false, + asyncHooks: false }; if (longStackTraces) Promise.longStackTraces(); return { + asyncHooks: function() { + return config.asyncHooks; + }, longStackTraces: function() { return config.longStackTraces; }, @@ -4171,8 +4512,7 @@ Promise.spawn = function (generatorFunction) { },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; @@ -4318,10 +4658,8 @@ Promise.join = function () { if (!ret._isFateSealed()) { if (holder.asyncNeeded) { - var domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, holder.fn); - } + var context = Promise._getContext(); + holder.fn = util.contextBind(context, holder.fn); } ret._setAsyncGuaranteed(); ret._setOnCancel(holder); @@ -4346,7 +4684,6 @@ module.exports = function(Promise, tryConvertToPromise, INTERNAL, debug) { -var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; @@ -4355,8 +4692,8 @@ var async = Promise._async; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); - var domain = getDomain(); - this._callback = domain === null ? fn : util.domainBind(domain, fn); + var context = Promise._getContext(); + this._callback = util.contextBind(context, fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; @@ -4364,6 +4701,14 @@ function MappingPromiseArray(promises, fn, limit, _filter) { this._inFlight = 0; this._queue = []; async.invoke(this._asyncInit, this, undefined); + if (util.isArray(promises)) { + for (var i = 0; i < promises.length; ++i) { + var maybePromise = promises[i]; + if (maybePromise instanceof Promise) { + maybePromise.suppressUnhandledRejections(); + } + } + } } util.inherits(MappingPromiseArray, PromiseArray); @@ -4693,20 +5038,42 @@ var apiRejection = function(msg) { function Proxyable() {} var UNDEFINED_BINDING = {}; var util = _dereq_("./util"); +util.setReflectHandler(reflectHandler); -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { +var getDomain = function() { + var domain = process.domain; + if (domain === undefined) { return null; + } + return domain; +}; +var getContextDefault = function() { + return null; +}; +var getContextDomain = function() { + return { + domain: getDomain(), + async: null }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); +}; +var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ? + _dereq_("async_hooks").AsyncResource : null; +var getContextAsyncHooks = function() { + return { + domain: getDomain(), + async: new AsyncResource("Bluebird::Promise") + }; +}; +var getContext = util.isNode ? getContextDomain : getContextDefault; +util.notEnumerableProp(Promise, "_getContext", getContext); +var enableAsyncHooks = function() { + getContext = getContextAsyncHooks; + util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks); +}; +var disableAsyncHooks = function() { + getContext = getContextDomain; + util.notEnumerableProp(Promise, "_getContext", getContextDomain); +}; var es5 = _dereq_("./es5"); var Async = _dereq_("./async"); @@ -4730,7 +5097,9 @@ var PromiseArray = var Context = _dereq_("./context")(Promise); /*jshint unused:false*/ var createContext = Context.create; -var debug = _dereq_("./debuggability")(Promise, Context); + +var debug = _dereq_("./debuggability")(Promise, Context, + enableAsyncHooks, disableAsyncHooks); var CapturedTrace = debug.CapturedTrace; var PassThroughHandlerContext = _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); @@ -4782,6 +5151,11 @@ Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { } catchInstances.length = j; fn = arguments[i]; + + if (typeof fn !== "function") { + throw new TypeError("The last argument to .catch() " + + "must be a function, got " + util.toString(fn)); + } return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); @@ -4922,7 +5296,7 @@ Promise.prototype._then = function ( this._fireEvent("promiseChained", this, promise); } - var domain = getDomain(); + var context = getContext(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { @@ -4940,15 +5314,14 @@ Promise.prototype._then = function ( } async.invoke(settler, target, { - handler: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), + handler: util.contextBind(context, handler), promise: promise, receiver: receiver, value: value }); } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); + target._addCallbacks(didFulfill, didReject, promise, + receiver, context); } return promise; @@ -5009,7 +5382,15 @@ Promise.prototype._setWillBeCancelled = function() { Promise.prototype._setAsyncGuaranteed = function() { if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; + var bitField = this._bitField; + this._bitField = bitField | + (((bitField & 536870912) >> 2) ^ + 134217728); +}; + +Promise.prototype._setNoAsyncGuarantee = function() { + this._bitField = (this._bitField | 536870912) & + (~134217728); }; Promise.prototype._receiverAt = function (index) { @@ -5064,7 +5445,7 @@ Promise.prototype._addCallbacks = function ( reject, promise, receiver, - domain + context ) { var index = this._length(); @@ -5077,12 +5458,10 @@ Promise.prototype._addCallbacks = function ( this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : util.domainBind(domain, fulfill); + this._fulfillmentHandler0 = util.contextBind(context, fulfill); } if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); + this._rejectionHandler0 = util.contextBind(context, reject); } } else { var base = index * 4 - 4; @@ -5090,11 +5469,11 @@ Promise.prototype._addCallbacks = function ( this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); + util.contextBind(context, fulfill); } if (typeof reject === "function") { this[base + 1] = - domain === null ? reject : util.domainBind(domain, reject); + util.contextBind(context, reject); } } this._setLength(index + 1); @@ -5114,6 +5493,7 @@ Promise.prototype._resolveCallback = function(value, shouldBind) { if (shouldBind) this._propagateFrom(maybePromise, 2); + var promise = maybePromise._target(); if (promise === this) { @@ -5130,7 +5510,7 @@ Promise.prototype._resolveCallback = function(value, shouldBind) { } this._setFollowing(); this._setLength(0); - this._setFollowee(promise); + this._setFollowee(maybePromise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { @@ -5389,6 +5769,14 @@ Promise.prototype._settledValue = function() { } }; +if (typeof Symbol !== "undefined" && Symbol.toStringTag) { + es5.defineProperty(Promise.prototype, Symbol.toStringTag, { + get: function () { + return "Object"; + } + }); +} + function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} @@ -5413,14 +5801,12 @@ _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); _dereq_("./direct_resolve")(Promise); _dereq_("./synchronous_inspection")(Promise); _dereq_("./join")( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); + Promise, PromiseArray, tryConvertToPromise, INTERNAL, async); Promise.Promise = Promise; -Promise.version = "3.5.2"; -_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +Promise.version = "3.7.2"; _dereq_('./call_get.js')(Promise); -_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -_dereq_('./timers.js')(Promise, INTERNAL, debug); _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./nodeify.js')(Promise); _dereq_('./promisify.js')(Promise, INTERNAL); _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); @@ -5428,9 +5814,11 @@ _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./settle.js')(Promise, PromiseArray, debug); _dereq_('./some.js')(Promise, PromiseArray, apiRejection); -_dereq_('./filter.js')(Promise, INTERNAL); -_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./timers.js')(Promise, INTERNAL, debug); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); _dereq_('./any.js')(Promise); +_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./filter.js')(Promise, INTERNAL); util.toFastProperties(Promise); util.toFastProperties(Promise.prototype); @@ -5456,7 +5844,7 @@ _dereq_('./any.js')(Promise); }; -},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ +},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36,"async_hooks":undefined}],23:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) { @@ -5475,6 +5863,7 @@ function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); if (values instanceof Promise) { promise._propagateFrom(values, 3); + values.suppressUnhandledRejections(); } promise._setOnCancel(this); this._values = values; @@ -6213,14 +6602,13 @@ module.exports = function(Promise, tryConvertToPromise, INTERNAL, debug) { -var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, fn); + var context = Promise._getContext(); + this._fn = util.contextBind(context, fn); if (initialValue !== undefined) { initialValue = Promise.resolve(initialValue); initialValue._attachCancellationCallback(this); @@ -6240,8 +6628,8 @@ function ReductionPromiseArray(promises, fn, initialValue, _each) { util.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && - this._eachValues !== null && + if (this._eachValues !== undefined && + this._eachValues !== null && accum !== INTERNAL) { this._eachValues.push(accum); } @@ -6297,6 +6685,13 @@ ReductionPromiseArray.prototype._iterate = function (values) { this._currentCancellable = value; + for (var j = i; j < length; ++j) { + var maybePromise = values[j]; + if (maybePromise instanceof Promise) { + maybePromise.suppressUnhandledRejections(); + } + } + if (!value.isRejected()) { for (; i < length; ++i) { var ctx = { @@ -6306,7 +6701,12 @@ ReductionPromiseArray.prototype._iterate = function (values) { length: length, array: this }; + value = value._then(gotAccum, undefined, undefined, ctx, undefined); + + if ((i & 127) === 0) { + value._setNoAsyncGuarantee(); + } } } @@ -6402,7 +6802,8 @@ if (util.isNode && typeof MutationObserver === "undefined") { } else if ((typeof MutationObserver !== "undefined") && !(typeof window !== "undefined" && window.navigator && - (window.navigator.standalone || window.cordova))) { + (window.navigator.standalone || window.cordova)) && + ("classList" in document.documentElement)) { schedule = (function() { var div = document.createElement("div"); var opts = {attributes: true}; @@ -6482,6 +6883,10 @@ Promise.settle = function (promises) { return new SettledPromiseArray(promises).promise(); }; +Promise.allSettled = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + Promise.prototype.settle = function () { return Promise.settle(this); }; @@ -7482,18 +7887,42 @@ function getNativePromise() { if (typeof Promise === "function") { try { var promise = new Promise(function(){}); - if ({}.toString.call(promise) === "[object Promise]") { + if (classString(promise) === "[object Promise]") { return Promise; } } catch (e) {} } } -function domainBind(self, cb) { - return self.bind(cb); +var reflectHandler; +function contextBind(ctx, cb) { + if (ctx === null || + typeof cb !== "function" || + cb === reflectHandler) { + return cb; + } + + if (ctx.domain !== null) { + cb = ctx.domain.bind(cb); + } + + var async = ctx.async; + if (async !== null) { + var old = cb; + cb = function() { + var args = (new Array(2)).concat([].slice.call(arguments));; + args[0] = old; + args[1] = this; + return async.runInAsyncScope.apply(async, args); + }; + } + return cb; } var ret = { + setReflectHandler: function(fn) { + reflectHandler = fn; + }, isClass: isClass, isIdentifier: isIdentifier, inheritedDataKeys: inheritedDataKeys, @@ -7520,31 +7949,42 @@ var ret = { markAsOriginatingFromRejection: markAsOriginatingFromRejection, classString: classString, copyDescriptors: copyDescriptors, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", isNode: isNode, hasEnvVariables: hasEnvVariables, env: env, global: globalObject, getNativePromise: getNativePromise, - domainBind: domainBind + contextBind: contextBind }; ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); + var version; + if (process.versions && process.versions.node) { + version = process.versions.node.split(".").map(Number); + } else if (process.version) { + version = process.version.split(".").map(Number); + } return (version[0] === 0 && version[1] > 10) || (version[0] > 0); })(); +ret.nodeSupportsAsyncResource = ret.isNode && (function() { + var supportsAsync = false; + try { + var res = _dereq_("async_hooks").AsyncResource; + supportsAsync = typeof res.prototype.runInAsyncScope === "function"; + } catch (e) { + supportsAsync = false; + } + return supportsAsync; +})(); if (ret.isNode) ret.toFastProperties(process); try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; -},{"./es5":13}]},{},[4])(4) +},{"./es5":13,"async_hooks":undefined}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) -},{"_process":69,"timers":85}],33:[function(require,module,exports){ - -},{}],34:[function(require,module,exports){ +},{"_process":64,"timers":77}],34:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * @@ -9323,32 +9763,7 @@ function numberIsNaN (obj) { return obj !== obj // eslint-disable-line no-self-compare } -},{"base64-js":30,"ieee754":57}],35:[function(require,module,exports){ -/** - * Slice reference. - */ - -var slice = [].slice; - -/** - * Bind `obj` to `fn`. - * - * @param {Object} obj - * @param {Function|String} fn or string - * @return {Function} - * @api public - */ - -module.exports = function(obj, fn){ - if ('string' == typeof fn) fn = obj[fn]; - if ('function' != typeof fn) throw new Error('bind() requires a function'); - var args = slice.call(arguments, 2); - return function(){ - return fn.apply(obj, args.concat(slice.call(arguments))); - } -}; - -},{}],36:[function(require,module,exports){ +},{"base64-js":32,"ieee754":56}],35:[function(require,module,exports){ /** * Expose `Emitter`. @@ -9462,6 +9877,13 @@ Emitter.prototype.removeEventListener = function(event, fn){ break; } } + + // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + return this; }; @@ -9475,9 +9897,14 @@ Emitter.prototype.removeEventListener = function(event, fn){ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) + + var args = new Array(arguments.length - 1) , callbacks = this._callbacks['$' + event]; + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { @@ -9513,15 +9940,7 @@ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; -},{}],37:[function(require,module,exports){ - -module.exports = function(a, b){ - var fn = function(){}; - fn.prototype = b.prototype; - a.prototype = new fn; - a.prototype.constructor = a; -}; -},{}],38:[function(require,module,exports){ +},{}],36:[function(require,module,exports){ /** * Helpers. */ @@ -9552,7 +9971,7 @@ module.exports = function(val, options) { var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); - } else if (type === 'number' && isNaN(val) === false) { + } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( @@ -9574,7 +9993,7 @@ function parse(str) { if (str.length > 100) { return; } - var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { @@ -9685,7 +10104,7 @@ function plural(ms, msAbs, n, name) { return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } -},{}],39:[function(require,module,exports){ +},{}],37:[function(require,module,exports){ (function (process){ /* eslint-env browser */ @@ -9693,12 +10112,21 @@ function plural(ms, msAbs, n, name) { * This is the web browser implementation of `debug()`. */ -exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); /** * Colors. @@ -9859,18 +10287,14 @@ function formatArgs(args) { } /** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. * * @api public */ -function log(...args) { - // This hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return typeof console === 'object' && - console.log && - console.log(...args); -} +exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. @@ -9953,7 +10377,7 @@ formatters.j = function (v) { }; }).call(this,require('_process')) -},{"./common":40,"_process":69}],40:[function(require,module,exports){ +},{"./common":38,"_process":64}],38:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser @@ -9968,16 +10392,12 @@ function setup(env) { createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = require('ms'); + createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); - /** - * Active `debug` instances. - */ - createDebug.instances = []; - /** * The currently active debug mode names, and names to skip. */ @@ -9994,7 +10414,7 @@ function setup(env) { /** * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored + * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ @@ -10019,6 +10439,9 @@ function setup(env) { */ function createDebug(namespace) { let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; function debug(...args) { // Disabled? @@ -10048,7 +10471,7 @@ function setup(env) { args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { - return match; + return '%'; } index++; const formatter = createDebug.formatters[format]; @@ -10071,35 +10494,42 @@ function setup(env) { } debug.namespace = namespace; - debug.enabled = createDebug.enabled(namespace); debug.useColors = createDebug.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; + debug.color = createDebug.selectColor(namespace); debug.extend = extend; - // Debug.formatArgs = formatArgs; - // debug.rawLog = rawLog; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); - // env-specific initialization logic for debug instances + // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } - createDebug.instances.push(debug); - return debug; } - function destroy() { - const index = createDebug.instances.indexOf(this); - if (index !== -1) { - createDebug.instances.splice(index, 1); - return true; - } - return false; - } - function extend(namespace, delimiter) { - return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; } /** @@ -10111,6 +10541,7 @@ function setup(env) { */ function enable(namespaces) { createDebug.save(namespaces); + createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; @@ -10128,16 +10559,11 @@ function setup(env) { namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } - - for (i = 0; i < createDebug.instances.length; i++) { - const instance = createDebug.instances[i]; - instance.enabled = createDebug.enabled(instance.namespace); - } } /** @@ -10212,6 +10638,14 @@ function setup(env) { return val; } + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + createDebug.enable(createDebug.load()); return createDebug; @@ -10219,23288 +10653,21488 @@ function setup(env) { module.exports = setup; -},{"ms":38}],41:[function(require,module,exports){ +},{"ms":36}],39:[function(require,module,exports){ +module.exports = (() => { + if (typeof self !== "undefined") { + return self; + } else if (typeof window !== "undefined") { + return window; + } else { + return Function("return this")(); + } +})(); -module.exports = require('./socket'); +},{}],40:[function(require,module,exports){ +const Socket = require("./socket"); -/** - * Exports parser - * - * @api public - * - */ -module.exports.parser = require('engine.io-parser'); +module.exports = (uri, opts) => new Socket(uri, opts); -},{"./socket":42,"engine.io-parser":52}],42:[function(require,module,exports){ /** - * Module dependencies. + * Expose deps for legacy compatibility + * and standalone browser access. */ -var transports = require('./transports/index'); -var Emitter = require('component-emitter'); -var debug = require('debug')('engine.io-client:socket'); -var index = require('indexof'); -var parser = require('engine.io-parser'); -var parseuri = require('parseuri'); -var parseqs = require('parseqs'); +module.exports.Socket = Socket; +module.exports.protocol = Socket.protocol; // this is an int +module.exports.Transport = require("./transport"); +module.exports.transports = require("./transports/index"); +module.exports.parser = require("engine.io-parser"); -/** - * Module exports. - */ +},{"./socket":41,"./transport":42,"./transports/index":43,"engine.io-parser":54}],41:[function(require,module,exports){ +const transports = require("./transports/index"); +const Emitter = require("component-emitter"); +const debug = require("debug")("engine.io-client:socket"); +const parser = require("engine.io-parser"); +const parseuri = require("parseuri"); +const parseqs = require("parseqs"); -module.exports = Socket; +class Socket extends Emitter { + /** + * Socket constructor. + * + * @param {String|Object} uri or options + * @param {Object} options + * @api public + */ + constructor(uri, opts = {}) { + super(); -/** - * Socket constructor. - * - * @param {String|Object} uri or options - * @param {Object} options - * @api public - */ + if (uri && "object" === typeof uri) { + opts = uri; + uri = null; + } + + if (uri) { + uri = parseuri(uri); + opts.hostname = uri.host; + opts.secure = uri.protocol === "https" || uri.protocol === "wss"; + opts.port = uri.port; + if (uri.query) opts.query = uri.query; + } else if (opts.host) { + opts.hostname = parseuri(opts.host).host; + } + + this.secure = + null != opts.secure + ? opts.secure + : typeof location !== "undefined" && "https:" === location.protocol; + + if (opts.hostname && !opts.port) { + // if no port is specified manually, use the protocol default + opts.port = this.secure ? "443" : "80"; + } + + this.hostname = + opts.hostname || + (typeof location !== "undefined" ? location.hostname : "localhost"); + this.port = + opts.port || + (typeof location !== "undefined" && location.port + ? location.port + : this.secure + ? 443 + : 80); + + this.transports = opts.transports || ["polling", "websocket"]; + this.readyState = ""; + this.writeBuffer = []; + this.prevBufferLen = 0; + + this.opts = Object.assign( + { + path: "/engine.io", + agent: false, + withCredentials: false, + upgrade: true, + jsonp: true, + timestampParam: "t", + rememberUpgrade: false, + rejectUnauthorized: true, + perMessageDeflate: { + threshold: 1024 + }, + transportOptions: {} + }, + opts + ); -function Socket (uri, opts) { - if (!(this instanceof Socket)) return new Socket(uri, opts); + this.opts.path = this.opts.path.replace(/\/$/, "") + "/"; - opts = opts || {}; + if (typeof this.opts.query === "string") { + this.opts.query = parseqs.decode(this.opts.query); + } - if (uri && 'object' === typeof uri) { - opts = uri; - uri = null; - } - - if (uri) { - uri = parseuri(uri); - opts.hostname = uri.host; - opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; - opts.port = uri.port; - if (uri.query) opts.query = uri.query; - } else if (opts.host) { - opts.hostname = parseuri(opts.host).host; - } - - this.secure = null != opts.secure ? opts.secure - : (typeof location !== 'undefined' && 'https:' === location.protocol); - - if (opts.hostname && !opts.port) { - // if no port is specified manually, use the protocol default - opts.port = this.secure ? '443' : '80'; - } - - this.agent = opts.agent || false; - this.hostname = opts.hostname || - (typeof location !== 'undefined' ? location.hostname : 'localhost'); - this.port = opts.port || (typeof location !== 'undefined' && location.port - ? location.port - : (this.secure ? 443 : 80)); - this.query = opts.query || {}; - if ('string' === typeof this.query) this.query = parseqs.decode(this.query); - this.upgrade = false !== opts.upgrade; - this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; - this.forceJSONP = !!opts.forceJSONP; - this.jsonp = false !== opts.jsonp; - this.forceBase64 = !!opts.forceBase64; - this.enablesXDR = !!opts.enablesXDR; - this.timestampParam = opts.timestampParam || 't'; - this.timestampRequests = opts.timestampRequests; - this.transports = opts.transports || ['polling', 'websocket']; - this.transportOptions = opts.transportOptions || {}; - this.readyState = ''; - this.writeBuffer = []; - this.prevBufferLen = 0; - this.policyPort = opts.policyPort || 843; - this.rememberUpgrade = opts.rememberUpgrade || false; - this.binaryType = null; - this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; - this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; - - if (true === this.perMessageDeflate) this.perMessageDeflate = {}; - if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { - this.perMessageDeflate.threshold = 1024; - } - - // SSL options for Node.js client - this.pfx = opts.pfx || null; - this.key = opts.key || null; - this.passphrase = opts.passphrase || null; - this.cert = opts.cert || null; - this.ca = opts.ca || null; - this.ciphers = opts.ciphers || null; - this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized; - this.forceNode = !!opts.forceNode; - - // detect ReactNative environment - this.isReactNative = (typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative'); - - // other options for Node.js or ReactNative client - if (typeof self === 'undefined' || this.isReactNative) { - if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { - this.extraHeaders = opts.extraHeaders; - } - - if (opts.localAddress) { - this.localAddress = opts.localAddress; - } - } - - // set on handshake - this.id = null; - this.upgrades = null; - this.pingInterval = null; - this.pingTimeout = null; - - // set on heartbeat - this.pingIntervalTimer = null; - this.pingTimeoutTimer = null; - - this.open(); -} + // set on handshake + this.id = null; + this.upgrades = null; + this.pingInterval = null; + this.pingTimeout = null; + + // set on heartbeat + this.pingTimeoutTimer = null; + + if (typeof addEventListener === "function") { + addEventListener( + "beforeunload", + () => { + if (this.transport) { + // silently close the transport + this.transport.removeAllListeners(); + this.transport.close(); + } + }, + false + ); + if (this.hostname !== "localhost") { + this.offlineEventListener = () => { + this.onClose("transport close"); + }; + addEventListener("offline", this.offlineEventListener, false); + } + } -Socket.priorWebsocketSuccess = false; + this.open(); + } -/** - * Mix in `Emitter`. - */ + /** + * Creates transport of the given type. + * + * @param {String} transport name + * @return {Transport} + * @api private + */ + createTransport(name) { + debug('creating transport "%s"', name); + const query = clone(this.opts.query); + + // append engine.io protocol identifier + query.EIO = parser.protocol; + + // transport name + query.transport = name; + + // session id if we already have one + if (this.id) query.sid = this.id; + + const opts = Object.assign( + {}, + this.opts.transportOptions[name], + this.opts, + { + query, + socket: this, + hostname: this.hostname, + secure: this.secure, + port: this.port + } + ); -Emitter(Socket.prototype); + debug("options: %j", opts); -/** - * Protocol version. - * - * @api public - */ + return new transports[name](opts); + } -Socket.protocol = parser.protocol; // this is an int + /** + * Initializes transport to use and starts probe. + * + * @api private + */ + open() { + let transport; + if ( + this.opts.rememberUpgrade && + Socket.priorWebsocketSuccess && + this.transports.indexOf("websocket") !== -1 + ) { + transport = "websocket"; + } else if (0 === this.transports.length) { + // Emit error on next tick so it can be listened to + const self = this; + setTimeout(function() { + self.emit("error", "No transports available"); + }, 0); + return; + } else { + transport = this.transports[0]; + } + this.readyState = "opening"; -/** - * Expose deps for legacy compatibility - * and standalone browser access. - */ + // Retry with the next transport if the transport is disabled (jsonp: false) + try { + transport = this.createTransport(transport); + } catch (e) { + debug("error while creating transport: %s", e); + this.transports.shift(); + this.open(); + return; + } -Socket.Socket = Socket; -Socket.Transport = require('./transport'); -Socket.transports = require('./transports/index'); -Socket.parser = require('engine.io-parser'); + transport.open(); + this.setTransport(transport); + } -/** - * Creates transport of the given type. - * - * @param {String} transport name - * @return {Transport} - * @api private - */ + /** + * Sets the current transport. Disables the existing one (if any). + * + * @api private + */ + setTransport(transport) { + debug("setting transport %s", transport.name); + const self = this; -Socket.prototype.createTransport = function (name) { - debug('creating transport "%s"', name); - var query = clone(this.query); - - // append engine.io protocol identifier - query.EIO = parser.protocol; - - // transport name - query.transport = name; - - // per-transport options - var options = this.transportOptions[name] || {}; - - // session id if we already have one - if (this.id) query.sid = this.id; - - var transport = new transports[name]({ - query: query, - socket: this, - agent: options.agent || this.agent, - hostname: options.hostname || this.hostname, - port: options.port || this.port, - secure: options.secure || this.secure, - path: options.path || this.path, - forceJSONP: options.forceJSONP || this.forceJSONP, - jsonp: options.jsonp || this.jsonp, - forceBase64: options.forceBase64 || this.forceBase64, - enablesXDR: options.enablesXDR || this.enablesXDR, - timestampRequests: options.timestampRequests || this.timestampRequests, - timestampParam: options.timestampParam || this.timestampParam, - policyPort: options.policyPort || this.policyPort, - pfx: options.pfx || this.pfx, - key: options.key || this.key, - passphrase: options.passphrase || this.passphrase, - cert: options.cert || this.cert, - ca: options.ca || this.ca, - ciphers: options.ciphers || this.ciphers, - rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized, - perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate, - extraHeaders: options.extraHeaders || this.extraHeaders, - forceNode: options.forceNode || this.forceNode, - localAddress: options.localAddress || this.localAddress, - requestTimeout: options.requestTimeout || this.requestTimeout, - protocols: options.protocols || void (0), - isReactNative: this.isReactNative - }); + if (this.transport) { + debug("clearing existing transport %s", this.transport.name); + this.transport.removeAllListeners(); + } - return transport; -}; + // set up transport + this.transport = transport; -function clone (obj) { - var o = {}; - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - o[i] = obj[i]; - } + // set up transport listeners + transport + .on("drain", function() { + self.onDrain(); + }) + .on("packet", function(packet) { + self.onPacket(packet); + }) + .on("error", function(e) { + self.onError(e); + }) + .on("close", function() { + self.onClose("transport close"); + }); } - return o; -} -/** - * Initializes transport to use and starts probe. - * - * @api private - */ -Socket.prototype.open = function () { - var transport; - if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { - transport = 'websocket'; - } else if (0 === this.transports.length) { - // Emit error on next tick so it can be listened to - var self = this; - setTimeout(function () { - self.emit('error', 'No transports available'); - }, 0); - return; - } else { - transport = this.transports[0]; - } - this.readyState = 'opening'; + /** + * Probes a transport. + * + * @param {String} transport name + * @api private + */ + probe(name) { + debug('probing transport "%s"', name); + let transport = this.createTransport(name, { probe: 1 }); + let failed = false; + const self = this; - // Retry with the next transport if the transport is disabled (jsonp: false) - try { - transport = this.createTransport(transport); - } catch (e) { - this.transports.shift(); - this.open(); - return; - } + Socket.priorWebsocketSuccess = false; - transport.open(); - this.setTransport(transport); -}; + function onTransportOpen() { + if (self.onlyBinaryUpgrades) { + const upgradeLosesBinary = + !this.supportsBinary && self.transport.supportsBinary; + failed = failed || upgradeLosesBinary; + } + if (failed) return; -/** - * Sets the current transport. Disables the existing one (if any). - * - * @api private - */ + debug('probe transport "%s" opened', name); + transport.send([{ type: "ping", data: "probe" }]); + transport.once("packet", function(msg) { + if (failed) return; + if ("pong" === msg.type && "probe" === msg.data) { + debug('probe transport "%s" pong', name); + self.upgrading = true; + self.emit("upgrading", transport); + if (!transport) return; + Socket.priorWebsocketSuccess = "websocket" === transport.name; + + debug('pausing current transport "%s"', self.transport.name); + self.transport.pause(function() { + if (failed) return; + if ("closed" === self.readyState) return; + debug("changing transport and sending upgrade packet"); + + cleanup(); + + self.setTransport(transport); + transport.send([{ type: "upgrade" }]); + self.emit("upgrade", transport); + transport = null; + self.upgrading = false; + self.flush(); + }); + } else { + debug('probe transport "%s" failed', name); + const err = new Error("probe error"); + err.transport = transport.name; + self.emit("upgradeError", err); + } + }); + } -Socket.prototype.setTransport = function (transport) { - debug('setting transport %s', transport.name); - var self = this; + function freezeTransport() { + if (failed) return; - if (this.transport) { - debug('clearing existing transport %s', this.transport.name); - this.transport.removeAllListeners(); - } + // Any callback called by transport should be ignored since now + failed = true; - // set up transport - this.transport = transport; + cleanup(); - // set up transport listeners - transport - .on('drain', function () { - self.onDrain(); - }) - .on('packet', function (packet) { - self.onPacket(packet); - }) - .on('error', function (e) { - self.onError(e); - }) - .on('close', function () { - self.onClose('transport close'); - }); -}; + transport.close(); + transport = null; + } -/** - * Probes a transport. - * - * @param {String} transport name - * @api private - */ + // Handle any error that happens while probing + function onerror(err) { + const error = new Error("probe error: " + err); + error.transport = transport.name; -Socket.prototype.probe = function (name) { - debug('probing transport "%s"', name); - var transport = this.createTransport(name, { probe: 1 }); - var failed = false; - var self = this; + freezeTransport(); - Socket.priorWebsocketSuccess = false; + debug('probe transport "%s" failed because of error: %s', name, err); - function onTransportOpen () { - if (self.onlyBinaryUpgrades) { - var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; - failed = failed || upgradeLosesBinary; + self.emit("upgradeError", error); } - if (failed) return; - debug('probe transport "%s" opened', name); - transport.send([{ type: 'ping', data: 'probe' }]); - transport.once('packet', function (msg) { - if (failed) return; - if ('pong' === msg.type && 'probe' === msg.data) { - debug('probe transport "%s" pong', name); - self.upgrading = true; - self.emit('upgrading', transport); - if (!transport) return; - Socket.priorWebsocketSuccess = 'websocket' === transport.name; - - debug('pausing current transport "%s"', self.transport.name); - self.transport.pause(function () { - if (failed) return; - if ('closed' === self.readyState) return; - debug('changing transport and sending upgrade packet'); - - cleanup(); - - self.setTransport(transport); - transport.send([{ type: 'upgrade' }]); - self.emit('upgrade', transport); - transport = null; - self.upgrading = false; - self.flush(); - }); - } else { - debug('probe transport "%s" failed', name); - var err = new Error('probe error'); - err.transport = transport.name; - self.emit('upgradeError', err); + function onTransportClose() { + onerror("transport closed"); + } + + // When the socket is closed while we're probing + function onclose() { + onerror("socket closed"); + } + + // When the socket is upgraded while we're probing + function onupgrade(to) { + if (transport && to.name !== transport.name) { + debug('"%s" works - aborting "%s"', to.name, transport.name); + freezeTransport(); } - }); - } + } - function freezeTransport () { - if (failed) return; + // Remove all listeners on the transport and on self + function cleanup() { + transport.removeListener("open", onTransportOpen); + transport.removeListener("error", onerror); + transport.removeListener("close", onTransportClose); + self.removeListener("close", onclose); + self.removeListener("upgrading", onupgrade); + } + + transport.once("open", onTransportOpen); + transport.once("error", onerror); + transport.once("close", onTransportClose); - // Any callback called by transport should be ignored since now - failed = true; + this.once("close", onclose); + this.once("upgrading", onupgrade); + + transport.open(); + } - cleanup(); + /** + * Called when connection is deemed open. + * + * @api public + */ + onOpen() { + debug("socket open"); + this.readyState = "open"; + Socket.priorWebsocketSuccess = "websocket" === this.transport.name; + this.emit("open"); + this.flush(); - transport.close(); - transport = null; + // we check for `readyState` in case an `open` + // listener already closed the socket + if ( + "open" === this.readyState && + this.opts.upgrade && + this.transport.pause + ) { + debug("starting upgrade probes"); + let i = 0; + const l = this.upgrades.length; + for (; i < l; i++) { + this.probe(this.upgrades[i]); + } + } } - // Handle any error that happens while probing - function onerror (err) { - var error = new Error('probe error: ' + err); - error.transport = transport.name; + /** + * Handles a packet. + * + * @api private + */ + onPacket(packet) { + if ( + "opening" === this.readyState || + "open" === this.readyState || + "closing" === this.readyState + ) { + debug('socket receive: type "%s", data "%s"', packet.type, packet.data); + + this.emit("packet", packet); - freezeTransport(); + // Socket is live - any packet counts + this.emit("heartbeat"); - debug('probe transport "%s" failed because of error: %s', name, err); + switch (packet.type) { + case "open": + this.onHandshake(JSON.parse(packet.data)); + break; - self.emit('upgradeError', error); - } + case "ping": + this.resetPingTimeout(); + this.sendPacket("pong"); + this.emit("pong"); + break; + + case "error": + const err = new Error("server error"); + err.code = packet.data; + this.onError(err); + break; - function onTransportClose () { - onerror('transport closed'); + case "message": + this.emit("data", packet.data); + this.emit("message", packet.data); + break; + } + } else { + debug('packet received with socket readyState "%s"', this.readyState); + } } - // When the socket is closed while we're probing - function onclose () { - onerror('socket closed'); + /** + * Called upon handshake completion. + * + * @param {Object} handshake obj + * @api private + */ + onHandshake(data) { + this.emit("handshake", data); + this.id = data.sid; + this.transport.query.sid = data.sid; + this.upgrades = this.filterUpgrades(data.upgrades); + this.pingInterval = data.pingInterval; + this.pingTimeout = data.pingTimeout; + this.onOpen(); + // In case open handler closes socket + if ("closed" === this.readyState) return; + this.resetPingTimeout(); } - // When the socket is upgraded while we're probing - function onupgrade (to) { - if (transport && to.name !== transport.name) { - debug('"%s" works - aborting "%s"', to.name, transport.name); - freezeTransport(); + /** + * Sets and resets ping timeout timer based on server pings. + * + * @api private + */ + resetPingTimeout() { + clearTimeout(this.pingTimeoutTimer); + this.pingTimeoutTimer = setTimeout(() => { + this.onClose("ping timeout"); + }, this.pingInterval + this.pingTimeout); + if (this.opts.autoUnref) { + this.pingTimeoutTimer.unref(); } } - // Remove all listeners on the transport and on self - function cleanup () { - transport.removeListener('open', onTransportOpen); - transport.removeListener('error', onerror); - transport.removeListener('close', onTransportClose); - self.removeListener('close', onclose); - self.removeListener('upgrading', onupgrade); - } + /** + * Called on `drain` event + * + * @api private + */ + onDrain() { + this.writeBuffer.splice(0, this.prevBufferLen); - transport.once('open', onTransportOpen); - transport.once('error', onerror); - transport.once('close', onTransportClose); + // setting prevBufferLen = 0 is very important + // for example, when upgrading, upgrade packet is sent over, + // and a nonzero prevBufferLen could cause problems on `drain` + this.prevBufferLen = 0; - this.once('close', onclose); - this.once('upgrading', onupgrade); + if (0 === this.writeBuffer.length) { + this.emit("drain"); + } else { + this.flush(); + } + } - transport.open(); -}; + /** + * Flush write buffers. + * + * @api private + */ + flush() { + if ( + "closed" !== this.readyState && + this.transport.writable && + !this.upgrading && + this.writeBuffer.length + ) { + debug("flushing %d packets in socket", this.writeBuffer.length); + this.transport.send(this.writeBuffer); + // keep track of current length of writeBuffer + // splice writeBuffer and callbackBuffer on `drain` + this.prevBufferLen = this.writeBuffer.length; + this.emit("flush"); + } + } -/** - * Called when connection is deemed open. - * - * @api public - */ + /** + * Sends a message. + * + * @param {String} message. + * @param {Function} callback function. + * @param {Object} options. + * @return {Socket} for chaining. + * @api public + */ + write(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } -Socket.prototype.onOpen = function () { - debug('socket open'); - this.readyState = 'open'; - Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; - this.emit('open'); - this.flush(); + send(msg, options, fn) { + this.sendPacket("message", msg, options, fn); + return this; + } - // we check for `readyState` in case an `open` - // listener already closed the socket - if ('open' === this.readyState && this.upgrade && this.transport.pause) { - debug('starting upgrade probes'); - for (var i = 0, l = this.upgrades.length; i < l; i++) { - this.probe(this.upgrades[i]); + /** + * Sends a packet. + * + * @param {String} packet type. + * @param {String} data. + * @param {Object} options. + * @param {Function} callback function. + * @api private + */ + sendPacket(type, data, options, fn) { + if ("function" === typeof data) { + fn = data; + data = undefined; } - } -}; -/** - * Handles a packet. - * - * @api private - */ + if ("function" === typeof options) { + fn = options; + options = null; + } + + if ("closing" === this.readyState || "closed" === this.readyState) { + return; + } -Socket.prototype.onPacket = function (packet) { - if ('opening' === this.readyState || 'open' === this.readyState || - 'closing' === this.readyState) { - debug('socket receive: type "%s", data "%s"', packet.type, packet.data); + options = options || {}; + options.compress = false !== options.compress; - this.emit('packet', packet); + const packet = { + type: type, + data: data, + options: options + }; + this.emit("packetCreate", packet); + this.writeBuffer.push(packet); + if (fn) this.once("flush", fn); + this.flush(); + } - // Socket is live - any packet counts - this.emit('heartbeat'); + /** + * Closes the connection. + * + * @api private + */ + close() { + const self = this; - switch (packet.type) { - case 'open': - this.onHandshake(JSON.parse(packet.data)); - break; + if ("opening" === this.readyState || "open" === this.readyState) { + this.readyState = "closing"; - case 'pong': - this.setPing(); - this.emit('pong'); - break; + if (this.writeBuffer.length) { + this.once("drain", function() { + if (this.upgrading) { + waitForUpgrade(); + } else { + close(); + } + }); + } else if (this.upgrading) { + waitForUpgrade(); + } else { + close(); + } + } - case 'error': - var err = new Error('server error'); - err.code = packet.data; - this.onError(err); - break; + function close() { + self.onClose("forced close"); + debug("socket closing - telling transport to close"); + self.transport.close(); + } - case 'message': - this.emit('data', packet.data); - this.emit('message', packet.data); - break; + function cleanupAndClose() { + self.removeListener("upgrade", cleanupAndClose); + self.removeListener("upgradeError", cleanupAndClose); + close(); } - } else { - debug('packet received with socket readyState "%s"', this.readyState); - } -}; -/** - * Called upon handshake completion. - * - * @param {Object} handshake obj - * @api private - */ + function waitForUpgrade() { + // wait for upgrade to finish since we can't send packets while pausing a transport + self.once("upgrade", cleanupAndClose); + self.once("upgradeError", cleanupAndClose); + } -Socket.prototype.onHandshake = function (data) { - this.emit('handshake', data); - this.id = data.sid; - this.transport.query.sid = data.sid; - this.upgrades = this.filterUpgrades(data.upgrades); - this.pingInterval = data.pingInterval; - this.pingTimeout = data.pingTimeout; - this.onOpen(); - // In case open handler closes socket - if ('closed' === this.readyState) return; - this.setPing(); + return this; + } - // Prolong liveness of socket on heartbeat - this.removeListener('heartbeat', this.onHeartbeat); - this.on('heartbeat', this.onHeartbeat); -}; + /** + * Called upon transport error + * + * @api private + */ + onError(err) { + debug("socket error %j", err); + Socket.priorWebsocketSuccess = false; + this.emit("error", err); + this.onClose("transport error", err); + } -/** - * Resets ping timeout. - * - * @api private - */ + /** + * Called upon transport close. + * + * @api private + */ + onClose(reason, desc) { + if ( + "opening" === this.readyState || + "open" === this.readyState || + "closing" === this.readyState + ) { + debug('socket close with reason: "%s"', reason); + const self = this; -Socket.prototype.onHeartbeat = function (timeout) { - clearTimeout(this.pingTimeoutTimer); - var self = this; - self.pingTimeoutTimer = setTimeout(function () { - if ('closed' === self.readyState) return; - self.onClose('ping timeout'); - }, timeout || (self.pingInterval + self.pingTimeout)); -}; + // clear timers + clearTimeout(this.pingIntervalTimer); + clearTimeout(this.pingTimeoutTimer); -/** - * Pings server every `this.pingInterval` and expects response - * within `this.pingTimeout` or closes connection. - * - * @api private - */ + // stop event from firing again for transport + this.transport.removeAllListeners("close"); -Socket.prototype.setPing = function () { - var self = this; - clearTimeout(self.pingIntervalTimer); - self.pingIntervalTimer = setTimeout(function () { - debug('writing ping packet - expecting pong within %sms', self.pingTimeout); - self.ping(); - self.onHeartbeat(self.pingTimeout); - }, self.pingInterval); -}; + // ensure transport won't stay open + this.transport.close(); -/** -* Sends a ping packet. -* -* @api private -*/ + // ignore further transport communication + this.transport.removeAllListeners(); -Socket.prototype.ping = function () { - var self = this; - this.sendPacket('ping', function () { - self.emit('ping'); - }); -}; + if (typeof removeEventListener === "function") { + removeEventListener("offline", this.offlineEventListener, false); + } -/** - * Called on `drain` event - * - * @api private - */ + // set ready state + this.readyState = "closed"; -Socket.prototype.onDrain = function () { - this.writeBuffer.splice(0, this.prevBufferLen); + // clear session id + this.id = null; - // setting prevBufferLen = 0 is very important - // for example, when upgrading, upgrade packet is sent over, - // and a nonzero prevBufferLen could cause problems on `drain` - this.prevBufferLen = 0; + // emit close event + this.emit("close", reason, desc); - if (0 === this.writeBuffer.length) { - this.emit('drain'); - } else { - this.flush(); + // clean buffers after, so users can still + // grab the buffers on `close` event + self.writeBuffer = []; + self.prevBufferLen = 0; + } } -}; -/** - * Flush write buffers. - * - * @api private - */ - -Socket.prototype.flush = function () { - if ('closed' !== this.readyState && this.transport.writable && - !this.upgrading && this.writeBuffer.length) { - debug('flushing %d packets in socket', this.writeBuffer.length); - this.transport.send(this.writeBuffer); - // keep track of current length of writeBuffer - // splice writeBuffer and callbackBuffer on `drain` - this.prevBufferLen = this.writeBuffer.length; - this.emit('flush'); + /** + * Filters upgrades, returning only those matching client transports. + * + * @param {Array} server upgrades + * @api private + * + */ + filterUpgrades(upgrades) { + const filteredUpgrades = []; + let i = 0; + const j = upgrades.length; + for (; i < j; i++) { + if (~this.transports.indexOf(upgrades[i])) + filteredUpgrades.push(upgrades[i]); + } + return filteredUpgrades; } -}; +} + +Socket.priorWebsocketSuccess = false; /** - * Sends a message. + * Protocol version. * - * @param {String} message. - * @param {Function} callback function. - * @param {Object} options. - * @return {Socket} for chaining. * @api public */ -Socket.prototype.write = -Socket.prototype.send = function (msg, options, fn) { - this.sendPacket('message', msg, options, fn); - return this; -}; - -/** - * Sends a packet. - * - * @param {String} packet type. - * @param {String} data. - * @param {Object} options. - * @param {Function} callback function. - * @api private - */ +Socket.protocol = parser.protocol; // this is an int -Socket.prototype.sendPacket = function (type, data, options, fn) { - if ('function' === typeof data) { - fn = data; - data = undefined; +function clone(obj) { + const o = {}; + for (let i in obj) { + if (obj.hasOwnProperty(i)) { + o[i] = obj[i]; + } } + return o; +} - if ('function' === typeof options) { - fn = options; - options = null; - } +module.exports = Socket; - if ('closing' === this.readyState || 'closed' === this.readyState) { - return; +},{"./transports/index":43,"component-emitter":35,"debug":37,"engine.io-parser":54,"parseqs":62,"parseuri":63}],42:[function(require,module,exports){ +const parser = require("engine.io-parser"); +const Emitter = require("component-emitter"); +const debug = require("debug")("engine.io-client:transport"); + +class Transport extends Emitter { + /** + * Transport abstract constructor. + * + * @param {Object} options. + * @api private + */ + constructor(opts) { + super(); + + this.opts = opts; + this.query = opts.query; + this.readyState = ""; + this.socket = opts.socket; } - options = options || {}; - options.compress = false !== options.compress; + /** + * Emits an error. + * + * @param {String} str + * @return {Transport} for chaining + * @api public + */ + onError(msg, desc) { + const err = new Error(msg); + err.type = "TransportError"; + err.description = desc; + this.emit("error", err); + return this; + } - var packet = { - type: type, - data: data, - options: options - }; - this.emit('packetCreate', packet); - this.writeBuffer.push(packet); - if (fn) this.once('flush', fn); - this.flush(); -}; + /** + * Opens the transport. + * + * @api public + */ + open() { + if ("closed" === this.readyState || "" === this.readyState) { + this.readyState = "opening"; + this.doOpen(); + } -/** - * Closes the connection. - * - * @api private - */ + return this; + } -Socket.prototype.close = function () { - if ('opening' === this.readyState || 'open' === this.readyState) { - this.readyState = 'closing'; + /** + * Closes the transport. + * + * @api private + */ + close() { + if ("opening" === this.readyState || "open" === this.readyState) { + this.doClose(); + this.onClose(); + } - var self = this; + return this; + } - if (this.writeBuffer.length) { - this.once('drain', function () { - if (this.upgrading) { - waitForUpgrade(); - } else { - close(); - } - }); - } else if (this.upgrading) { - waitForUpgrade(); + /** + * Sends multiple packets. + * + * @param {Array} packets + * @api private + */ + send(packets) { + if ("open" === this.readyState) { + this.write(packets); } else { - close(); + // this might happen if the transport was silently closed in the beforeunload event handler + debug("transport is not open, discarding packets"); } } - function close () { - self.onClose('forced close'); - debug('socket closing - telling transport to close'); - self.transport.close(); + /** + * Called upon open + * + * @api private + */ + onOpen() { + this.readyState = "open"; + this.writable = true; + this.emit("open"); } - function cleanupAndClose () { - self.removeListener('upgrade', cleanupAndClose); - self.removeListener('upgradeError', cleanupAndClose); - close(); + /** + * Called with data. + * + * @param {String} data + * @api private + */ + onData(data) { + const packet = parser.decodePacket(data, this.socket.binaryType); + this.onPacket(packet); } - function waitForUpgrade () { - // wait for upgrade to finish since we can't send packets while pausing a transport - self.once('upgrade', cleanupAndClose); - self.once('upgradeError', cleanupAndClose); + /** + * Called with a decoded packet. + */ + onPacket(packet) { + this.emit("packet", packet); } - return this; -}; + /** + * Called upon close. + * + * @api private + */ + onClose() { + this.readyState = "closed"; + this.emit("close"); + } +} -/** - * Called upon transport error - * - * @api private - */ +module.exports = Transport; -Socket.prototype.onError = function (err) { - debug('socket error %j', err); - Socket.priorWebsocketSuccess = false; - this.emit('error', err); - this.onClose('transport error', err); -}; +},{"component-emitter":35,"debug":37,"engine.io-parser":54}],43:[function(require,module,exports){ +const XMLHttpRequest = require("../../contrib/xmlhttprequest-ssl/XMLHttpRequest"); +const XHR = require("./polling-xhr"); +const JSONP = require("./polling-jsonp"); +const websocket = require("./websocket"); + +exports.polling = polling; +exports.websocket = websocket; /** - * Called upon transport close. + * Polling transport polymorphic constructor. + * Decides on xhr vs jsonp based on feature detection. * * @api private */ -Socket.prototype.onClose = function (reason, desc) { - if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { - debug('socket close with reason: "%s"', reason); - var self = this; - - // clear timers - clearTimeout(this.pingIntervalTimer); - clearTimeout(this.pingTimeoutTimer); - - // stop event from firing again for transport - this.transport.removeAllListeners('close'); - - // ensure transport won't stay open - this.transport.close(); +function polling(opts) { + let xhr; + let xd = false; + let xs = false; + const jsonp = false !== opts.jsonp; - // ignore further transport communication - this.transport.removeAllListeners(); + if (typeof location !== "undefined") { + const isSSL = "https:" === location.protocol; + let port = location.port; - // set ready state - this.readyState = 'closed'; - - // clear session id - this.id = null; - - // emit close event - this.emit('close', reason, desc); + // some user agents have empty `location.port` + if (!port) { + port = isSSL ? 443 : 80; + } - // clean buffers after, so users can still - // grab the buffers on `close` event - self.writeBuffer = []; - self.prevBufferLen = 0; + xd = opts.hostname !== location.hostname || port !== opts.port; + xs = opts.secure !== isSSL; } -}; -/** - * Filters upgrades, returning only those matching client transports. - * - * @param {Array} server upgrades - * @api private - * - */ + opts.xdomain = xd; + opts.xscheme = xs; + xhr = new XMLHttpRequest(opts); -Socket.prototype.filterUpgrades = function (upgrades) { - var filteredUpgrades = []; - for (var i = 0, j = upgrades.length; i < j; i++) { - if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); + if ("open" in xhr && !opts.forceJSONP) { + return new XHR(opts); + } else { + if (!jsonp) throw new Error("JSONP disabled"); + return new JSONP(opts); } - return filteredUpgrades; -}; - -},{"./transport":43,"./transports/index":44,"component-emitter":36,"debug":50,"engine.io-parser":52,"indexof":58,"parseqs":67,"parseuri":68}],43:[function(require,module,exports){ -/** - * Module dependencies. - */ - -var parser = require('engine.io-parser'); -var Emitter = require('component-emitter'); +} -/** - * Module exports. - */ +},{"../../contrib/xmlhttprequest-ssl/XMLHttpRequest":50,"./polling-jsonp":44,"./polling-xhr":45,"./websocket":48}],44:[function(require,module,exports){ +const Polling = require("./polling"); +const globalThis = require("../globalThis"); -module.exports = Transport; +const rNewline = /\n/g; +const rEscapedNewline = /\\n/g; /** - * Transport abstract constructor. - * - * @param {Object} options. - * @api private + * Global JSONP callbacks. */ -function Transport (opts) { - this.path = opts.path; - this.hostname = opts.hostname; - this.port = opts.port; - this.secure = opts.secure; - this.query = opts.query; - this.timestampParam = opts.timestampParam; - this.timestampRequests = opts.timestampRequests; - this.readyState = ''; - this.agent = opts.agent || false; - this.socket = opts.socket; - this.enablesXDR = opts.enablesXDR; - - // SSL options for Node.js client - this.pfx = opts.pfx; - this.key = opts.key; - this.passphrase = opts.passphrase; - this.cert = opts.cert; - this.ca = opts.ca; - this.ciphers = opts.ciphers; - this.rejectUnauthorized = opts.rejectUnauthorized; - this.forceNode = opts.forceNode; - - // results of ReactNative environment detection - this.isReactNative = opts.isReactNative; - - // other options for Node.js client - this.extraHeaders = opts.extraHeaders; - this.localAddress = opts.localAddress; -} +let callbacks; -/** - * Mix in `Emitter`. - */ +class JSONPPolling extends Polling { + /** + * JSONP Polling constructor. + * + * @param {Object} opts. + * @api public + */ + constructor(opts) { + super(opts); -Emitter(Transport.prototype); + this.query = this.query || {}; -/** - * Emits an error. - * - * @param {String} str - * @return {Transport} for chaining - * @api public - */ + // define global callbacks array if not present + // we do this here (lazily) to avoid unneeded global pollution + if (!callbacks) { + // we need to consider multiple engines in the same page + callbacks = globalThis.___eio = globalThis.___eio || []; + } -Transport.prototype.onError = function (msg, desc) { - var err = new Error(msg); - err.type = 'TransportError'; - err.description = desc; - this.emit('error', err); - return this; -}; + // callback identifier + this.index = callbacks.length; -/** - * Opens the transport. - * - * @api public - */ + // add callback to jsonp global + const self = this; + callbacks.push(function(msg) { + self.onData(msg); + }); -Transport.prototype.open = function () { - if ('closed' === this.readyState || '' === this.readyState) { - this.readyState = 'opening'; - this.doOpen(); + // append to query string + this.query.j = this.index; } - return this; -}; - -/** - * Closes the transport. - * - * @api private - */ - -Transport.prototype.close = function () { - if ('opening' === this.readyState || 'open' === this.readyState) { - this.doClose(); - this.onClose(); + /** + * JSONP only supports binary as base64 encoded strings + */ + get supportsBinary() { + return false; } - return this; -}; + /** + * Closes the socket. + * + * @api private + */ + doClose() { + if (this.script) { + // prevent spurious errors from being emitted when the window is unloaded + this.script.onerror = () => {}; + this.script.parentNode.removeChild(this.script); + this.script = null; + } -/** - * Sends multiple packets. - * - * @param {Array} packets - * @api private - */ + if (this.form) { + this.form.parentNode.removeChild(this.form); + this.form = null; + this.iframe = null; + } -Transport.prototype.send = function (packets) { - if ('open' === this.readyState) { - this.write(packets); - } else { - throw new Error('Transport not open'); + super.doClose(); } -}; -/** - * Called upon open - * - * @api private - */ + /** + * Starts a poll cycle. + * + * @api private + */ + doPoll() { + const self = this; + const script = document.createElement("script"); -Transport.prototype.onOpen = function () { - this.readyState = 'open'; - this.writable = true; - this.emit('open'); -}; + if (this.script) { + this.script.parentNode.removeChild(this.script); + this.script = null; + } -/** - * Called with data. - * - * @param {String} data - * @api private - */ + script.async = true; + script.src = this.uri(); + script.onerror = function(e) { + self.onError("jsonp poll error", e); + }; -Transport.prototype.onData = function (data) { - var packet = parser.decodePacket(data, this.socket.binaryType); - this.onPacket(packet); -}; + const insertAt = document.getElementsByTagName("script")[0]; + if (insertAt) { + insertAt.parentNode.insertBefore(script, insertAt); + } else { + (document.head || document.body).appendChild(script); + } + this.script = script; -/** - * Called with a decoded packet. - */ + const isUAgecko = + "undefined" !== typeof navigator && /gecko/i.test(navigator.userAgent); -Transport.prototype.onPacket = function (packet) { - this.emit('packet', packet); -}; + if (isUAgecko) { + setTimeout(function() { + const iframe = document.createElement("iframe"); + document.body.appendChild(iframe); + document.body.removeChild(iframe); + }, 100); + } + } -/** - * Called upon close. - * - * @api private - */ + /** + * Writes with a hidden iframe. + * + * @param {String} data to send + * @param {Function} called upon flush. + * @api private + */ + doWrite(data, fn) { + const self = this; + let iframe; -Transport.prototype.onClose = function () { - this.readyState = 'closed'; - this.emit('close'); -}; + if (!this.form) { + const form = document.createElement("form"); + const area = document.createElement("textarea"); + const id = (this.iframeId = "eio_iframe_" + this.index); -},{"component-emitter":36,"engine.io-parser":52}],44:[function(require,module,exports){ -/** - * Module dependencies - */ + form.className = "socketio"; + form.style.position = "absolute"; + form.style.top = "-1000px"; + form.style.left = "-1000px"; + form.target = id; + form.method = "POST"; + form.setAttribute("accept-charset", "utf-8"); + area.name = "d"; + form.appendChild(area); + document.body.appendChild(form); -var XMLHttpRequest = require('xmlhttprequest-ssl'); -var XHR = require('./polling-xhr'); -var JSONP = require('./polling-jsonp'); -var websocket = require('./websocket'); + this.form = form; + this.area = area; + } -/** - * Export transports. - */ + this.form.action = this.uri(); -exports.polling = polling; -exports.websocket = websocket; + function complete() { + initIframe(); + fn(); + } -/** - * Polling transport polymorphic constructor. - * Decides on xhr vs jsonp based on feature detection. - * - * @api private - */ + function initIframe() { + if (self.iframe) { + try { + self.form.removeChild(self.iframe); + } catch (e) { + self.onError("jsonp polling iframe removal error", e); + } + } -function polling (opts) { - var xhr; - var xd = false; - var xs = false; - var jsonp = false !== opts.jsonp; + try { + // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) + const html = '