diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c8afc45..27fe954 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,9 +19,9 @@ jobs: runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Setup Node ${{ matrix.node-version }} - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - run: npm ci diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 3d12a0e..12de602 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -16,7 +16,7 @@ jobs: coverage: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: ArtiomTr/jest-coverage-report-action@v2 with: test-script: npm test \ No newline at end of file diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index 774c068..611d29d 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -19,11 +19,11 @@ jobs: name: Prepare release runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Setup Node - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: 18 - name: Git config diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index ea2d6e0..d0dce86 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -24,9 +24,9 @@ jobs: runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Setup Node ${{ matrix.node-version }} - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - run: npm ci diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 34c968e..cdfe93f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,11 +17,11 @@ jobs: name: Release package runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Setup Node - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: 18 - name: Git config diff --git a/dist/cli/index.js b/dist/cli/index.js index 4c1b9df..2ad0740 100755 --- a/dist/cli/index.js +++ b/dist/cli/index.js @@ -19613,7 +19613,7 @@ exports.suggestSimilar = suggestSimilar; /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Axios v1.7.4 Copyright (c) 2024 Matt Zabriskie and contributors +// Axios v1.6.0 Copyright (c) 2023 Matt Zabriskie and contributors const FormData$1 = __nccwpck_require__(4334); @@ -19625,7 +19625,7 @@ const util = __nccwpck_require__(3837); const followRedirects = __nccwpck_require__(7707); const zlib = __nccwpck_require__(9796); const stream = __nccwpck_require__(2781); -const events = __nccwpck_require__(2361); +const EventEmitter = __nccwpck_require__(2361); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } @@ -19637,6 +19637,7 @@ 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() { @@ -19851,8 +19852,6 @@ 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 * @@ -20241,7 +20240,8 @@ const toObjectSet = (arrayOrString, delimiter) => { const noop = () => {}; const toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; + value = +value; + return Number.isFinite(value) ? value : defaultValue; }; const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; @@ -20311,37 +20311,7 @@ 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 = { +const utils = { isArray, isArrayBuffer, isBuffer, @@ -20352,10 +20322,6 @@ const utils$1 = { isBoolean, isObject, isPlainObject, - isReadableStream, - isRequest, - isResponse, - isHeaders, isUndefined, isDate, isFile, @@ -20396,9 +20362,7 @@ const utils$1 = { isSpecCompliantForm, toJSONObject, isAsyncFn, - isThenable, - setImmediate: _setImmediate, - asap + isThenable }; /** @@ -20429,7 +20393,7 @@ function AxiosError(message, code, config, request, response) { response && (this.response = response); } -utils$1.inherits(AxiosError, Error, { +utils.inherits(AxiosError, Error, { toJSON: function toJSON() { return { // Standard @@ -20444,7 +20408,7 @@ utils$1.inherits(AxiosError, Error, { columnNumber: this.columnNumber, stack: this.stack, // Axios - config: utils$1.toJSONObject(this.config), + config: utils.toJSONObject(this.config), code: this.code, status: this.response && this.response.status ? this.response.status : null }; @@ -20479,7 +20443,7 @@ Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); AxiosError.from = (error, code, config, request, response, customProps) => { const axiosError = Object.create(prototype$1); - utils$1.toFlatObject(error, axiosError, function filter(obj) { + utils.toFlatObject(error, axiosError, function filter(obj) { return obj !== Error.prototype; }, prop => { return prop !== 'isAxiosError'; @@ -20504,7 +20468,7 @@ AxiosError.from = (error, code, config, request, response, customProps) => { * @returns {boolean} */ function isVisitable(thing) { - return utils$1.isPlainObject(thing) || utils$1.isArray(thing); + return utils.isPlainObject(thing) || utils.isArray(thing); } /** @@ -20515,7 +20479,7 @@ function isVisitable(thing) { * @returns {string} the key without the brackets. */ function removeBrackets(key) { - return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; + return utils.endsWith(key, '[]') ? key.slice(0, -2) : key; } /** @@ -20544,10 +20508,10 @@ function renderKey(path, key, dots) { * @returns {boolean} */ function isFlatArray(arr) { - return utils$1.isArray(arr) && !arr.some(isVisitable); + return utils.isArray(arr) && !arr.some(isVisitable); } -const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { +const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) { return /^is[A-Z]/.test(prop); }); @@ -20575,7 +20539,7 @@ const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) * @returns */ function toFormData(obj, formData, options) { - if (!utils$1.isObject(obj)) { + if (!utils.isObject(obj)) { throw new TypeError('target must be an object'); } @@ -20583,13 +20547,13 @@ function toFormData(obj, formData, options) { formData = formData || new (FormData__default["default"] || FormData)(); // eslint-disable-next-line no-param-reassign - options = utils$1.toFlatObject(options, { + options = utils.toFlatObject(options, { metaTokens: true, dots: false, indexes: false }, false, function defined(option, source) { // eslint-disable-next-line no-eq-null,eqeqeq - return !utils$1.isUndefined(source[option]); + return !utils.isUndefined(source[option]); }); const metaTokens = options.metaTokens; @@ -20598,24 +20562,24 @@ function toFormData(obj, formData, options) { const dots = options.dots; const indexes = options.indexes; const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; - const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + const useBlob = _Blob && utils.isSpecCompliantForm(formData); - if (!utils$1.isFunction(visitor)) { + if (!utils.isFunction(visitor)) { throw new TypeError('visitor must be a function'); } function convertValue(value) { if (value === null) return ''; - if (utils$1.isDate(value)) { + if (utils.isDate(value)) { return value.toISOString(); } - if (!useBlob && utils$1.isBlob(value)) { + if (!useBlob && utils.isBlob(value)) { throw new AxiosError('Blob is not supported. Use a Buffer instead.'); } - if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); } @@ -20636,20 +20600,20 @@ function toFormData(obj, formData, options) { let arr = value; if (value && !path && typeof value === 'object') { - if (utils$1.endsWith(key, '{}')) { + if (utils.endsWith(key, '{}')) { // eslint-disable-next-line no-param-reassign key = metaTokens ? key : key.slice(0, -2); // eslint-disable-next-line no-param-reassign value = JSON.stringify(value); } else if ( - (utils$1.isArray(value) && isFlatArray(value)) || - ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) + (utils.isArray(value) && isFlatArray(value)) || + ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)) )) { // eslint-disable-next-line no-param-reassign key = removeBrackets(key); arr.forEach(function each(el, index) { - !(utils$1.isUndefined(el) || el === null) && formData.append( + !(utils.isUndefined(el) || el === null) && formData.append( // eslint-disable-next-line no-nested-ternary indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), convertValue(el) @@ -20677,7 +20641,7 @@ function toFormData(obj, formData, options) { }); function build(value, path) { - if (utils$1.isUndefined(value)) return; + if (utils.isUndefined(value)) return; if (stack.indexOf(value) !== -1) { throw Error('Circular reference detected in ' + path.join('.')); @@ -20685,9 +20649,9 @@ function toFormData(obj, formData, options) { stack.push(value); - utils$1.forEach(value, function each(el, key) { - const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( - formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers + utils.forEach(value, function each(el, key) { + const result = !(utils.isUndefined(el) || el === null) && visitor.call( + formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers ); if (result === true) { @@ -20698,7 +20662,7 @@ function toFormData(obj, formData, options) { stack.pop(); } - if (!utils$1.isObject(obj)) { + if (!utils.isObject(obj)) { throw new TypeError('data must be an object'); } @@ -20802,7 +20766,7 @@ function buildURL(url, params, options) { if (serializeFn) { serializedParams = serializeFn(params, options); } else { - serializedParams = utils$1.isURLSearchParams(params) ? + serializedParams = utils.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode); } @@ -20877,7 +20841,7 @@ class InterceptorManager { * @returns {void} */ forEach(fn) { - utils$1.forEach(this.handlers, function forEachHandler(h) { + utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } @@ -20895,7 +20859,7 @@ const transitionalDefaults = { const URLSearchParams = url__default["default"].URLSearchParams; -const platform$1 = { +const platform = { isNode: true, classes: { URLSearchParams, @@ -20905,67 +20869,10 @@ const platform$1 = { protocols: [ 'http', 'https', 'file', 'data' ] }; -const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; - -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - * - * @returns {boolean} - */ -const hasStandardBrowserEnv = ( - (product) => { - return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0 - })(typeof navigator !== 'undefined' && navigator.product); - -/** - * Determine if we're running in a standard browser webWorker environment - * - * Although the `isStandardBrowserEnv` method indicates that - * `allows axios to run in a web worker`, the WebWorker will still be - * filtered out due to its judgment standard - * `typeof window !== 'undefined' && typeof document !== 'undefined'`. - * This leads to a problem when axios post `FormData` in webWorker - */ -const hasStandardBrowserWebWorkerEnv = (() => { - return ( - typeof WorkerGlobalScope !== 'undefined' && - // eslint-disable-next-line no-undef - self instanceof WorkerGlobalScope && - typeof self.importScripts === 'function' - ); -})(); - -const origin = hasBrowserEnv && window.location.href || 'http://localhost'; - -const utils = /*#__PURE__*/Object.freeze({ - __proto__: null, - hasBrowserEnv: hasBrowserEnv, - hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, - hasStandardBrowserEnv: hasStandardBrowserEnv, - origin: origin -}); - -const platform = { - ...utils, - ...platform$1 -}; - function toURLEncodedForm(data, options) { return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ visitor: function(value, key, path, helpers) { - if (platform.isNode && utils$1.isBuffer(value)) { + if (utils.isBuffer(value)) { this.append(key, value.toString('base64')); return false; } @@ -20987,7 +20894,7 @@ function parsePropPath(name) { // foo.x.y.z // foo-x-y-z // foo x y z - return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => { return match[0] === '[]' ? '' : match[1] || match[0]; }); } @@ -21022,15 +20929,12 @@ function arrayToObject(arr) { function formDataToJSON(formData) { function buildPath(path, value, target, index) { let name = path[index++]; - - if (name === '__proto__') return true; - const isNumericKey = Number.isFinite(+name); const isLast = index >= path.length; - name = !name && utils$1.isArray(target) ? target.length : name; + name = !name && utils.isArray(target) ? target.length : name; if (isLast) { - if (utils$1.hasOwnProp(target, name)) { + if (utils.hasOwnProp(target, name)) { target[name] = [target[name], value]; } else { target[name] = value; @@ -21039,23 +20943,23 @@ function formDataToJSON(formData) { return !isNumericKey; } - if (!target[name] || !utils$1.isObject(target[name])) { + if (!target[name] || !utils.isObject(target[name])) { target[name] = []; } const result = buildPath(path, value, target[name], index); - if (result && utils$1.isArray(target[name])) { + if (result && utils.isArray(target[name])) { target[name] = arrayToObject(target[name]); } return !isNumericKey; } - if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + if (utils.isFormData(formData) && utils.isFunction(formData.entries)) { const obj = {}; - utils$1.forEachEntry(formData, (name, value) => { + utils.forEachEntry(formData, (name, value) => { buildPath(parsePropPath(name), value, obj, 0); }); @@ -21076,10 +20980,10 @@ function formDataToJSON(formData) { * @returns {string} A stringified version of the rawValue. */ function stringifySafely(rawValue, parser, encoder) { - if (utils$1.isString(rawValue)) { + if (utils.isString(rawValue)) { try { (parser || JSON.parse)(rawValue); - return utils$1.trim(rawValue); + return utils.trim(rawValue); } catch (e) { if (e.name !== 'SyntaxError') { throw e; @@ -21094,36 +20998,38 @@ const defaults = { transitional: transitionalDefaults, - adapter: ['xhr', 'http', 'fetch'], + adapter: ['xhr', 'http'], transformRequest: [function transformRequest(data, headers) { const contentType = headers.getContentType() || ''; const hasJSONContentType = contentType.indexOf('application/json') > -1; - const isObjectPayload = utils$1.isObject(data); + const isObjectPayload = utils.isObject(data); - if (isObjectPayload && utils$1.isHTMLForm(data)) { + if (isObjectPayload && utils.isHTMLForm(data)) { data = new FormData(data); } - const isFormData = utils$1.isFormData(data); + const isFormData = utils.isFormData(data); if (isFormData) { + if (!hasJSONContentType) { + return data; + } return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; } - if (utils$1.isArrayBuffer(data) || - utils$1.isBuffer(data) || - utils$1.isStream(data) || - utils$1.isFile(data) || - utils$1.isBlob(data) || - utils$1.isReadableStream(data) + if (utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) ) { return data; } - if (utils$1.isArrayBufferView(data)) { + if (utils.isArrayBufferView(data)) { return data.buffer; } - if (utils$1.isURLSearchParams(data)) { + if (utils.isURLSearchParams(data)) { headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); return data.toString(); } @@ -21135,7 +21041,7 @@ const defaults = { return toURLEncodedForm(data, this.formSerializer).toString(); } - if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { const _FormData = this.env && this.env.FormData; return toFormData( @@ -21159,11 +21065,7 @@ 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)) { + if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { const silentJSONParsing = transitional && transitional.silentJSONParsing; const strictJSONParsing = !silentJSONParsing && JSONRequested; @@ -21211,7 +21113,7 @@ const defaults = { } }; -utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { +utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { defaults.headers[method] = {}; }); @@ -21219,7 +21121,7 @@ const defaults$1 = defaults; // RawAxiosHeaders whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers -const ignoreDuplicateOf = utils$1.toObjectSet([ +const ignoreDuplicateOf = utils.toObjectSet([ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', @@ -21280,7 +21182,7 @@ function normalizeValue(value) { return value; } - return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); + return utils.isArray(value) ? value.map(normalizeValue) : String(value); } function parseTokens(str) { @@ -21298,7 +21200,7 @@ function parseTokens(str) { const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { - if (utils$1.isFunction(filter)) { + if (utils.isFunction(filter)) { return filter.call(this, value, header); } @@ -21306,13 +21208,13 @@ function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { value = header; } - if (!utils$1.isString(value)) return; + if (!utils.isString(value)) return; - if (utils$1.isString(filter)) { + if (utils.isString(filter)) { return value.indexOf(filter) !== -1; } - if (utils$1.isRegExp(filter)) { + if (utils.isRegExp(filter)) { return filter.test(value); } } @@ -21325,7 +21227,7 @@ function formatHeader(header) { } function buildAccessors(obj, header) { - const accessorName = utils$1.toCamelCase(' ' + header); + const accessorName = utils.toCamelCase(' ' + header); ['get', 'set', 'has'].forEach(methodName => { Object.defineProperty(obj, methodName + accessorName, { @@ -21352,7 +21254,7 @@ class AxiosHeaders { throw new Error('header name must be a non-empty string'); } - const key = utils$1.findKey(self, lHeader); + const key = utils.findKey(self, lHeader); if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { self[key || _header] = normalizeValue(_value); @@ -21360,16 +21262,12 @@ class AxiosHeaders { } const setHeaders = (headers, _rewrite) => - utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); - if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + if (utils.isPlainObject(header) || header instanceof this.constructor) { setHeaders(header, valueOrRewrite); - } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + } else if(utils.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); } @@ -21381,7 +21279,7 @@ class AxiosHeaders { header = normalizeHeader(header); if (header) { - const key = utils$1.findKey(this, header); + const key = utils.findKey(this, header); if (key) { const value = this[key]; @@ -21394,11 +21292,11 @@ class AxiosHeaders { return parseTokens(value); } - if (utils$1.isFunction(parser)) { + if (utils.isFunction(parser)) { return parser.call(this, value, key); } - if (utils$1.isRegExp(parser)) { + if (utils.isRegExp(parser)) { return parser.exec(value); } @@ -21411,7 +21309,7 @@ class AxiosHeaders { header = normalizeHeader(header); if (header) { - const key = utils$1.findKey(this, header); + const key = utils.findKey(this, header); return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); } @@ -21427,7 +21325,7 @@ class AxiosHeaders { _header = normalizeHeader(_header); if (_header) { - const key = utils$1.findKey(self, _header); + const key = utils.findKey(self, _header); if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { delete self[key]; @@ -21437,7 +21335,7 @@ class AxiosHeaders { } } - if (utils$1.isArray(header)) { + if (utils.isArray(header)) { header.forEach(deleteHeader); } else { deleteHeader(header); @@ -21466,8 +21364,8 @@ class AxiosHeaders { const self = this; const headers = {}; - utils$1.forEach(this, (value, header) => { - const key = utils$1.findKey(headers, header); + utils.forEach(this, (value, header) => { + const key = utils.findKey(headers, header); if (key) { self[key] = normalizeValue(value); @@ -21496,8 +21394,8 @@ class AxiosHeaders { toJSON(asStrings) { const obj = Object.create(null); - utils$1.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value); + utils.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); }); return obj; @@ -21544,7 +21442,7 @@ class AxiosHeaders { } } - utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); return this; } @@ -21553,7 +21451,7 @@ class AxiosHeaders { AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); // reserved names hotfix -utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { +utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` return { get: () => value, @@ -21563,7 +21461,7 @@ utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { } }); -utils$1.freezeMethods(AxiosHeaders); +utils.freezeMethods(AxiosHeaders); const AxiosHeaders$1 = AxiosHeaders; @@ -21581,7 +21479,7 @@ function transformData(fns, response) { const headers = AxiosHeaders$1.from(context.headers); let data = context.data; - utils$1.forEach(fns, function transform(fn) { + utils.forEach(fns, function transform(fn) { data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); }); @@ -21609,7 +21507,7 @@ function CanceledError(message, config, request) { this.name = 'CanceledError'; } -utils$1.inherits(CanceledError, AxiosError, { +utils.inherits(CanceledError, AxiosError, { __CANCEL__: true }); @@ -21661,7 +21559,7 @@ function isAbsoluteURL(url) { */ function combineURLs(baseURL, relativeURL) { return relativeURL - ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; } @@ -21682,7 +21580,7 @@ function buildFullPath(baseURL, requestedURL) { return requestedURL; } -const VERSION = "1.7.4"; +const VERSION = "1.6.0"; function parseProtocol(url) { const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); @@ -21737,11 +21635,93 @@ 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{ constructor(options) { - options = utils$1.toFlatObject(options, { + options = utils.toFlatObject(options, { maxRate: 0, chunkSize: 64 * 1024, minChunkSize: 100, @@ -21749,15 +21729,19 @@ class AxiosTransformStream extends stream__default["default"].Transform{ ticksRate: 2, samplesCount: 15 }, null, (prop, source) => { - return !utils$1.isUndefined(source[prop]); + return !utils.isUndefined(source[prop]); }); super({ 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, @@ -21769,6 +21753,8 @@ 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) { @@ -21776,6 +21762,38 @@ 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) { @@ -21789,6 +21807,7 @@ class AxiosTransformStream extends stream__default["default"].Transform{ } _transform(chunk, encoding, callback) { + const self = this; const internals = this[kInternals]; const maxRate = internals.maxRate; @@ -21800,14 +21819,16 @@ class AxiosTransformStream extends stream__default["default"].Transform{ const bytesThreshold = (maxRate / divider); const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; - const pushChunk = (_chunk, _callback) => { + function pushChunk(_chunk, _callback) { const bytes = Buffer.byteLength(_chunk); internals.bytesSeen += bytes; internals.bytes += bytes; - internals.isCaptured && this.emit('progress', internals.bytesSeen); + if (internals.isCaptured) { + internals.updateProgress(); + } - if (this.push(_chunk)) { + if (self.push(_chunk)) { process.nextTick(_callback); } else { internals.onReadCallback = () => { @@ -21815,7 +21836,7 @@ class AxiosTransformStream extends stream__default["default"].Transform{ process.nextTick(_callback); }; } - }; + } const transformChunk = (_chunk, _callback) => { const chunkSize = Buffer.byteLength(_chunk); @@ -21872,6 +21893,11 @@ class AxiosTransformStream extends stream__default["default"].Transform{ } }); } + + setLength(length) { + this[kInternals].length = +length; + return this; + } } const AxiosTransformStream$1 = AxiosTransformStream; @@ -21892,7 +21918,7 @@ const readBlob = async function* (blob) { const readBlob$1 = readBlob; -const BOUNDARY_ALPHABET = utils$1.ALPHABET.ALPHA_DIGIT + '-_'; +const BOUNDARY_ALPHABET = utils.ALPHABET.ALPHA_DIGIT + '-_'; const textEncoder = new util.TextEncoder(); @@ -21903,7 +21929,7 @@ const CRLF_BYTES_COUNT = 2; class FormDataPart { constructor(name, value) { const {escapeName} = this.constructor; - const isStringValue = utils$1.isString(value); + const isStringValue = utils.isString(value); let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : '' @@ -21930,7 +21956,7 @@ class FormDataPart { const {value} = this; - if(utils$1.isTypedArray(value)) { + if(utils.isTypedArray(value)) { yield value; } else { yield* readBlob$1(value); @@ -21952,10 +21978,10 @@ const formDataToStream = (form, headersHandler, options) => { const { tag = 'form-data-boundary', size = 25, - boundary = tag + '-' + utils$1.generateString(size, BOUNDARY_ALPHABET) + boundary = tag + '-' + utils.generateString(size, BOUNDARY_ALPHABET) } = options || {}; - if(!utils$1.isFormData(form)) { + if(!utils.isFormData(form)) { throw TypeError('FormData instance required'); } @@ -21975,7 +22001,7 @@ const formDataToStream = (form, headersHandler, options) => { contentLength += boundaryBytes.byteLength * parts.length; - contentLength = utils$1.toFiniteNumber(contentLength); + contentLength = utils.toFiniteNumber(contentLength); const computedHeaders = { 'Content-Type': `multipart/form-data; boundary=${boundary}` @@ -22025,7 +22051,7 @@ class ZlibHeaderTransformStream extends stream__default["default"].Transform { const ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream; const callbackify = (fn, reducer) => { - return utils$1.isAsyncFn(fn) ? function (...args) { + return utils.isAsyncFn(fn) ? function (...args) { const cb = args.pop(); fn.apply(this, args).then((value) => { try { @@ -22039,142 +22065,6 @@ 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 @@ -22185,7 +22075,7 @@ const brotliOptions = { finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH }; -const isBrotliSupported = utils$1.isFunction(zlib__default["default"].createBrotliDecompress); +const isBrotliSupported = utils.isFunction(zlib__default["default"].createBrotliDecompress); const {http: httpFollow, https: httpsFollow} = followRedirects__default["default"]; @@ -22195,14 +22085,6 @@ 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. @@ -22211,12 +22093,12 @@ const flushOnFinish = (stream, [throttled, flush]) => { * * @returns {Object} */ -function dispatchBeforeRedirect(options, responseDetails) { +function dispatchBeforeRedirect(options) { if (options.beforeRedirects.proxy) { options.beforeRedirects.proxy(options); } if (options.beforeRedirects.config) { - options.beforeRedirects.config(options, responseDetails); + options.beforeRedirects.config(options); } } @@ -22273,7 +22155,7 @@ function setProxy(options, configProxy, location) { }; } -const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process'; +const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process'; // temporary hotfix @@ -22303,7 +22185,7 @@ const wrapAsync = (asyncExecutor) => { }; const resolveFamily = ({address, family}) => { - if (!utils$1.isString(address)) { + if (!utils.isString(address)) { throw TypeError('address must be a string'); } return ({ @@ -22312,7 +22194,7 @@ const resolveFamily = ({address, family}) => { }); }; -const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {address, family}); +const buildAddressEntry = (address, family) => resolveFamily(utils.isObject(address) ? address : {address, family}); /*eslint consistent-return:0*/ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { @@ -22325,15 +22207,11 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { let req; if (lookup) { - const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]); + const _lookup = callbackify$1(lookup, (value) => utils.isArray(value) ? value : [value]); // hotfix to support opt.all option which is required for node 20.x lookup = (hostname, opt, cb) => { _lookup(hostname, opt, (err, arg0, arg1) => { - if (err) { - return cb(err); - } - - const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; + const addresses = utils.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); }); @@ -22341,7 +22219,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } // temporary internal emitter until the AxiosRequest class will be implemented - const emitter = new events.EventEmitter(); + const emitter = new EventEmitter__default["default"](); const onFinished = () => { if (config.cancelToken) { @@ -22378,7 +22256,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // Parse url const fullPath = buildFullPath(config.baseURL, config.url); - const parsed = new URL(fullPath, utils$1.hasBrowserEnv ? platform.origin : undefined); + const parsed = new URL(fullPath, 'http://localhost'); const protocol = parsed.protocol || supportedProtocols[0]; if (protocol === 'data:') { @@ -22405,7 +22283,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { convertedData = convertedData.toString(responseEncoding); if (!responseEncoding || responseEncoding === 'utf8') { - convertedData = utils$1.stripBOM(convertedData); + convertedData = utils.stripBOM(convertedData); } } else if (responseType === 'stream') { convertedData = stream__default["default"].Readable.from(convertedData); @@ -22436,13 +22314,14 @@ 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 {onUploadProgress, onDownloadProgress} = config; + const onDownloadProgress = config.onDownloadProgress; + const onUploadProgress = config.onUploadProgress; const maxRate = config.maxRate; let maxUploadRate = undefined; let maxDownloadRate = undefined; // support for spec compliant FormData objects - if (utils$1.isSpecCompliantForm(data)) { + if (utils.isSpecCompliantForm(data)) { const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); data = formDataToStream$1(data, (formHeaders) => { @@ -22452,7 +22331,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { boundary: userBoundary && userBoundary[1] || undefined }); // support for https://www.npmjs.com/package/form-data api - } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) { + } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { headers.set(data.getHeaders()); if (!headers.hasContentLength()) { @@ -22463,14 +22342,14 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } catch (e) { } } - } else if (utils$1.isBlob(data)) { + } else if (utils.isBlob(data)) { data.size && headers.setContentType(data.type || 'application/octet-stream'); headers.setContentLength(data.size || 0); data = stream__default["default"].Readable.from(readBlob$1(data)); - } else if (data && !utils$1.isStream(data)) { - if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) { + } else if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) ; else if (utils.isArrayBuffer(data)) { data = Buffer.from(new Uint8Array(data)); - } else if (utils$1.isString(data)) { + } else if (utils.isString(data)) { data = Buffer.from(data, 'utf-8'); } else { return reject(new AxiosError( @@ -22492,9 +22371,9 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } } - const contentLength = utils$1.toFiniteNumber(headers.getContentLength()); + const contentLength = utils.toFiniteNumber(headers.getContentLength()); - if (utils$1.isArray(maxRate)) { + if (utils.isArray(maxRate)) { maxUploadRate = maxRate[0]; maxDownloadRate = maxRate[1]; } else { @@ -22502,21 +22381,20 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } if (data && (onUploadProgress || maxUploadRate)) { - if (!utils$1.isStream(data)) { + if (!utils.isStream(data)) { data = stream__default["default"].Readable.from(data, {objectMode: false}); } data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ - maxRate: utils$1.toFiniteNumber(maxUploadRate) - })], utils$1.noop); + length: contentLength, + maxRate: utils.toFiniteNumber(maxUploadRate) + })], utils.noop); - onUploadProgress && data.on('progress', flushOnFinish( - data, - progressEventDecorator( - contentLength, - progressEventReducer(asyncDecorator(onUploadProgress), false, 3) - ) - )); + onUploadProgress && data.on('progress', progress => { + onUploadProgress(Object.assign(progress, { + upload: true + })); + }); } // HTTP basic authentication @@ -22569,7 +22447,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { }; // cacheable-lookup integration hotfix - !utils$1.isUndefined(lookup) && (options.lookup = lookup); + !utils.isUndefined(lookup) && (options.lookup = lookup); if (config.socketPath) { options.socketPath = config.socketPath; @@ -22615,18 +22493,17 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { const responseLength = +res.headers['content-length']; - if (onDownloadProgress || maxDownloadRate) { + if (onDownloadProgress) { const transformStream = new AxiosTransformStream$1({ - maxRate: utils$1.toFiniteNumber(maxDownloadRate) + length: utils.toFiniteNumber(responseLength), + maxRate: utils.toFiniteNumber(maxDownloadRate) }); - onDownloadProgress && transformStream.on('progress', flushOnFinish( - transformStream, - progressEventDecorator( - responseLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) - ) - )); + onDownloadProgress && transformStream.on('progress', progress => { + onDownloadProgress(Object.assign(progress, { + download: true + })); + }); streams.push(transformStream); } @@ -22674,7 +22551,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } } - responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0]; + responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils.noop) : streams[0]; const offListeners = stream__default["default"].finished(responseStream, () => { offListeners(); @@ -22736,7 +22613,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { if (responseType !== 'arraybuffer') { responseData = responseData.toString(responseEncoding); if (!responseEncoding || responseEncoding === 'utf8') { - responseData = utils$1.stripBOM(responseData); + responseData = utils.stripBOM(responseData); } } response.data = responseData; @@ -22813,7 +22690,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // Send the request - if (utils$1.isStream(data)) { + if (utils.isStream(data)) { let ended = false; let errored = false; @@ -22839,7 +22716,55 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { }); }; -const isURLSameOrigin = platform.hasStandardBrowserEnv ? +const cookies = platform.isStandardBrowserEnv ? + +// Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + const cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); + + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } + + if (utils.isString(path)) { + cookie.push('path=' + path); + } + + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } + + if (secure === true) { + cookie.push('secure'); + } + + document.cookie = cookie.join('; '); + }, + + read: function read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + 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() {} + }; + })(); + +const isURLSameOrigin = platform.isStandardBrowserEnv ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. @@ -22849,7 +22774,7 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ? let originURL; /** - * Parse a URL to discover its components + * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} @@ -22889,7 +22814,7 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ? * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { - const parsed = (utils$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; @@ -22902,222 +22827,81 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ? }; })(); -const cookies = platform.hasStandardBrowserEnv ? +function progressEventReducer(listener, isDownloadStream) { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); - // Standard browser envs support document.cookie - { - write(name, value, expires, path, domain, secure) { - const cookie = [name + '=' + encodeURIComponent(value)]; + 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; - utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); + bytesNotified = loaded; - utils$1.isString(path) && cookie.push('path=' + path); + 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(domain) && cookie.push('domain=' + domain); + data[isDownloadStream ? 'download' : 'upload'] = true; - 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() {} + listener(data); }; - -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 resolveConfig = (config) => { - const newConfig = mergeConfig({}, config); - - let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; - - 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)); - - if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { - // Add xsrf header - const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); - - if (xsrfValue) { - headers.set(xsrfHeaderName, xsrfValue); - } - } - } - - return newConfig; -}; - 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 requestData = config.data; + const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); + const responseType = config.responseType; let onCanceled; - let uploadThrottled, downloadThrottled; - let flushUpload, flushDownload; - function done() { - flushUpload && flushUpload(); // flush events - flushDownload && flushDownload(); // flush events + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } - _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); + } + } - _config.signal && _config.signal.removeEventListener('abort', onCanceled); + let contentType; + + if (utils.isFormData(requestData)) { + if (platform.isStandardBrowserEnv || platform.isStandardBrowserWebWorkerEnv) { + requestHeaders.setContentType(false); // Let the browser set it + } else if(!requestHeaders.getContentType(/^\s*multipart\/form-data/)){ + requestHeaders.setContentType('multipart/form-data'); // mobile/desktop app frameworks + } else if(utils.isString(contentType = requestHeaders.getContentType())){ + // fix semicolon duplication issue for ReactNative FormData implementation + requestHeaders.setContentType(contentType.replace(/^\s*(multipart\/form-data);+/, '$1')); + } } let request = new XMLHttpRequest(); - request.open(_config.method.toUpperCase(), _config.url, true); + // 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 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; + request.timeout = config.timeout; function onloadend() { if (!request) { @@ -23197,10 +22981,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, @@ -23212,42 +22996,50 @@ 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.isStandardBrowserEnv) { + // Add xsrf header + // regarding CVE-2023-45857 config.withCredentials condition was removed temporarily + const xsrfValue = isURLSameOrigin(fullPath) && 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); // Add headers to the request if ('setRequestHeader' in request) { - utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { request.setRequestHeader(key, val); }); } // Add withCredentials to request if needed - if (!utils$1.isUndefined(_config.withCredentials)) { - request.withCredentials = !!_config.withCredentials; + if (!utils.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 (onDownloadProgress) { - ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); - request.addEventListener('progress', downloadThrottled); + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true)); } // Not all browsers support upload events - if (onUploadProgress && request.upload) { - ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); - - request.upload.addEventListener('progress', uploadThrottled); - - request.upload.addEventListener('loadend', flushUpload); + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress)); } - if (_config.cancelToken || _config.signal) { + if (config.cancelToken || config.signal) { // Handle cancellation // eslint-disable-next-line func-names onCanceled = cancel => { @@ -23259,13 +23051,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(_config.url); + const protocol = parseProtocol(fullPath); if (protocol && platform.protocols.indexOf(protocol) === -1) { reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); @@ -23278,342 +23070,12 @@ 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, - fetch: fetchAdapter + xhr: xhrAdapter }; -utils$1.forEach(knownAdapters, (fn, value) => { +utils.forEach(knownAdapters, (fn, value) => { if (fn) { try { Object.defineProperty(fn, 'name', {value}); @@ -23626,11 +23088,11 @@ utils$1.forEach(knownAdapters, (fn, value) => { const renderReason = (reason) => `- ${reason}`; -const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; +const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false; const adapters = { getAdapter: (adapters) => { - adapters = utils$1.isArray(adapters) ? adapters : [adapters]; + adapters = utils.isArray(adapters) ? adapters : [adapters]; const {length} = adapters; let nameOrAdapter; @@ -23754,6 +23216,107 @@ 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.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge.call({caseless}, target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, caseless) { + if (!utils.isUndefined(b)) { + return getMergedValue(a, b, caseless); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a, caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils.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, + 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.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; +} + const validators$1 = {}; // eslint-disable-next-line func-names @@ -23867,34 +23430,7 @@ class Axios { * * @returns {Promise} The Promise to be fulfilled */ - async request(configOrUrl, config) { - try { - return await this._request(configOrUrl, config); - } catch (err) { - if (err instanceof Error) { - let dummy; - - Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error()); - - // slice off the Error: ... line - const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; - 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 - } - } - - throw err; - } - } - - _request(configOrUrl, config) { + request(configOrUrl, config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof configOrUrl === 'string') { @@ -23917,7 +23453,7 @@ class Axios { } if (paramsSerializer != null) { - if (utils$1.isFunction(paramsSerializer)) { + if (utils.isFunction(paramsSerializer)) { config.paramsSerializer = { serialize: paramsSerializer }; @@ -23933,12 +23469,12 @@ class Axios { config.method = (config.method || this.defaults.method || 'get').toLowerCase(); // Flatten headers - let contextHeaders = headers && utils$1.merge( + let contextHeaders = headers && utils.merge( headers.common, headers[config.method] ); - headers && utils$1.forEach( + headers && utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], (method) => { delete headers[method]; @@ -24025,7 +23561,7 @@ class Axios { } // Provide aliases for supported request methods -utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { @@ -24036,7 +23572,7 @@ utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoDa }; }); -utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ function generateHTTPMethod(isForm) { @@ -24212,7 +23748,7 @@ function spread(callback) { * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ function isAxiosError(payload) { - return utils$1.isObject(payload) && (payload.isAxiosError === true); + return utils.isObject(payload) && (payload.isAxiosError === true); } const HttpStatusCode = { @@ -24299,10 +23835,10 @@ function createInstance(defaultConfig) { const instance = bind(Axios$1.prototype.request, context); // Copy axios.prototype to instance - utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); + utils.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); // Copy context to instance - utils$1.extend(instance, context, null, {allOwnKeys: true}); + utils.extend(instance, context, null, {allOwnKeys: true}); // Factory for creating new instances instance.create = function create(instanceConfig) { @@ -24346,7 +23882,7 @@ axios.mergeConfig = mergeConfig; axios.AxiosHeaders = AxiosHeaders$1; -axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); +axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); axios.getAdapter = adapters.getAdapter; diff --git a/dist/gha/index.js b/dist/gha/index.js index aaa35f5..0c37615 100755 --- a/dist/gha/index.js +++ b/dist/gha/index.js @@ -19021,7 +19021,7 @@ module.exports = require("zlib"); /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Axios v1.7.4 Copyright (c) 2024 Matt Zabriskie and contributors +// Axios v1.6.0 Copyright (c) 2023 Matt Zabriskie and contributors const FormData$1 = __nccwpck_require__(4334); @@ -19033,7 +19033,7 @@ const util = __nccwpck_require__(3837); const followRedirects = __nccwpck_require__(7707); const zlib = __nccwpck_require__(9796); const stream = __nccwpck_require__(2781); -const events = __nccwpck_require__(2361); +const EventEmitter = __nccwpck_require__(2361); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } @@ -19045,6 +19045,7 @@ 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() { @@ -19259,8 +19260,6 @@ 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 * @@ -19649,7 +19648,8 @@ const toObjectSet = (arrayOrString, delimiter) => { const noop = () => {}; const toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; + value = +value; + return Number.isFinite(value) ? value : defaultValue; }; const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; @@ -19719,37 +19719,7 @@ 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 = { +const utils = { isArray, isArrayBuffer, isBuffer, @@ -19760,10 +19730,6 @@ const utils$1 = { isBoolean, isObject, isPlainObject, - isReadableStream, - isRequest, - isResponse, - isHeaders, isUndefined, isDate, isFile, @@ -19804,9 +19770,7 @@ const utils$1 = { isSpecCompliantForm, toJSONObject, isAsyncFn, - isThenable, - setImmediate: _setImmediate, - asap + isThenable }; /** @@ -19837,7 +19801,7 @@ function AxiosError(message, code, config, request, response) { response && (this.response = response); } -utils$1.inherits(AxiosError, Error, { +utils.inherits(AxiosError, Error, { toJSON: function toJSON() { return { // Standard @@ -19852,7 +19816,7 @@ utils$1.inherits(AxiosError, Error, { columnNumber: this.columnNumber, stack: this.stack, // Axios - config: utils$1.toJSONObject(this.config), + config: utils.toJSONObject(this.config), code: this.code, status: this.response && this.response.status ? this.response.status : null }; @@ -19887,7 +19851,7 @@ Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); AxiosError.from = (error, code, config, request, response, customProps) => { const axiosError = Object.create(prototype$1); - utils$1.toFlatObject(error, axiosError, function filter(obj) { + utils.toFlatObject(error, axiosError, function filter(obj) { return obj !== Error.prototype; }, prop => { return prop !== 'isAxiosError'; @@ -19912,7 +19876,7 @@ AxiosError.from = (error, code, config, request, response, customProps) => { * @returns {boolean} */ function isVisitable(thing) { - return utils$1.isPlainObject(thing) || utils$1.isArray(thing); + return utils.isPlainObject(thing) || utils.isArray(thing); } /** @@ -19923,7 +19887,7 @@ function isVisitable(thing) { * @returns {string} the key without the brackets. */ function removeBrackets(key) { - return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; + return utils.endsWith(key, '[]') ? key.slice(0, -2) : key; } /** @@ -19952,10 +19916,10 @@ function renderKey(path, key, dots) { * @returns {boolean} */ function isFlatArray(arr) { - return utils$1.isArray(arr) && !arr.some(isVisitable); + return utils.isArray(arr) && !arr.some(isVisitable); } -const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { +const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) { return /^is[A-Z]/.test(prop); }); @@ -19983,7 +19947,7 @@ const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) * @returns */ function toFormData(obj, formData, options) { - if (!utils$1.isObject(obj)) { + if (!utils.isObject(obj)) { throw new TypeError('target must be an object'); } @@ -19991,13 +19955,13 @@ function toFormData(obj, formData, options) { formData = formData || new (FormData__default["default"] || FormData)(); // eslint-disable-next-line no-param-reassign - options = utils$1.toFlatObject(options, { + options = utils.toFlatObject(options, { metaTokens: true, dots: false, indexes: false }, false, function defined(option, source) { // eslint-disable-next-line no-eq-null,eqeqeq - return !utils$1.isUndefined(source[option]); + return !utils.isUndefined(source[option]); }); const metaTokens = options.metaTokens; @@ -20006,24 +19970,24 @@ function toFormData(obj, formData, options) { const dots = options.dots; const indexes = options.indexes; const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; - const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + const useBlob = _Blob && utils.isSpecCompliantForm(formData); - if (!utils$1.isFunction(visitor)) { + if (!utils.isFunction(visitor)) { throw new TypeError('visitor must be a function'); } function convertValue(value) { if (value === null) return ''; - if (utils$1.isDate(value)) { + if (utils.isDate(value)) { return value.toISOString(); } - if (!useBlob && utils$1.isBlob(value)) { + if (!useBlob && utils.isBlob(value)) { throw new AxiosError('Blob is not supported. Use a Buffer instead.'); } - if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); } @@ -20044,20 +20008,20 @@ function toFormData(obj, formData, options) { let arr = value; if (value && !path && typeof value === 'object') { - if (utils$1.endsWith(key, '{}')) { + if (utils.endsWith(key, '{}')) { // eslint-disable-next-line no-param-reassign key = metaTokens ? key : key.slice(0, -2); // eslint-disable-next-line no-param-reassign value = JSON.stringify(value); } else if ( - (utils$1.isArray(value) && isFlatArray(value)) || - ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) + (utils.isArray(value) && isFlatArray(value)) || + ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)) )) { // eslint-disable-next-line no-param-reassign key = removeBrackets(key); arr.forEach(function each(el, index) { - !(utils$1.isUndefined(el) || el === null) && formData.append( + !(utils.isUndefined(el) || el === null) && formData.append( // eslint-disable-next-line no-nested-ternary indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), convertValue(el) @@ -20085,7 +20049,7 @@ function toFormData(obj, formData, options) { }); function build(value, path) { - if (utils$1.isUndefined(value)) return; + if (utils.isUndefined(value)) return; if (stack.indexOf(value) !== -1) { throw Error('Circular reference detected in ' + path.join('.')); @@ -20093,9 +20057,9 @@ function toFormData(obj, formData, options) { stack.push(value); - utils$1.forEach(value, function each(el, key) { - const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( - formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers + utils.forEach(value, function each(el, key) { + const result = !(utils.isUndefined(el) || el === null) && visitor.call( + formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers ); if (result === true) { @@ -20106,7 +20070,7 @@ function toFormData(obj, formData, options) { stack.pop(); } - if (!utils$1.isObject(obj)) { + if (!utils.isObject(obj)) { throw new TypeError('data must be an object'); } @@ -20210,7 +20174,7 @@ function buildURL(url, params, options) { if (serializeFn) { serializedParams = serializeFn(params, options); } else { - serializedParams = utils$1.isURLSearchParams(params) ? + serializedParams = utils.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode); } @@ -20285,7 +20249,7 @@ class InterceptorManager { * @returns {void} */ forEach(fn) { - utils$1.forEach(this.handlers, function forEachHandler(h) { + utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } @@ -20303,7 +20267,7 @@ const transitionalDefaults = { const URLSearchParams = url__default["default"].URLSearchParams; -const platform$1 = { +const platform = { isNode: true, classes: { URLSearchParams, @@ -20313,67 +20277,10 @@ const platform$1 = { protocols: [ 'http', 'https', 'file', 'data' ] }; -const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; - -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - * - * @returns {boolean} - */ -const hasStandardBrowserEnv = ( - (product) => { - return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0 - })(typeof navigator !== 'undefined' && navigator.product); - -/** - * Determine if we're running in a standard browser webWorker environment - * - * Although the `isStandardBrowserEnv` method indicates that - * `allows axios to run in a web worker`, the WebWorker will still be - * filtered out due to its judgment standard - * `typeof window !== 'undefined' && typeof document !== 'undefined'`. - * This leads to a problem when axios post `FormData` in webWorker - */ -const hasStandardBrowserWebWorkerEnv = (() => { - return ( - typeof WorkerGlobalScope !== 'undefined' && - // eslint-disable-next-line no-undef - self instanceof WorkerGlobalScope && - typeof self.importScripts === 'function' - ); -})(); - -const origin = hasBrowserEnv && window.location.href || 'http://localhost'; - -const utils = /*#__PURE__*/Object.freeze({ - __proto__: null, - hasBrowserEnv: hasBrowserEnv, - hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, - hasStandardBrowserEnv: hasStandardBrowserEnv, - origin: origin -}); - -const platform = { - ...utils, - ...platform$1 -}; - function toURLEncodedForm(data, options) { return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ visitor: function(value, key, path, helpers) { - if (platform.isNode && utils$1.isBuffer(value)) { + if (utils.isBuffer(value)) { this.append(key, value.toString('base64')); return false; } @@ -20395,7 +20302,7 @@ function parsePropPath(name) { // foo.x.y.z // foo-x-y-z // foo x y z - return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => { return match[0] === '[]' ? '' : match[1] || match[0]; }); } @@ -20430,15 +20337,12 @@ function arrayToObject(arr) { function formDataToJSON(formData) { function buildPath(path, value, target, index) { let name = path[index++]; - - if (name === '__proto__') return true; - const isNumericKey = Number.isFinite(+name); const isLast = index >= path.length; - name = !name && utils$1.isArray(target) ? target.length : name; + name = !name && utils.isArray(target) ? target.length : name; if (isLast) { - if (utils$1.hasOwnProp(target, name)) { + if (utils.hasOwnProp(target, name)) { target[name] = [target[name], value]; } else { target[name] = value; @@ -20447,23 +20351,23 @@ function formDataToJSON(formData) { return !isNumericKey; } - if (!target[name] || !utils$1.isObject(target[name])) { + if (!target[name] || !utils.isObject(target[name])) { target[name] = []; } const result = buildPath(path, value, target[name], index); - if (result && utils$1.isArray(target[name])) { + if (result && utils.isArray(target[name])) { target[name] = arrayToObject(target[name]); } return !isNumericKey; } - if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + if (utils.isFormData(formData) && utils.isFunction(formData.entries)) { const obj = {}; - utils$1.forEachEntry(formData, (name, value) => { + utils.forEachEntry(formData, (name, value) => { buildPath(parsePropPath(name), value, obj, 0); }); @@ -20484,10 +20388,10 @@ function formDataToJSON(formData) { * @returns {string} A stringified version of the rawValue. */ function stringifySafely(rawValue, parser, encoder) { - if (utils$1.isString(rawValue)) { + if (utils.isString(rawValue)) { try { (parser || JSON.parse)(rawValue); - return utils$1.trim(rawValue); + return utils.trim(rawValue); } catch (e) { if (e.name !== 'SyntaxError') { throw e; @@ -20502,36 +20406,38 @@ const defaults = { transitional: transitionalDefaults, - adapter: ['xhr', 'http', 'fetch'], + adapter: ['xhr', 'http'], transformRequest: [function transformRequest(data, headers) { const contentType = headers.getContentType() || ''; const hasJSONContentType = contentType.indexOf('application/json') > -1; - const isObjectPayload = utils$1.isObject(data); + const isObjectPayload = utils.isObject(data); - if (isObjectPayload && utils$1.isHTMLForm(data)) { + if (isObjectPayload && utils.isHTMLForm(data)) { data = new FormData(data); } - const isFormData = utils$1.isFormData(data); + const isFormData = utils.isFormData(data); if (isFormData) { + if (!hasJSONContentType) { + return data; + } return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; } - if (utils$1.isArrayBuffer(data) || - utils$1.isBuffer(data) || - utils$1.isStream(data) || - utils$1.isFile(data) || - utils$1.isBlob(data) || - utils$1.isReadableStream(data) + if (utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) ) { return data; } - if (utils$1.isArrayBufferView(data)) { + if (utils.isArrayBufferView(data)) { return data.buffer; } - if (utils$1.isURLSearchParams(data)) { + if (utils.isURLSearchParams(data)) { headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); return data.toString(); } @@ -20543,7 +20449,7 @@ const defaults = { return toURLEncodedForm(data, this.formSerializer).toString(); } - if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { const _FormData = this.env && this.env.FormData; return toFormData( @@ -20567,11 +20473,7 @@ 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)) { + if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { const silentJSONParsing = transitional && transitional.silentJSONParsing; const strictJSONParsing = !silentJSONParsing && JSONRequested; @@ -20619,7 +20521,7 @@ const defaults = { } }; -utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { +utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { defaults.headers[method] = {}; }); @@ -20627,7 +20529,7 @@ const defaults$1 = defaults; // RawAxiosHeaders whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers -const ignoreDuplicateOf = utils$1.toObjectSet([ +const ignoreDuplicateOf = utils.toObjectSet([ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', @@ -20688,7 +20590,7 @@ function normalizeValue(value) { return value; } - return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); + return utils.isArray(value) ? value.map(normalizeValue) : String(value); } function parseTokens(str) { @@ -20706,7 +20608,7 @@ function parseTokens(str) { const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { - if (utils$1.isFunction(filter)) { + if (utils.isFunction(filter)) { return filter.call(this, value, header); } @@ -20714,13 +20616,13 @@ function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { value = header; } - if (!utils$1.isString(value)) return; + if (!utils.isString(value)) return; - if (utils$1.isString(filter)) { + if (utils.isString(filter)) { return value.indexOf(filter) !== -1; } - if (utils$1.isRegExp(filter)) { + if (utils.isRegExp(filter)) { return filter.test(value); } } @@ -20733,7 +20635,7 @@ function formatHeader(header) { } function buildAccessors(obj, header) { - const accessorName = utils$1.toCamelCase(' ' + header); + const accessorName = utils.toCamelCase(' ' + header); ['get', 'set', 'has'].forEach(methodName => { Object.defineProperty(obj, methodName + accessorName, { @@ -20760,7 +20662,7 @@ class AxiosHeaders { throw new Error('header name must be a non-empty string'); } - const key = utils$1.findKey(self, lHeader); + const key = utils.findKey(self, lHeader); if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { self[key || _header] = normalizeValue(_value); @@ -20768,16 +20670,12 @@ class AxiosHeaders { } const setHeaders = (headers, _rewrite) => - utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); - if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + if (utils.isPlainObject(header) || header instanceof this.constructor) { setHeaders(header, valueOrRewrite); - } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + } else if(utils.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); } @@ -20789,7 +20687,7 @@ class AxiosHeaders { header = normalizeHeader(header); if (header) { - const key = utils$1.findKey(this, header); + const key = utils.findKey(this, header); if (key) { const value = this[key]; @@ -20802,11 +20700,11 @@ class AxiosHeaders { return parseTokens(value); } - if (utils$1.isFunction(parser)) { + if (utils.isFunction(parser)) { return parser.call(this, value, key); } - if (utils$1.isRegExp(parser)) { + if (utils.isRegExp(parser)) { return parser.exec(value); } @@ -20819,7 +20717,7 @@ class AxiosHeaders { header = normalizeHeader(header); if (header) { - const key = utils$1.findKey(this, header); + const key = utils.findKey(this, header); return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); } @@ -20835,7 +20733,7 @@ class AxiosHeaders { _header = normalizeHeader(_header); if (_header) { - const key = utils$1.findKey(self, _header); + const key = utils.findKey(self, _header); if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { delete self[key]; @@ -20845,7 +20743,7 @@ class AxiosHeaders { } } - if (utils$1.isArray(header)) { + if (utils.isArray(header)) { header.forEach(deleteHeader); } else { deleteHeader(header); @@ -20874,8 +20772,8 @@ class AxiosHeaders { const self = this; const headers = {}; - utils$1.forEach(this, (value, header) => { - const key = utils$1.findKey(headers, header); + utils.forEach(this, (value, header) => { + const key = utils.findKey(headers, header); if (key) { self[key] = normalizeValue(value); @@ -20904,8 +20802,8 @@ class AxiosHeaders { toJSON(asStrings) { const obj = Object.create(null); - utils$1.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value); + utils.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); }); return obj; @@ -20952,7 +20850,7 @@ class AxiosHeaders { } } - utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); return this; } @@ -20961,7 +20859,7 @@ class AxiosHeaders { AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); // reserved names hotfix -utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { +utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` return { get: () => value, @@ -20971,7 +20869,7 @@ utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { } }); -utils$1.freezeMethods(AxiosHeaders); +utils.freezeMethods(AxiosHeaders); const AxiosHeaders$1 = AxiosHeaders; @@ -20989,7 +20887,7 @@ function transformData(fns, response) { const headers = AxiosHeaders$1.from(context.headers); let data = context.data; - utils$1.forEach(fns, function transform(fn) { + utils.forEach(fns, function transform(fn) { data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); }); @@ -21017,7 +20915,7 @@ function CanceledError(message, config, request) { this.name = 'CanceledError'; } -utils$1.inherits(CanceledError, AxiosError, { +utils.inherits(CanceledError, AxiosError, { __CANCEL__: true }); @@ -21069,7 +20967,7 @@ function isAbsoluteURL(url) { */ function combineURLs(baseURL, relativeURL) { return relativeURL - ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; } @@ -21090,7 +20988,7 @@ function buildFullPath(baseURL, requestedURL) { return requestedURL; } -const VERSION = "1.7.4"; +const VERSION = "1.6.0"; function parseProtocol(url) { const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); @@ -21145,11 +21043,93 @@ 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{ constructor(options) { - options = utils$1.toFlatObject(options, { + options = utils.toFlatObject(options, { maxRate: 0, chunkSize: 64 * 1024, minChunkSize: 100, @@ -21157,15 +21137,19 @@ class AxiosTransformStream extends stream__default["default"].Transform{ ticksRate: 2, samplesCount: 15 }, null, (prop, source) => { - return !utils$1.isUndefined(source[prop]); + return !utils.isUndefined(source[prop]); }); super({ 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, @@ -21177,6 +21161,8 @@ 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) { @@ -21184,6 +21170,38 @@ 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) { @@ -21197,6 +21215,7 @@ class AxiosTransformStream extends stream__default["default"].Transform{ } _transform(chunk, encoding, callback) { + const self = this; const internals = this[kInternals]; const maxRate = internals.maxRate; @@ -21208,14 +21227,16 @@ class AxiosTransformStream extends stream__default["default"].Transform{ const bytesThreshold = (maxRate / divider); const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; - const pushChunk = (_chunk, _callback) => { + function pushChunk(_chunk, _callback) { const bytes = Buffer.byteLength(_chunk); internals.bytesSeen += bytes; internals.bytes += bytes; - internals.isCaptured && this.emit('progress', internals.bytesSeen); + if (internals.isCaptured) { + internals.updateProgress(); + } - if (this.push(_chunk)) { + if (self.push(_chunk)) { process.nextTick(_callback); } else { internals.onReadCallback = () => { @@ -21223,7 +21244,7 @@ class AxiosTransformStream extends stream__default["default"].Transform{ process.nextTick(_callback); }; } - }; + } const transformChunk = (_chunk, _callback) => { const chunkSize = Buffer.byteLength(_chunk); @@ -21280,6 +21301,11 @@ class AxiosTransformStream extends stream__default["default"].Transform{ } }); } + + setLength(length) { + this[kInternals].length = +length; + return this; + } } const AxiosTransformStream$1 = AxiosTransformStream; @@ -21300,7 +21326,7 @@ const readBlob = async function* (blob) { const readBlob$1 = readBlob; -const BOUNDARY_ALPHABET = utils$1.ALPHABET.ALPHA_DIGIT + '-_'; +const BOUNDARY_ALPHABET = utils.ALPHABET.ALPHA_DIGIT + '-_'; const textEncoder = new util.TextEncoder(); @@ -21311,7 +21337,7 @@ const CRLF_BYTES_COUNT = 2; class FormDataPart { constructor(name, value) { const {escapeName} = this.constructor; - const isStringValue = utils$1.isString(value); + const isStringValue = utils.isString(value); let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : '' @@ -21338,7 +21364,7 @@ class FormDataPart { const {value} = this; - if(utils$1.isTypedArray(value)) { + if(utils.isTypedArray(value)) { yield value; } else { yield* readBlob$1(value); @@ -21360,10 +21386,10 @@ const formDataToStream = (form, headersHandler, options) => { const { tag = 'form-data-boundary', size = 25, - boundary = tag + '-' + utils$1.generateString(size, BOUNDARY_ALPHABET) + boundary = tag + '-' + utils.generateString(size, BOUNDARY_ALPHABET) } = options || {}; - if(!utils$1.isFormData(form)) { + if(!utils.isFormData(form)) { throw TypeError('FormData instance required'); } @@ -21383,7 +21409,7 @@ const formDataToStream = (form, headersHandler, options) => { contentLength += boundaryBytes.byteLength * parts.length; - contentLength = utils$1.toFiniteNumber(contentLength); + contentLength = utils.toFiniteNumber(contentLength); const computedHeaders = { 'Content-Type': `multipart/form-data; boundary=${boundary}` @@ -21433,7 +21459,7 @@ class ZlibHeaderTransformStream extends stream__default["default"].Transform { const ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream; const callbackify = (fn, reducer) => { - return utils$1.isAsyncFn(fn) ? function (...args) { + return utils.isAsyncFn(fn) ? function (...args) { const cb = args.pop(); fn.apply(this, args).then((value) => { try { @@ -21447,142 +21473,6 @@ 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 @@ -21593,7 +21483,7 @@ const brotliOptions = { finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH }; -const isBrotliSupported = utils$1.isFunction(zlib__default["default"].createBrotliDecompress); +const isBrotliSupported = utils.isFunction(zlib__default["default"].createBrotliDecompress); const {http: httpFollow, https: httpsFollow} = followRedirects__default["default"]; @@ -21603,14 +21493,6 @@ 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. @@ -21619,12 +21501,12 @@ const flushOnFinish = (stream, [throttled, flush]) => { * * @returns {Object} */ -function dispatchBeforeRedirect(options, responseDetails) { +function dispatchBeforeRedirect(options) { if (options.beforeRedirects.proxy) { options.beforeRedirects.proxy(options); } if (options.beforeRedirects.config) { - options.beforeRedirects.config(options, responseDetails); + options.beforeRedirects.config(options); } } @@ -21681,7 +21563,7 @@ function setProxy(options, configProxy, location) { }; } -const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process'; +const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process'; // temporary hotfix @@ -21711,7 +21593,7 @@ const wrapAsync = (asyncExecutor) => { }; const resolveFamily = ({address, family}) => { - if (!utils$1.isString(address)) { + if (!utils.isString(address)) { throw TypeError('address must be a string'); } return ({ @@ -21720,7 +21602,7 @@ const resolveFamily = ({address, family}) => { }); }; -const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {address, family}); +const buildAddressEntry = (address, family) => resolveFamily(utils.isObject(address) ? address : {address, family}); /*eslint consistent-return:0*/ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { @@ -21733,15 +21615,11 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { let req; if (lookup) { - const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]); + const _lookup = callbackify$1(lookup, (value) => utils.isArray(value) ? value : [value]); // hotfix to support opt.all option which is required for node 20.x lookup = (hostname, opt, cb) => { _lookup(hostname, opt, (err, arg0, arg1) => { - if (err) { - return cb(err); - } - - const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; + const addresses = utils.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); }); @@ -21749,7 +21627,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } // temporary internal emitter until the AxiosRequest class will be implemented - const emitter = new events.EventEmitter(); + const emitter = new EventEmitter__default["default"](); const onFinished = () => { if (config.cancelToken) { @@ -21786,7 +21664,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // Parse url const fullPath = buildFullPath(config.baseURL, config.url); - const parsed = new URL(fullPath, utils$1.hasBrowserEnv ? platform.origin : undefined); + const parsed = new URL(fullPath, 'http://localhost'); const protocol = parsed.protocol || supportedProtocols[0]; if (protocol === 'data:') { @@ -21813,7 +21691,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { convertedData = convertedData.toString(responseEncoding); if (!responseEncoding || responseEncoding === 'utf8') { - convertedData = utils$1.stripBOM(convertedData); + convertedData = utils.stripBOM(convertedData); } } else if (responseType === 'stream') { convertedData = stream__default["default"].Readable.from(convertedData); @@ -21844,13 +21722,14 @@ 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 {onUploadProgress, onDownloadProgress} = config; + const onDownloadProgress = config.onDownloadProgress; + const onUploadProgress = config.onUploadProgress; const maxRate = config.maxRate; let maxUploadRate = undefined; let maxDownloadRate = undefined; // support for spec compliant FormData objects - if (utils$1.isSpecCompliantForm(data)) { + if (utils.isSpecCompliantForm(data)) { const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); data = formDataToStream$1(data, (formHeaders) => { @@ -21860,7 +21739,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { boundary: userBoundary && userBoundary[1] || undefined }); // support for https://www.npmjs.com/package/form-data api - } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) { + } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { headers.set(data.getHeaders()); if (!headers.hasContentLength()) { @@ -21871,14 +21750,14 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } catch (e) { } } - } else if (utils$1.isBlob(data)) { + } else if (utils.isBlob(data)) { data.size && headers.setContentType(data.type || 'application/octet-stream'); headers.setContentLength(data.size || 0); data = stream__default["default"].Readable.from(readBlob$1(data)); - } else if (data && !utils$1.isStream(data)) { - if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) { + } else if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) ; else if (utils.isArrayBuffer(data)) { data = Buffer.from(new Uint8Array(data)); - } else if (utils$1.isString(data)) { + } else if (utils.isString(data)) { data = Buffer.from(data, 'utf-8'); } else { return reject(new AxiosError( @@ -21900,9 +21779,9 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } } - const contentLength = utils$1.toFiniteNumber(headers.getContentLength()); + const contentLength = utils.toFiniteNumber(headers.getContentLength()); - if (utils$1.isArray(maxRate)) { + if (utils.isArray(maxRate)) { maxUploadRate = maxRate[0]; maxDownloadRate = maxRate[1]; } else { @@ -21910,21 +21789,20 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } if (data && (onUploadProgress || maxUploadRate)) { - if (!utils$1.isStream(data)) { + if (!utils.isStream(data)) { data = stream__default["default"].Readable.from(data, {objectMode: false}); } data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ - maxRate: utils$1.toFiniteNumber(maxUploadRate) - })], utils$1.noop); + length: contentLength, + maxRate: utils.toFiniteNumber(maxUploadRate) + })], utils.noop); - onUploadProgress && data.on('progress', flushOnFinish( - data, - progressEventDecorator( - contentLength, - progressEventReducer(asyncDecorator(onUploadProgress), false, 3) - ) - )); + onUploadProgress && data.on('progress', progress => { + onUploadProgress(Object.assign(progress, { + upload: true + })); + }); } // HTTP basic authentication @@ -21977,7 +21855,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { }; // cacheable-lookup integration hotfix - !utils$1.isUndefined(lookup) && (options.lookup = lookup); + !utils.isUndefined(lookup) && (options.lookup = lookup); if (config.socketPath) { options.socketPath = config.socketPath; @@ -22023,18 +21901,17 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { const responseLength = +res.headers['content-length']; - if (onDownloadProgress || maxDownloadRate) { + if (onDownloadProgress) { const transformStream = new AxiosTransformStream$1({ - maxRate: utils$1.toFiniteNumber(maxDownloadRate) + length: utils.toFiniteNumber(responseLength), + maxRate: utils.toFiniteNumber(maxDownloadRate) }); - onDownloadProgress && transformStream.on('progress', flushOnFinish( - transformStream, - progressEventDecorator( - responseLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) - ) - )); + onDownloadProgress && transformStream.on('progress', progress => { + onDownloadProgress(Object.assign(progress, { + download: true + })); + }); streams.push(transformStream); } @@ -22082,7 +21959,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } } - responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0]; + responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils.noop) : streams[0]; const offListeners = stream__default["default"].finished(responseStream, () => { offListeners(); @@ -22144,7 +22021,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { if (responseType !== 'arraybuffer') { responseData = responseData.toString(responseEncoding); if (!responseEncoding || responseEncoding === 'utf8') { - responseData = utils$1.stripBOM(responseData); + responseData = utils.stripBOM(responseData); } } response.data = responseData; @@ -22221,7 +22098,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // Send the request - if (utils$1.isStream(data)) { + if (utils.isStream(data)) { let ended = false; let errored = false; @@ -22247,7 +22124,55 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { }); }; -const isURLSameOrigin = platform.hasStandardBrowserEnv ? +const cookies = platform.isStandardBrowserEnv ? + +// Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + const cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); + + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } + + if (utils.isString(path)) { + cookie.push('path=' + path); + } + + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } + + if (secure === true) { + cookie.push('secure'); + } + + document.cookie = cookie.join('; '); + }, + + read: function read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + 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() {} + }; + })(); + +const isURLSameOrigin = platform.isStandardBrowserEnv ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. @@ -22257,7 +22182,7 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ? let originURL; /** - * Parse a URL to discover its components + * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} @@ -22297,7 +22222,7 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ? * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { - const parsed = (utils$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; @@ -22310,222 +22235,81 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ? }; })(); -const cookies = platform.hasStandardBrowserEnv ? +function progressEventReducer(listener, isDownloadStream) { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); - // Standard browser envs support document.cookie - { - write(name, value, expires, path, domain, secure) { - const cookie = [name + '=' + encodeURIComponent(value)]; + 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; - utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); + bytesNotified = loaded; - utils$1.isString(path) && cookie.push('path=' + path); + 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(domain) && cookie.push('domain=' + domain); + data[isDownloadStream ? 'download' : 'upload'] = true; - 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() {} + listener(data); }; - -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 resolveConfig = (config) => { - const newConfig = mergeConfig({}, config); - - let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; - - 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)); - - if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { - // Add xsrf header - const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); - - if (xsrfValue) { - headers.set(xsrfHeaderName, xsrfValue); - } - } - } - - return newConfig; -}; - 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 requestData = config.data; + const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); + const responseType = config.responseType; let onCanceled; - let uploadThrottled, downloadThrottled; - let flushUpload, flushDownload; - function done() { - flushUpload && flushUpload(); // flush events - flushDownload && flushDownload(); // flush events + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } - _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); + } + } - _config.signal && _config.signal.removeEventListener('abort', onCanceled); + let contentType; + + if (utils.isFormData(requestData)) { + if (platform.isStandardBrowserEnv || platform.isStandardBrowserWebWorkerEnv) { + requestHeaders.setContentType(false); // Let the browser set it + } else if(!requestHeaders.getContentType(/^\s*multipart\/form-data/)){ + requestHeaders.setContentType('multipart/form-data'); // mobile/desktop app frameworks + } else if(utils.isString(contentType = requestHeaders.getContentType())){ + // fix semicolon duplication issue for ReactNative FormData implementation + requestHeaders.setContentType(contentType.replace(/^\s*(multipart\/form-data);+/, '$1')); + } } let request = new XMLHttpRequest(); - request.open(_config.method.toUpperCase(), _config.url, true); + // 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 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; + request.timeout = config.timeout; function onloadend() { if (!request) { @@ -22605,10 +22389,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, @@ -22620,42 +22404,50 @@ 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.isStandardBrowserEnv) { + // Add xsrf header + // regarding CVE-2023-45857 config.withCredentials condition was removed temporarily + const xsrfValue = isURLSameOrigin(fullPath) && 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); // Add headers to the request if ('setRequestHeader' in request) { - utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { request.setRequestHeader(key, val); }); } // Add withCredentials to request if needed - if (!utils$1.isUndefined(_config.withCredentials)) { - request.withCredentials = !!_config.withCredentials; + if (!utils.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 (onDownloadProgress) { - ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); - request.addEventListener('progress', downloadThrottled); + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true)); } // Not all browsers support upload events - if (onUploadProgress && request.upload) { - ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); - - request.upload.addEventListener('progress', uploadThrottled); - - request.upload.addEventListener('loadend', flushUpload); + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress)); } - if (_config.cancelToken || _config.signal) { + if (config.cancelToken || config.signal) { // Handle cancellation // eslint-disable-next-line func-names onCanceled = cancel => { @@ -22667,13 +22459,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(_config.url); + const protocol = parseProtocol(fullPath); if (protocol && platform.protocols.indexOf(protocol) === -1) { reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); @@ -22686,342 +22478,12 @@ 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, - fetch: fetchAdapter + xhr: xhrAdapter }; -utils$1.forEach(knownAdapters, (fn, value) => { +utils.forEach(knownAdapters, (fn, value) => { if (fn) { try { Object.defineProperty(fn, 'name', {value}); @@ -23034,11 +22496,11 @@ utils$1.forEach(knownAdapters, (fn, value) => { const renderReason = (reason) => `- ${reason}`; -const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; +const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false; const adapters = { getAdapter: (adapters) => { - adapters = utils$1.isArray(adapters) ? adapters : [adapters]; + adapters = utils.isArray(adapters) ? adapters : [adapters]; const {length} = adapters; let nameOrAdapter; @@ -23162,6 +22624,107 @@ 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.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge.call({caseless}, target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, caseless) { + if (!utils.isUndefined(b)) { + return getMergedValue(a, b, caseless); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a, caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils.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, + 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.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; +} + const validators$1 = {}; // eslint-disable-next-line func-names @@ -23275,34 +22838,7 @@ class Axios { * * @returns {Promise} The Promise to be fulfilled */ - async request(configOrUrl, config) { - try { - return await this._request(configOrUrl, config); - } catch (err) { - if (err instanceof Error) { - let dummy; - - Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error()); - - // slice off the Error: ... line - const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; - 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 - } - } - - throw err; - } - } - - _request(configOrUrl, config) { + request(configOrUrl, config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof configOrUrl === 'string') { @@ -23325,7 +22861,7 @@ class Axios { } if (paramsSerializer != null) { - if (utils$1.isFunction(paramsSerializer)) { + if (utils.isFunction(paramsSerializer)) { config.paramsSerializer = { serialize: paramsSerializer }; @@ -23341,12 +22877,12 @@ class Axios { config.method = (config.method || this.defaults.method || 'get').toLowerCase(); // Flatten headers - let contextHeaders = headers && utils$1.merge( + let contextHeaders = headers && utils.merge( headers.common, headers[config.method] ); - headers && utils$1.forEach( + headers && utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], (method) => { delete headers[method]; @@ -23433,7 +22969,7 @@ class Axios { } // Provide aliases for supported request methods -utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { @@ -23444,7 +22980,7 @@ utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoDa }; }); -utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ function generateHTTPMethod(isForm) { @@ -23620,7 +23156,7 @@ function spread(callback) { * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ function isAxiosError(payload) { - return utils$1.isObject(payload) && (payload.isAxiosError === true); + return utils.isObject(payload) && (payload.isAxiosError === true); } const HttpStatusCode = { @@ -23707,10 +23243,10 @@ function createInstance(defaultConfig) { const instance = bind(Axios$1.prototype.request, context); // Copy axios.prototype to instance - utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); + utils.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); // Copy context to instance - utils$1.extend(instance, context, null, {allOwnKeys: true}); + utils.extend(instance, context, null, {allOwnKeys: true}); // Factory for creating new instances instance.create = function create(instanceConfig) { @@ -23754,7 +23290,7 @@ axios.mergeConfig = mergeConfig; axios.AxiosHeaders = AxiosHeaders$1; -axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); +axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); axios.getAdapter = adapters.getAdapter; diff --git a/examples/on-pr-merge/automated-workflow.yaml b/examples/on-pr-merge/automated-workflow.yaml index 191a21f..751bbb5 100644 --- a/examples/on-pr-merge/automated-workflow.yaml +++ b/examples/on-pr-merge/automated-workflow.yaml @@ -35,7 +35,7 @@ jobs: fail-fast: true steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 - name: Backporting