diff --git a/dist/index.js b/dist/index.js index 857f983..a8de070 100644 --- a/dist/index.js +++ b/dist/index.js @@ -13690,7 +13690,7 @@ module.exports = require("zlib"); /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Axios v1.6.7 Copyright (c) 2024 Matt Zabriskie and contributors +// Axios v1.7.4 Copyright (c) 2024 Matt Zabriskie and contributors const FormData$1 = __nccwpck_require__(4334); @@ -13702,7 +13702,7 @@ const util = __nccwpck_require__(3837); const followRedirects = __nccwpck_require__(7707); const zlib = __nccwpck_require__(9796); const stream = __nccwpck_require__(2781); -const EventEmitter = __nccwpck_require__(2361); +const events = __nccwpck_require__(2361); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } @@ -13714,7 +13714,6 @@ const util__default = /*#__PURE__*/_interopDefaultLegacy(util); const followRedirects__default = /*#__PURE__*/_interopDefaultLegacy(followRedirects); const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); const stream__default = /*#__PURE__*/_interopDefaultLegacy(stream); -const EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter); function bind(fn, thisArg) { return function wrap() { @@ -13929,6 +13928,8 @@ const isFormData = (thing) => { */ const isURLSearchParams = kindOfTest('URLSearchParams'); +const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); + /** * Trim excess whitespace off the beginning and end of a string * @@ -14317,8 +14318,7 @@ const toObjectSet = (arrayOrString, delimiter) => { const noop = () => {}; const toFiniteNumber = (value, defaultValue) => { - value = +value; - return Number.isFinite(value) ? value : defaultValue; + return value != null && Number.isFinite(value = +value) ? value : defaultValue; }; const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; @@ -14388,6 +14388,36 @@ const isAsyncFn = kindOfTest('AsyncFunction'); const isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); +// original code +// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + +const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener("message", ({source, data}) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + } + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); +})( + typeof setImmediate === 'function', + isFunction(_global.postMessage) +); + +const asap = typeof queueMicrotask !== 'undefined' ? + queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); + +// ********************* + const utils$1 = { isArray, isArrayBuffer, @@ -14399,6 +14429,10 @@ const utils$1 = { isBoolean, isObject, isPlainObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, isUndefined, isDate, isFile, @@ -14439,7 +14473,9 @@ const utils$1 = { isSpecCompliantForm, toJSONObject, isAsyncFn, - isThenable + isThenable, + setImmediate: _setImmediate, + asap }; /** @@ -14988,11 +15024,14 @@ const hasStandardBrowserWebWorkerEnv = (() => { ); })(); +const origin = hasBrowserEnv && window.location.href || 'http://localhost'; + const utils = /*#__PURE__*/Object.freeze({ __proto__: null, hasBrowserEnv: hasBrowserEnv, hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, - hasStandardBrowserEnv: hasStandardBrowserEnv + hasStandardBrowserEnv: hasStandardBrowserEnv, + origin: origin }); const platform = { @@ -15132,7 +15171,7 @@ const defaults = { transitional: transitionalDefaults, - adapter: ['xhr', 'http'], + adapter: ['xhr', 'http', 'fetch'], transformRequest: [function transformRequest(data, headers) { const contentType = headers.getContentType() || ''; @@ -15153,7 +15192,8 @@ const defaults = { utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || - utils$1.isBlob(data) + utils$1.isBlob(data) || + utils$1.isReadableStream(data) ) { return data; } @@ -15196,6 +15236,10 @@ const defaults = { const forcedJSONParsing = transitional && transitional.forcedJSONParsing; const JSONRequested = this.responseType === 'json'; + if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) { + return data; + } + if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { const silentJSONParsing = transitional && transitional.silentJSONParsing; const strictJSONParsing = !silentJSONParsing && JSONRequested; @@ -15399,6 +15443,10 @@ class AxiosHeaders { setHeaders(header, valueOrRewrite); } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils$1.isHeaders(header)) { + for (const [key, value] of header.entries()) { + setHeader(value, key, rewrite); + } } else { header != null && setHeader(valueOrRewrite, header, rewrite); } @@ -15711,7 +15759,7 @@ function buildFullPath(baseURL, requestedURL) { return requestedURL; } -const VERSION = "1.6.7"; +const VERSION = "1.7.4"; function parseProtocol(url) { const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); @@ -15766,88 +15814,6 @@ function fromDataURI(uri, asBlob, options) { throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); } -/** - * Throttle decorator - * @param {Function} fn - * @param {Number} freq - * @return {Function} - */ -function throttle(fn, freq) { - let timestamp = 0; - const threshold = 1000 / freq; - let timer = null; - return function throttled(force, args) { - const now = Date.now(); - if (force || now - timestamp > threshold) { - if (timer) { - clearTimeout(timer); - timer = null; - } - timestamp = now; - return fn.apply(null, args); - } - if (!timer) { - timer = setTimeout(() => { - timer = null; - timestamp = Date.now(); - return fn.apply(null, args); - }, threshold - (now - timestamp)); - } - }; -} - -/** - * Calculate data maxRate - * @param {Number} [samplesCount= 10] - * @param {Number} [min= 1000] - * @returns {Function} - */ -function speedometer(samplesCount, min) { - samplesCount = samplesCount || 10; - const bytes = new Array(samplesCount); - const timestamps = new Array(samplesCount); - let head = 0; - let tail = 0; - let firstSampleTS; - - min = min !== undefined ? min : 1000; - - return function push(chunkLength) { - const now = Date.now(); - - const startedAt = timestamps[tail]; - - if (!firstSampleTS) { - firstSampleTS = now; - } - - bytes[head] = chunkLength; - timestamps[head] = now; - - let i = tail; - let bytesCount = 0; - - while (i !== head) { - bytesCount += bytes[i++]; - i = i % samplesCount; - } - - head = (head + 1) % samplesCount; - - if (head === tail) { - tail = (tail + 1) % samplesCount; - } - - if (now - firstSampleTS < min) { - return; - } - - const passed = startedAt && now - startedAt; - - return passed ? Math.round(bytesCount * 1000 / passed) : undefined; - }; -} - const kInternals = Symbol('internals'); class AxiosTransformStream extends stream__default["default"].Transform{ @@ -15867,12 +15833,8 @@ class AxiosTransformStream extends stream__default["default"].Transform{ readableHighWaterMark: options.chunkSize }); - const self = this; - const internals = this[kInternals] = { - length: options.length, timeWindow: options.timeWindow, - ticksRate: options.ticksRate, chunkSize: options.chunkSize, maxRate: options.maxRate, minChunkSize: options.minChunkSize, @@ -15884,8 +15846,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{ onReadCallback: null }; - const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow); - this.on('newListener', event => { if (event === 'progress') { if (!internals.isCaptured) { @@ -15893,38 +15853,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{ } } }); - - let bytesNotified = 0; - - internals.updateProgress = throttle(function throttledHandler() { - const totalBytes = internals.length; - const bytesTransferred = internals.bytesSeen; - const progressBytes = bytesTransferred - bytesNotified; - if (!progressBytes || self.destroyed) return; - - const rate = _speedometer(progressBytes); - - bytesNotified = bytesTransferred; - - process.nextTick(() => { - self.emit('progress', { - 'loaded': bytesTransferred, - 'total': totalBytes, - 'progress': totalBytes ? (bytesTransferred / totalBytes) : undefined, - 'bytes': progressBytes, - 'rate': rate ? rate : undefined, - 'estimated': rate && totalBytes && bytesTransferred <= totalBytes ? - (totalBytes - bytesTransferred) / rate : undefined - }); - }); - }, internals.ticksRate); - - const onFinish = () => { - internals.updateProgress(true); - }; - - this.once('end', onFinish); - this.once('error', onFinish); } _read(size) { @@ -15938,7 +15866,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{ } _transform(chunk, encoding, callback) { - const self = this; const internals = this[kInternals]; const maxRate = internals.maxRate; @@ -15950,16 +15877,14 @@ class AxiosTransformStream extends stream__default["default"].Transform{ const bytesThreshold = (maxRate / divider); const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; - function pushChunk(_chunk, _callback) { + const pushChunk = (_chunk, _callback) => { const bytes = Buffer.byteLength(_chunk); internals.bytesSeen += bytes; internals.bytes += bytes; - if (internals.isCaptured) { - internals.updateProgress(); - } + internals.isCaptured && this.emit('progress', internals.bytesSeen); - if (self.push(_chunk)) { + if (this.push(_chunk)) { process.nextTick(_callback); } else { internals.onReadCallback = () => { @@ -15967,7 +15892,7 @@ class AxiosTransformStream extends stream__default["default"].Transform{ process.nextTick(_callback); }; } - } + }; const transformChunk = (_chunk, _callback) => { const chunkSize = Buffer.byteLength(_chunk); @@ -16024,11 +15949,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{ } }); } - - setLength(length) { - this[kInternals].length = +length; - return this; - } } const AxiosTransformStream$1 = AxiosTransformStream; @@ -16196,6 +16116,142 @@ const callbackify = (fn, reducer) => { const callbackify$1 = callbackify; +/** + * Calculate data maxRate + * @param {Number} [samplesCount= 10] + * @param {Number} [min= 1000] + * @returns {Function} + */ +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + + min = min !== undefined ? min : 1000; + + return function push(chunkLength) { + const now = Date.now(); + + const startedAt = timestamps[tail]; + + if (!firstSampleTS) { + firstSampleTS = now; + } + + bytes[head] = chunkLength; + timestamps[head] = now; + + let i = tail; + let bytesCount = 0; + + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + + head = (head + 1) % samplesCount; + + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + + if (now - firstSampleTS < min) { + return; + } + + const passed = startedAt && now - startedAt; + + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + }; +} + +/** + * Throttle decorator + * @param {Function} fn + * @param {Number} freq + * @return {Function} + */ +function throttle(fn, freq) { + let timestamp = 0; + let threshold = 1000 / freq; + let lastArgs; + let timer; + + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn.apply(null, args); + }; + + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if ( passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs); + }, threshold - passed); + } + } + }; + + const flush = () => lastArgs && invoke(lastArgs); + + return [throttled, flush]; +} + +const progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + + return throttle(e => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : undefined; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + + bytesNotified = loaded; + + const data = { + loaded, + total, + progress: total ? (loaded / total) : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total && inRange ? (total - loaded) / rate : undefined, + event: e, + lengthComputable: total != null, + [isDownloadStream ? 'download' : 'upload']: true + }; + + listener(data); + }, freq); +}; + +const progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; +}; + +const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args)); + const zlibOptions = { flush: zlib__default["default"].constants.Z_SYNC_FLUSH, finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH @@ -16216,6 +16272,14 @@ const supportedProtocols = platform.protocols.map(protocol => { return protocol + ':'; }); +const flushOnFinish = (stream, [throttled, flush]) => { + stream + .on('end', flush) + .on('error', flush); + + return throttled; +}; + /** * If the proxy or config beforeRedirects functions are defined, call them with the options * object. @@ -16354,7 +16418,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } // temporary internal emitter until the AxiosRequest class will be implemented - const emitter = new EventEmitter__default["default"](); + const emitter = new events.EventEmitter(); const onFinished = () => { if (config.cancelToken) { @@ -16391,7 +16455,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // Parse url const fullPath = buildFullPath(config.baseURL, config.url); - const parsed = new URL(fullPath, 'http://localhost'); + const parsed = new URL(fullPath, utils$1.hasBrowserEnv ? platform.origin : undefined); const protocol = parsed.protocol || supportedProtocols[0]; if (protocol === 'data:') { @@ -16449,8 +16513,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // Only set header if it hasn't been set in config headers.set('User-Agent', 'axios/' + VERSION, false); - const onDownloadProgress = config.onDownloadProgress; - const onUploadProgress = config.onUploadProgress; + const {onUploadProgress, onDownloadProgress} = config; const maxRate = config.maxRate; let maxUploadRate = undefined; let maxDownloadRate = undefined; @@ -16521,15 +16584,16 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ - length: contentLength, maxRate: utils$1.toFiniteNumber(maxUploadRate) })], utils$1.noop); - onUploadProgress && data.on('progress', progress => { - onUploadProgress(Object.assign(progress, { - upload: true - })); - }); + onUploadProgress && data.on('progress', flushOnFinish( + data, + progressEventDecorator( + contentLength, + progressEventReducer(asyncDecorator(onUploadProgress), false, 3) + ) + )); } // HTTP basic authentication @@ -16628,17 +16692,18 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { const responseLength = +res.headers['content-length']; - if (onDownloadProgress) { + if (onDownloadProgress || maxDownloadRate) { const transformStream = new AxiosTransformStream$1({ - length: utils$1.toFiniteNumber(responseLength), maxRate: utils$1.toFiniteNumber(maxDownloadRate) }); - onDownloadProgress && transformStream.on('progress', progress => { - onDownloadProgress(Object.assign(progress, { - download: true - })); - }); + onDownloadProgress && transformStream.on('progress', flushOnFinish( + transformStream, + progressEventDecorator( + responseLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) + ) + )); streams.push(transformStream); } @@ -16851,45 +16916,6 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { }); }; -const cookies = platform.hasStandardBrowserEnv ? - - // Standard browser envs support document.cookie - { - write(name, value, expires, path, domain, secure) { - const cookie = [name + '=' + encodeURIComponent(value)]; - - utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); - - utils$1.isString(path) && cookie.push('path=' + path); - - utils$1.isString(domain) && cookie.push('domain=' + domain); - - secure === true && cookie.push('secure'); - - document.cookie = cookie.join('; '); - }, - - read(name) { - const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, - - remove(name) { - this.write(name, '', Date.now() - 86400000); - } - } - - : - - // Non-standard browser env (web workers, react-native) lack needed support. - { - write() {}, - read() { - return null; - }, - remove() {} - }; - const isURLSameOrigin = platform.hasStandardBrowserEnv ? // Standard browser envs have full support of the APIs needed to test @@ -16953,80 +16979,222 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ? }; })(); -function progressEventReducer(listener, isDownloadStream) { - let bytesNotified = 0; - const _speedometer = speedometer(50, 250); +const cookies = platform.hasStandardBrowserEnv ? - return e => { - const loaded = e.loaded; - const total = e.lengthComputable ? e.total : undefined; - const progressBytes = loaded - bytesNotified; - const rate = _speedometer(progressBytes); - const inRange = loaded <= total; + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + '=' + encodeURIComponent(value)]; - bytesNotified = loaded; + utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); - const data = { - loaded, - total, - progress: total ? (loaded / total) : undefined, - bytes: progressBytes, - rate: rate ? rate : undefined, - estimated: rate && total && inRange ? (total - loaded) / rate : undefined, - event: e - }; + utils$1.isString(path) && cookie.push('path=' + path); - data[isDownloadStream ? 'download' : 'upload'] = true; + utils$1.isString(domain) && cookie.push('domain=' + domain); - listener(data); + secure === true && cookie.push('secure'); + + document.cookie = cookie.join('; '); + }, + + read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove(name) { + this.write(name, '', Date.now() - 86400000); + } + } + + : + + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() {}, + read() { + return null; + }, + remove() {} }; + +const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; + +/** + * 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 + */ +function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + const config = {}; + + function getMergedValue(target, source, caseless) { + if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { + return utils$1.merge.call({caseless}, target, source); + } else if (utils$1.isPlainObject(source)) { + return utils$1.merge({}, source); + } else if (utils$1.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, caseless) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(a, b, caseless); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a, caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a); + } + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(undefined, a); + } + } + + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true) + }; + + utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; } -const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; +const resolveConfig = (config) => { + const newConfig = mergeConfig({}, config); -const xhrAdapter = isXHRAdapterSupported && function (config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - let requestData = config.data; - const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); - let {responseType, withXSRFToken} = config; - let onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } + let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } + newConfig.headers = headers = AxiosHeaders$1.from(headers); + + newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer); + + // HTTP basic authentication + if (auth) { + headers.set('Authorization', 'Basic ' + + btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')) + ); + } + + let contentType; + + if (utils$1.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(undefined); // Let the browser set it + } else if ((contentType = headers.getContentType()) !== false) { + // fix semicolon duplication issue for ReactNative FormData implementation + const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; + headers.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); } + } + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); - let contentType; + if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { + // Add xsrf header + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); - if (utils$1.isFormData(requestData)) { - if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { - requestHeaders.setContentType(false); // Let the browser set it - } else if ((contentType = requestHeaders.getContentType()) !== false) { - // fix semicolon duplication issue for ReactNative FormData implementation - const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; - requestHeaders.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); } } + } - let request = new XMLHttpRequest(); + return newConfig; +}; - // HTTP basic authentication - if (config.auth) { - const username = config.auth.username || ''; - const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password)); +const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + +const xhrAdapter = isXHRAdapterSupported && function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config); + let requestData = _config.data; + const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); + let {responseType, onUploadProgress, onDownloadProgress} = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + + function done() { + flushUpload && flushUpload(); // flush events + flushDownload && flushDownload(); // flush events + + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + + _config.signal && _config.signal.removeEventListener('abort', onCanceled); } - const fullPath = buildFullPath(config.baseURL, config.url); + let request = new XMLHttpRequest(); - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + request.open(_config.method.toUpperCase(), _config.url, true); // Set the request timeout in MS - request.timeout = config.timeout; + request.timeout = _config.timeout; function onloadend() { if (!request) { @@ -17106,10 +17274,10 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { // Handle timeout request.ontimeout = function handleTimeout() { - let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - const transitional = config.transitional || transitionalDefaults; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; + let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = _config.transitional || transitionalDefaults; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; } reject(new AxiosError( timeoutErrorMessage, @@ -17121,22 +17289,6 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { request = null; }; - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if(platform.hasStandardBrowserEnv) { - withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config)); - - if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(fullPath))) { - // Add xsrf header - const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName); - - if (xsrfValue) { - requestHeaders.set(config.xsrfHeaderName, xsrfValue); - } - } - } - // Remove Content-Type if data is undefined requestData === undefined && requestHeaders.setContentType(null); @@ -17148,26 +17300,31 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { } // Add withCredentials to request if needed - if (!utils$1.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; + if (!utils$1.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; } // Add responseType to request if needed if (responseType && responseType !== 'json') { - request.responseType = config.responseType; + request.responseType = _config.responseType; } // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true)); + if (onDownloadProgress) { + ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); + request.addEventListener('progress', downloadThrottled); } // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress)); + if (onUploadProgress && request.upload) { + ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); + + request.upload.addEventListener('progress', uploadThrottled); + + request.upload.addEventListener('loadend', flushUpload); } - if (config.cancelToken || config.signal) { + if (_config.cancelToken || _config.signal) { // Handle cancellation // eslint-disable-next-line func-names onCanceled = cancel => { @@ -17179,13 +17336,13 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { request = null; }; - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); } } - const protocol = parseProtocol(fullPath); + const protocol = parseProtocol(_config.url); if (protocol && platform.protocols.indexOf(protocol) === -1) { reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); @@ -17198,9 +17355,339 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { }); }; +const composeSignals = (signals, timeout) => { + let controller = new AbortController(); + + let aborted; + + const onabort = function (cancel) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = cancel instanceof Error ? cancel : this.reason; + controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); + } + }; + + let timer = timeout && setTimeout(() => { + onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT)); + }, timeout); + + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach(signal => { + signal && + (signal.removeEventListener ? signal.removeEventListener('abort', onabort) : signal.unsubscribe(onabort)); + }); + signals = null; + } + }; + + signals.forEach((signal) => signal && signal.addEventListener && signal.addEventListener('abort', onabort)); + + const {signal} = controller; + + signal.unsubscribe = unsubscribe; + + return [signal, () => { + timer && clearTimeout(timer); + timer = null; + }]; +}; + +const composeSignals$1 = composeSignals; + +const streamChunk = function* (chunk, chunkSize) { + let len = chunk.byteLength; + + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + + let pos = 0; + let end; + + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } +}; + +const readBytes = async function* (iterable, chunkSize, encode) { + for await (const chunk of iterable) { + yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encode(String(chunk))), chunkSize); + } +}; + +const trackStream = (stream, chunkSize, onProgress, onFinish, encode) => { + const iterator = readBytes(stream, chunkSize, encode); + + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + }; + + return new ReadableStream({ + async pull(controller) { + try { + const {done, value} = await iterator.next(); + + if (done) { + _onFinish(); + controller.close(); + return; + } + + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator.return(); + } + }, { + highWaterMark: 2 + }) +}; + +const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function'; +const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function'; + +// used only inside the fetch adapter +const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? + ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : + async (str) => new Uint8Array(await new Response(str).arrayBuffer()) +); + +const test = (fn, ...args) => { + try { + return !!fn(...args); + } catch (e) { + return false + } +}; + +const supportsRequestStream = isReadableStreamSupported && test(() => { + let duplexAccessed = false; + + const hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }).headers.has('Content-Type'); + + return duplexAccessed && !hasContentType; +}); + +const DEFAULT_CHUNK_SIZE = 64 * 1024; + +const supportsResponseStream = isReadableStreamSupported && + test(() => utils$1.isReadableStream(new Response('').body)); + + +const resolvers = { + stream: supportsResponseStream && ((res) => res.body) +}; + +isFetchSupported && (((res) => { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { + !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() : + (_, config) => { + throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); + }); + }); +})(new Response)); + +const getBodyLength = async (body) => { + if (body == null) { + return 0; + } + + if(utils$1.isBlob(body)) { + return body.size; + } + + if(utils$1.isSpecCompliantForm(body)) { + return (await new Request(body).arrayBuffer()).byteLength; + } + + if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { + return body.byteLength; + } + + if(utils$1.isURLSearchParams(body)) { + body = body + ''; + } + + if(utils$1.isString(body)) { + return (await encodeText(body)).byteLength; + } +}; + +const resolveBodyLength = async (headers, body) => { + const length = utils$1.toFiniteNumber(headers.getContentLength()); + + return length == null ? getBodyLength(body) : length; +}; + +const fetchAdapter = isFetchSupported && (async (config) => { + let { + url, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = 'same-origin', + fetchOptions + } = resolveConfig(config); + + responseType = responseType ? (responseType + '').toLowerCase() : 'text'; + + let [composedSignal, stopTimeout] = (signal || cancelToken || timeout) ? + composeSignals$1([signal, cancelToken], timeout) : []; + + let finished, request; + + const onFinish = () => { + !finished && setTimeout(() => { + composedSignal && composedSignal.unsubscribe(); + }); + + finished = true; + }; + + let requestContentLength; + + try { + if ( + onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && + (requestContentLength = await resolveBodyLength(headers, data)) !== 0 + ) { + let _request = new Request(url, { + method: 'POST', + body: data, + duplex: "half" + }); + + let contentTypeHeader; + + if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + headers.setContentType(contentTypeHeader); + } + + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); + + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush, encodeText); + } + } + + if (!utils$1.isString(withCredentials)) { + withCredentials = withCredentials ? 'include' : 'omit'; + } + + request = new Request(url, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: withCredentials + }); + + let response = await fetch(request); + + const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + + if (supportsResponseStream && (onDownloadProgress || isStreamResponse)) { + const options = {}; + + ['status', 'statusText', 'headers'].forEach(prop => { + options[prop] = response[prop]; + }); + + const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length')); + + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; + + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + isStreamResponse && onFinish(); + }, encodeText), + options + ); + } + + responseType = responseType || 'text'; + + let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config); + + !isStreamResponse && onFinish(); + + stopTimeout && stopTimeout(); + + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders$1.from(response.headers), + status: response.status, + statusText: response.statusText, + config, + request + }); + }) + } catch (err) { + onFinish(); + + if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), + { + cause: err.cause || err + } + ) + } + + throw AxiosError.from(err, err && err.code, config, request); + } +}); + const knownAdapters = { http: httpAdapter, - xhr: xhrAdapter + xhr: xhrAdapter, + fetch: fetchAdapter }; utils$1.forEach(knownAdapters, (fn, value) => { @@ -17344,108 +17831,6 @@ function dispatchRequest(config) { }); } -const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? thing.toJSON() : thing; - -/** - * 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 - */ -function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - const config = {}; - - function getMergedValue(target, source, caseless) { - if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { - return utils$1.merge.call({caseless}, target, source); - } else if (utils$1.isPlainObject(source)) { - return utils$1.merge({}, source); - } else if (utils$1.isArray(source)) { - return source.slice(); - } - return source; - } - - // eslint-disable-next-line consistent-return - function mergeDeepProperties(a, b, caseless) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(a, b, caseless); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(undefined, a, caseless); - } - } - - // eslint-disable-next-line consistent-return - function valueFromConfig2(a, b) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(undefined, b); - } - } - - // eslint-disable-next-line consistent-return - function defaultToConfig2(a, b) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(undefined, b); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(undefined, a); - } - } - - // eslint-disable-next-line consistent-return - function mergeDirectKeys(a, b, prop) { - if (prop in config2) { - return getMergedValue(a, b); - } else if (prop in config1) { - return getMergedValue(undefined, a); - } - } - - const mergeMap = { - url: valueFromConfig2, - method: valueFromConfig2, - data: valueFromConfig2, - baseURL: defaultToConfig2, - transformRequest: defaultToConfig2, - transformResponse: defaultToConfig2, - paramsSerializer: defaultToConfig2, - timeout: defaultToConfig2, - timeoutMessage: defaultToConfig2, - withCredentials: defaultToConfig2, - withXSRFToken: defaultToConfig2, - adapter: defaultToConfig2, - responseType: defaultToConfig2, - xsrfCookieName: defaultToConfig2, - xsrfHeaderName: defaultToConfig2, - onUploadProgress: defaultToConfig2, - onDownloadProgress: defaultToConfig2, - decompress: defaultToConfig2, - maxContentLength: defaultToConfig2, - maxBodyLength: defaultToConfig2, - beforeRedirect: defaultToConfig2, - transport: defaultToConfig2, - httpAgent: defaultToConfig2, - httpsAgent: defaultToConfig2, - cancelToken: defaultToConfig2, - socketPath: defaultToConfig2, - responseEncoding: defaultToConfig2, - validateStatus: mergeDirectKeys, - headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true) - }; - - utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { - const merge = mergeMap[prop] || mergeDeepProperties; - const configValue = merge(config1[prop], config2[prop], prop); - (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); - }); - - return config; -} - const validators$1 = {}; // eslint-disable-next-line func-names @@ -17570,12 +17955,15 @@ class Axios { // slice off the Error: ... line const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; - - if (!err.stack) { - err.stack = stack; - // match without the 2 top stack lines - } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { - err.stack += '\n' + stack; + try { + if (!err.stack) { + err.stack = stack; + // match without the 2 top stack lines + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { + err.stack += '\n' + stack; + } + } catch (e) { + // ignore the case where "stack" is an un-writable property } }