diff --git a/.gitignore b/.gitignore index e7f36ba..2bc70ed 100644 --- a/.gitignore +++ b/.gitignore @@ -104,3 +104,5 @@ typings/ # TernJS port file .tern-port + +.DS_Store \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index 49ab1d2..2a6e3f0 100644 --- a/dist/index.js +++ b/dist/index.js @@ -10135,7 +10135,7 @@ module.exports = require("zlib"); /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Axios v1.3.3 Copyright (c) 2023 Matt Zabriskie and contributors +// Axios v1.1.3 Copyright (c) 2022 Matt Zabriskie and contributors const FormData$1 = __nccwpck_require__(4334); @@ -10143,7 +10143,6 @@ const url = __nccwpck_require__(7310); const proxyFromEnv = __nccwpck_require__(3329); const http = __nccwpck_require__(3685); const https = __nccwpck_require__(5687); -const util = __nccwpck_require__(3837); const followRedirects = __nccwpck_require__(7707); const zlib = __nccwpck_require__(9796); const stream = __nccwpck_require__(2781); @@ -10155,7 +10154,6 @@ const FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData$1); const url__default = /*#__PURE__*/_interopDefaultLegacy(url); const http__default = /*#__PURE__*/_interopDefaultLegacy(http); const https__default = /*#__PURE__*/_interopDefaultLegacy(https); -const util__default = /*#__PURE__*/_interopDefaultLegacy(util); const followRedirects__default = /*#__PURE__*/_interopDefaultLegacy(followRedirects); const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); const stream__default = /*#__PURE__*/_interopDefaultLegacy(stream); @@ -10393,7 +10391,7 @@ const trim = (str) => str.trim ? * @param {Function} fn The callback to invoke for each item * * @param {Boolean} [allOwnKeys = false] - * @returns {any} + * @returns {void} */ function forEach(obj, fn, {allOwnKeys = false} = {}) { // Don't bother if no value provided @@ -10428,28 +10426,6 @@ function forEach(obj, fn, {allOwnKeys = false} = {}) { } } -function findKey(obj, key) { - key = key.toLowerCase(); - const keys = Object.keys(obj); - let i = keys.length; - let _key; - while (i-- > 0) { - _key = keys[i]; - if (key === _key.toLowerCase()) { - return _key; - } - } - return null; -} - -const _global = (() => { - /*eslint no-undef:0*/ - if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) -})(); - -const isContextDefined = (context) => !isUndefined(context) && context !== _global; - /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. @@ -10469,18 +10445,16 @@ const isContextDefined = (context) => !isUndefined(context) && context !== _glob * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { - const {caseless} = isContextDefined(this) && this || {}; const result = {}; const assignValue = (val, key) => { - const targetKey = caseless && findKey(result, key) || key; - if (isPlainObject(result[targetKey]) && isPlainObject(val)) { - result[targetKey] = merge(result[targetKey], val); + if (isPlainObject(result[key]) && isPlainObject(val)) { + result[key] = merge(result[key], val); } else if (isPlainObject(val)) { - result[targetKey] = merge({}, val); + result[key] = merge({}, val); } else if (isArray(val)) { - result[targetKey] = val.slice(); + result[key] = val.slice(); } else { - result[targetKey] = val; + result[key] = val; } }; @@ -10677,7 +10651,7 @@ const matchAll = (regExp, str) => { const isHTMLForm = kindOfTest('HTMLFormElement'); const toCamelCase = str => { - return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + return str.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { return p1.toUpperCase() + p2; } @@ -10716,11 +10690,6 @@ const reduceDescriptors = (obj, reducer) => { const freezeMethods = (obj) => { reduceDescriptors(obj, (descriptor, name) => { - // skip restricted props in strict mode - if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { - return false; - } - const value = obj[name]; if (!isFunction(value)) return; @@ -10734,7 +10703,7 @@ const freezeMethods = (obj) => { if (!descriptor.set) { descriptor.set = () => { - throw Error('Can not rewrite read-only method \'' + name + '\''); + throw Error('Can not read-only method \'' + name + '\''); }; } }); @@ -10761,68 +10730,6 @@ const toFiniteNumber = (value, defaultValue) => { return Number.isFinite(value) ? value : defaultValue; }; -const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; - -const DIGIT = '0123456789'; - -const ALPHABET = { - DIGIT, - ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT -}; - -const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { - let str = ''; - const {length} = alphabet; - while (size--) { - str += alphabet[Math.random() * length|0]; - } - - return str; -}; - -/** - * If the thing is a FormData object, return true, otherwise return false. - * - * @param {unknown} thing - The thing to check. - * - * @returns {boolean} - */ -function isSpecCompliantForm(thing) { - return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); -} - -const toJSONObject = (obj) => { - const stack = new Array(10); - - const visit = (source, i) => { - - if (isObject(source)) { - if (stack.indexOf(source) >= 0) { - return; - } - - if(!('toJSON' in source)) { - stack[i] = source; - const target = isArray(source) ? [] : {}; - - forEach(source, (value, key) => { - const reducedValue = visit(value, i + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); - - stack[i] = undefined; - - return target; - } - } - - return source; - }; - - return visit(obj, 0); -}; - const utils = { isArray, isArrayBuffer, @@ -10865,14 +10772,7 @@ const utils = { toObjectSet, toCamelCase, noop, - toFiniteNumber, - findKey, - global: _global, - isContextDefined, - ALPHABET, - generateString, - isSpecCompliantForm, - toJSONObject + toFiniteNumber }; /** @@ -10918,7 +10818,7 @@ utils.inherits(AxiosError, Error, { columnNumber: this.columnNumber, stack: this.stack, // Axios - config: utils.toJSONObject(this.config), + config: this.config, code: this.code, status: this.response && this.response.status ? this.response.status : null }; @@ -11025,6 +10925,17 @@ const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) { return /^is[A-Z]/.test(prop); }); +/** + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} + */ +function isSpecCompliant(thing) { + return thing && utils.isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]; +} + /** * Convert a data object to FormData * @@ -11072,7 +10983,7 @@ 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.isSpecCompliantForm(formData); + const useBlob = _Blob && isSpecCompliant(formData); if (!utils.isFunction(visitor)) { throw new TypeError('visitor must be a function'); @@ -11117,7 +11028,7 @@ function toFormData(obj, formData, options) { value = JSON.stringify(value); } else if ( (utils.isArray(value) && isFlatArray(value)) || - ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)) + (utils.isFileList(value) || utils.endsWith(key, '[]') && (arr = utils.toArray(value)) )) { // eslint-disable-next-line no-param-reassign key = removeBrackets(key); @@ -11359,8 +11270,6 @@ class InterceptorManager { } } -const InterceptorManager$1 = InterceptorManager; - const transitionalDefaults = { silentJSONParsing: true, forcedJSONParsing: true, @@ -11479,162 +11388,148 @@ function formDataToJSON(formData) { return null; } -const DEFAULT_CONTENT_TYPE = { - 'Content-Type': undefined -}; - /** - * It takes a string, tries to parse it, and if it fails, it returns the stringified version - * of the input + * Resolve or reject a Promise based on response status. * - * @param {any} rawValue - The value to be stringified. - * @param {Function} parser - A function that parses a string into a JavaScript object. - * @param {Function} encoder - A function that takes a value and returns a string. + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. * - * @returns {string} A stringified version of the rawValue. + * @returns {object} The response. */ -function stringifySafely(rawValue, parser, encoder) { - if (utils.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } +function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + 'Request failed with status code ' + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); } +} - return (encoder || JSON.stringify)(rawValue); +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); } -const defaults = { +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * + * @returns {string} The combined URL + */ +function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +} - transitional: transitionalDefaults, +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * + * @returns {string} The combined full path + */ +function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} - adapter: ['xhr', 'http'], +const VERSION = "1.1.3"; - transformRequest: [function transformRequest(data, headers) { - const contentType = headers.getContentType() || ''; - const hasJSONContentType = contentType.indexOf('application/json') > -1; - const isObjectPayload = utils.isObject(data); +/** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ +function CanceledError(message, config, request) { + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); + this.name = 'CanceledError'; +} - if (isObjectPayload && utils.isHTMLForm(data)) { - data = new FormData(data); - } +utils.inherits(CanceledError, AxiosError, { + __CANCEL__: true +}); - const isFormData = utils.isFormData(data); +function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +} - if (isFormData) { - if (!hasJSONContentType) { - return data; - } - return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; - } +const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; - if (utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isFile(data) || - utils.isBlob(data) - ) { - return data; - } - if (utils.isArrayBufferView(data)) { - return data.buffer; - } - if (utils.isURLSearchParams(data)) { - headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); - return data.toString(); - } +/** + * Parse data uri to a Buffer or Blob + * + * @param {String} uri + * @param {?Boolean} asBlob + * @param {?Object} options + * @param {?Function} options.Blob + * + * @returns {Buffer|Blob} + */ +function fromDataURI(uri, asBlob, options) { + const _Blob = options && options.Blob || platform.classes.Blob; + const protocol = parseProtocol(uri); - let isFileList; + if (asBlob === undefined && _Blob) { + asBlob = true; + } - if (isObjectPayload) { - if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { - return toURLEncodedForm(data, this.formSerializer).toString(); - } + if (protocol === 'data') { + uri = protocol.length ? uri.slice(protocol.length + 1) : uri; - if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { - const _FormData = this.env && this.env.FormData; + const match = DATA_URL_PATTERN.exec(uri); - return toFormData( - isFileList ? {'files[]': data} : data, - _FormData && new _FormData(), - this.formSerializer - ); - } + if (!match) { + throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL); } - if (isObjectPayload || hasJSONContentType ) { - headers.setContentType('application/json', false); - return stringifySafely(data); - } + const mime = match[1]; + const isBase64 = match[2]; + const body = match[3]; + const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8'); - return data; - }], + if (asBlob) { + if (!_Blob) { + throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT); + } - transformResponse: [function transformResponse(data) { - const transitional = this.transitional || defaults.transitional; - const forcedJSONParsing = transitional && transitional.forcedJSONParsing; - const JSONRequested = this.responseType === 'json'; + return new _Blob([buffer], {type: mime}); + } - if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { - const silentJSONParsing = transitional && transitional.silentJSONParsing; - const strictJSONParsing = !silentJSONParsing && JSONRequested; + return buffer; + } - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e; - } - } - } - - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - - maxContentLength: -1, - maxBodyLength: -1, - - env: { - FormData: platform.classes.FormData, - Blob: platform.classes.Blob - }, - - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' - } - } -}; - -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults.headers[method] = {}; -}); - -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); -}); - -const defaults$1 = defaults; + throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); +} // RawAxiosHeaders whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers @@ -11689,6 +11584,7 @@ const parseHeaders = rawHeaders => { }; const $internals = Symbol('internals'); +const $defaults = Symbol('defaults'); function normalizeHeader(header) { return header && String(header).trim().toLowerCase(); @@ -11714,19 +11610,11 @@ function parseTokens(str) { return tokens; } -function isValidHeaderName(str) { - return /^[-_a-zA-Z]+$/.test(str.trim()); -} - -function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { +function matchHeaderValue(context, value, header, filter) { if (utils.isFunction(filter)) { return filter.call(this, value, header); } - if (isHeaderNameFilter) { - value = header; - } - if (!utils.isString(value)) return; if (utils.isString(filter)) { @@ -11758,12 +11646,27 @@ function buildAccessors(obj, header) { }); } -class AxiosHeaders { - constructor(headers) { - headers && this.set(headers); +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } } + return null; +} + +function AxiosHeaders(headers, defaults) { + headers && this.set(headers); + this[$defaults] = defaults || null; +} - set(header, valueOrRewrite, rewrite) { +Object.assign(AxiosHeaders.prototype, { + set: function(header, valueOrRewrite, rewrite) { const self = this; function setHeader(_value, _header, _rewrite) { @@ -11773,70 +11676,69 @@ class AxiosHeaders { throw new Error('header name must be a non-empty string'); } - const key = utils.findKey(self, lHeader); + const key = findKey(self, lHeader); - if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { - self[key || _header] = normalizeValue(_value); + if (key && _rewrite !== true && (self[key] === false || _rewrite === false)) { + return; } - } - const setHeaders = (headers, _rewrite) => - utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + self[key || _header] = normalizeValue(_value); + } - if (utils.isPlainObject(header) || header instanceof this.constructor) { - setHeaders(header, valueOrRewrite); - } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { - setHeaders(parseHeaders(header), valueOrRewrite); + if (utils.isPlainObject(header)) { + utils.forEach(header, (_value, _header) => { + setHeader(_value, _header, valueOrRewrite); + }); } else { - header != null && setHeader(valueOrRewrite, header, rewrite); + setHeader(valueOrRewrite, header, rewrite); } return this; - } + }, - get(header, parser) { + get: function(header, parser) { header = normalizeHeader(header); - if (header) { - const key = utils.findKey(this, header); + if (!header) return undefined; - if (key) { - const value = this[key]; + const key = findKey(this, header); - if (!parser) { - return value; - } + if (key) { + const value = this[key]; - if (parser === true) { - return parseTokens(value); - } + if (!parser) { + return value; + } - if (utils.isFunction(parser)) { - return parser.call(this, value, key); - } + if (parser === true) { + return parseTokens(value); + } - if (utils.isRegExp(parser)) { - return parser.exec(value); - } + if (utils.isFunction(parser)) { + return parser.call(this, value, key); + } - throw new TypeError('parser must be boolean|regexp|function'); + if (utils.isRegExp(parser)) { + return parser.exec(value); } + + throw new TypeError('parser must be boolean|regexp|function'); } - } + }, - has(header, matcher) { + has: function(header, matcher) { header = normalizeHeader(header); if (header) { - const key = utils.findKey(this, header); + const key = findKey(this, header); - return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + return !!(key && (!matcher || matchHeaderValue(this, this[key], key, matcher))); } return false; - } + }, - delete(header, matcher) { + delete: function(header, matcher) { const self = this; let deleted = false; @@ -11844,7 +11746,7 @@ class AxiosHeaders { _header = normalizeHeader(_header); if (_header) { - const key = utils.findKey(self, _header); + const key = findKey(self, _header); if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { delete self[key]; @@ -11861,30 +11763,18 @@ class AxiosHeaders { } return deleted; - } - - clear(matcher) { - const keys = Object.keys(this); - let i = keys.length; - let deleted = false; - - while (i--) { - const key = keys[i]; - if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { - delete this[key]; - deleted = true; - } - } + }, - return deleted; - } + clear: function() { + return Object.keys(this).forEach(this.delete.bind(this)); + }, - normalize(format) { + normalize: function(format) { const self = this; const headers = {}; utils.forEach(this, (value, header) => { - const key = utils.findKey(headers, header); + const key = findKey(headers, header); if (key) { self[key] = normalizeValue(value); @@ -11904,47 +11794,30 @@ class AxiosHeaders { }); return this; - } - - concat(...targets) { - return this.constructor.concat(this, ...targets); - } + }, - toJSON(asStrings) { + toJSON: function(asStrings) { const obj = Object.create(null); - utils.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); - }); + utils.forEach(Object.assign({}, this[$defaults] || null, this), + (value, header) => { + if (value == null || value === false) return; + obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value; + }); return obj; } +}); - [Symbol.iterator]() { - return Object.entries(this.toJSON())[Symbol.iterator](); - } - - toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); - } - - get [Symbol.toStringTag]() { - return 'AxiosHeaders'; - } - - static from(thing) { +Object.assign(AxiosHeaders, { + from: function(thing) { + if (utils.isString(thing)) { + return new this(parseHeaders(thing)); + } return thing instanceof this ? thing : new this(thing); - } - - static concat(first, ...targets) { - const computed = new this(first); - - targets.forEach((target) => computed.set(target)); - - return computed; - } + }, - static accessor(header) { + accessor: function(header) { const internals = this[$internals] = (this[$internals] = { accessors: {} }); @@ -11965,185 +11838,13 @@ class AxiosHeaders { return this; } -} +}); -AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); +AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent']); utils.freezeMethods(AxiosHeaders.prototype); utils.freezeMethods(AxiosHeaders); -const AxiosHeaders$1 = AxiosHeaders; - -/** - * Transform the data for a request or a response - * - * @param {Array|Function} fns A single function or Array of functions - * @param {?Object} response The response object - * - * @returns {*} The resulting transformed data - */ -function transformData(fns, response) { - const config = this || defaults$1; - const context = response || config; - const headers = AxiosHeaders$1.from(context.headers); - let data = context.data; - - utils.forEach(fns, function transform(fn) { - data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); - }); - - headers.normalize(); - - return data; -} - -function isCancel(value) { - return !!(value && value.__CANCEL__); -} - -/** - * A `CanceledError` is an object that is thrown when an operation is canceled. - * - * @param {string=} message The message. - * @param {Object=} config The config. - * @param {Object=} request The request. - * - * @returns {CanceledError} The created error. - */ -function CanceledError(message, config, request) { - // eslint-disable-next-line no-eq-null,eqeqeq - AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); - this.name = 'CanceledError'; -} - -utils.inherits(CanceledError, AxiosError, { - __CANCEL__: true -}); - -/** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - * - * @returns {object} The response. - */ -function settle(resolve, reject, response) { - const validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(new AxiosError( - 'Request failed with status code ' + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); - } -} - -/** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ -function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); -} - -/** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * - * @returns {string} The combined URL - */ -function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; -} - -/** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * - * @returns {string} The combined full path - */ -function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; -} - -const VERSION = "1.3.3"; - -function parseProtocol(url) { - const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); - return match && match[1] || ''; -} - -const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; - -/** - * Parse data uri to a Buffer or Blob - * - * @param {String} uri - * @param {?Boolean} asBlob - * @param {?Object} options - * @param {?Function} options.Blob - * - * @returns {Buffer|Blob} - */ -function fromDataURI(uri, asBlob, options) { - const _Blob = options && options.Blob || platform.classes.Blob; - const protocol = parseProtocol(uri); - - if (asBlob === undefined && _Blob) { - asBlob = true; - } - - if (protocol === 'data') { - uri = protocol.length ? uri.slice(protocol.length + 1) : uri; - - const match = DATA_URL_PATTERN.exec(uri); - - if (!match) { - throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL); - } - - const mime = match[1]; - const isBase64 = match[2]; - const body = match[3]; - const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8'); - - if (asBlob) { - if (!_Blob) { - throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT); - } - - return new _Blob([buffer], {type: mime}); - } - - return buffer; - } - - throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); -} - /** * Throttle decorator * @param {Function} fn @@ -12222,7 +11923,7 @@ function speedometer(samplesCount, min) { const passed = startedAt && now - startedAt; - return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; }; } @@ -12403,172 +12104,12 @@ class AxiosTransformStream extends stream__default["default"].Transform{ }); } - setLength(length) { - this[kInternals].length = +length; - return this; - } -} - -const AxiosTransformStream$1 = AxiosTransformStream; - -const {asyncIterator} = Symbol; - -const readBlob = async function* (blob) { - if (blob.stream) { - yield* blob.stream(); - } else if (blob.arrayBuffer) { - yield await blob.arrayBuffer(); - } else if (blob[asyncIterator]) { - yield* blob[asyncIterator](); - } else { - yield blob; - } -}; - -const readBlob$1 = readBlob; - -const BOUNDARY_ALPHABET = utils.ALPHABET.ALPHA_DIGIT + '-_'; - -const textEncoder = new util.TextEncoder(); - -const CRLF = '\r\n'; -const CRLF_BYTES = textEncoder.encode(CRLF); -const CRLF_BYTES_COUNT = 2; - -class FormDataPart { - constructor(name, value) { - const {escapeName} = this.constructor; - const isStringValue = utils.isString(value); - - let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ - !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : '' - }${CRLF}`; - - if (isStringValue) { - value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); - } else { - headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; - } - - this.headers = textEncoder.encode(headers + CRLF); - - this.contentLength = isStringValue ? value.byteLength : value.size; - - this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; - - this.name = name; - this.value = value; - } - - async *encode(){ - yield this.headers; - - const {value} = this; - - if(utils.isTypedArray(value)) { - yield value; - } else { - yield* readBlob$1(value); - } - - yield CRLF_BYTES; - } - - static escapeName(name) { - return String(name).replace(/[\r\n"]/g, (match) => ({ - '\r' : '%0D', - '\n' : '%0A', - '"' : '%22', - }[match])); - } -} - -const formDataToStream = (form, headersHandler, options) => { - const { - tag = 'form-data-boundary', - size = 25, - boundary = tag + '-' + utils.generateString(size, BOUNDARY_ALPHABET) - } = options || {}; - - if(!utils.isFormData(form)) { - throw TypeError('FormData instance required'); - } - - if (boundary.length < 1 || boundary.length > 70) { - throw Error('boundary must be 10-70 characters long') - } - - const boundaryBytes = textEncoder.encode('--' + boundary + CRLF); - const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF); - let contentLength = footerBytes.byteLength; - - const parts = Array.from(form.entries()).map(([name, value]) => { - const part = new FormDataPart(name, value); - contentLength += part.size; - return part; - }); - - contentLength += boundaryBytes.byteLength * parts.length; - - contentLength = utils.toFiniteNumber(contentLength); - - const computedHeaders = { - 'Content-Type': `multipart/form-data; boundary=${boundary}` - }; - - if (Number.isFinite(contentLength)) { - computedHeaders['Content-Length'] = contentLength; - } - - headersHandler && headersHandler(computedHeaders); - - return stream.Readable.from((async function *() { - for(const part of parts) { - yield boundaryBytes; - yield* part.encode(); - } - - yield footerBytes; - })()); -}; - -const formDataToStream$1 = formDataToStream; - -class ZlibHeaderTransformStream extends stream__default["default"].Transform { - __transform(chunk, encoding, callback) { - this.push(chunk); - callback(); - } - - _transform(chunk, encoding, callback) { - if (chunk.length !== 0) { - this._transform = this.__transform; - - // Add Default Compression headers if no zlib headers are present - if (chunk[0] !== 120) { // Hex: 78 - const header = Buffer.alloc(2); - header[0] = 120; // Hex: 78 - header[1] = 156; // Hex: 9C - this.push(header, encoding); - } - } - - this.__transform(chunk, encoding, callback); + setLength(length) { + this[kInternals].length = +length; + return this; } } -const ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream; - -const zlibOptions = { - flush: zlib__default["default"].constants.Z_SYNC_FLUSH, - finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH -}; - -const brotliOptions = { - flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH, - finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH -}; - const isBrotliSupported = utils.isFunction(zlib__default["default"].createBrotliDecompress); const {http: httpFollow, https: httpsFollow} = followRedirects__default["default"]; @@ -12649,12 +12190,9 @@ function setProxy(options, configProxy, location) { }; } -const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process'; - /*eslint consistent-return:0*/ -const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { - /*eslint no-async-promise-executor:0*/ - return new Promise(async function dispatchHttpRequest(resolvePromise, rejectPromise) { +function httpAdapter(config) { + return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { let data = config.data; const responseType = config.responseType; const responseEncoding = config.responseEncoding; @@ -12718,7 +12256,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { // Parse url const fullPath = buildFullPath(config.baseURL, config.url); - const parsed = new URL(fullPath, 'http://localhost'); + const parsed = new URL(fullPath); const protocol = parsed.protocol || supportedProtocols[0]; if (protocol === 'data:') { @@ -12745,7 +12283,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { convertedData = convertedData.toString(responseEncoding); if (!responseEncoding || responseEncoding === 'utf8') { - convertedData = utils.stripBOM(convertedData); + data = utils.stripBOM(convertedData); } } else if (responseType === 'stream') { convertedData = stream__default["default"].Readable.from(convertedData); @@ -12755,7 +12293,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { data: convertedData, status: 200, statusText: 'OK', - headers: new AxiosHeaders$1(), + headers: {}, config }); } @@ -12768,7 +12306,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { )); } - const headers = AxiosHeaders$1.from(config.headers).normalize(); + const headers = AxiosHeaders.from(config.headers).normalize(); // Set User-Agent (required by some servers) // See https://github.com/axios/axios/issues/69 @@ -12782,32 +12320,9 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { let maxUploadRate = undefined; let maxDownloadRate = undefined; - // support for spec compliant FormData objects - if (utils.isSpecCompliantForm(data)) { - const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); - - data = formDataToStream$1(data, (formHeaders) => { - headers.set(formHeaders); - }, { - tag: `axios-${VERSION}-boundary`, - boundary: userBoundary && userBoundary[1] || undefined - }); - // support for https://www.npmjs.com/package/form-data api - } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { + // support for https://www.npmjs.com/package/form-data api + if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { headers.set(data.getHeaders()); - - if (!headers.hasContentLength()) { - try { - const knownLength = await util__default["default"].promisify(data.getLength).call(data); - Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); - /*eslint no-empty:0*/ - } catch (e) { - } - } - } 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.isStream(data)) { if (Buffer.isBuffer(data)) ; else if (utils.isArrayBuffer(data)) { data = Buffer.from(new Uint8Array(data)); @@ -12822,7 +12337,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } // Add Content-Length header if data exists - headers.setContentLength(data.length, false); + headers.set('Content-Length', data.length, false); if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { return reject(new AxiosError( @@ -12833,7 +12348,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { } } - const contentLength = utils.toFiniteNumber(headers.getContentLength()); + const contentLength = +headers.getContentLength(); if (utils.isArray(maxRate)) { maxUploadRate = maxRate[0]; @@ -12847,8 +12362,8 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { data = stream__default["default"].Readable.from(data, {objectMode: false}); } - data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ - length: contentLength, + data = stream__default["default"].pipeline([data, new AxiosTransformStream({ + length: utils.toFiniteNumber(contentLength), maxRate: utils.toFiniteNumber(maxUploadRate) })], utils.noop); @@ -12891,10 +12406,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { return reject(customErr); } - headers.set( - 'Accept-Encoding', - 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false - ); + headers.set('Accept-Encoding', 'gzip, deflate, br', false); const options = { path, @@ -12949,66 +12461,56 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { const streams = [res]; - const responseLength = +res.headers['content-length']; - - if (onDownloadProgress) { - const transformStream = new AxiosTransformStream$1({ - length: utils.toFiniteNumber(responseLength), - maxRate: utils.toFiniteNumber(maxDownloadRate) - }); - - onDownloadProgress && transformStream.on('progress', progress => { - onDownloadProgress(Object.assign(progress, { - download: true - })); - }); - - streams.push(transformStream); - } - - // decompress the response body transparently if required + // uncompress the response body transparently if required let responseStream = res; // return the last request in case of redirects const lastRequest = res.req || req; // if decompress disabled we should not decompress - if (config.decompress !== false && res.headers['content-encoding']) { + if (config.decompress !== false) { // if no content, but headers still say that it is encoded, // remove the header not confuse downstream operations - if (method === 'HEAD' || res.statusCode === 204) { + if (data && data.length === 0 && res.headers['content-encoding']) { delete res.headers['content-encoding']; } switch (res.headers['content-encoding']) { /*eslint default-case:0*/ case 'gzip': - case 'x-gzip': case 'compress': - case 'x-compress': - // add the unzipper to the body stream processing pipeline - streams.push(zlib__default["default"].createUnzip(zlibOptions)); - - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; case 'deflate': - streams.push(new ZlibHeaderTransformStream$1()); - // add the unzipper to the body stream processing pipeline - streams.push(zlib__default["default"].createUnzip(zlibOptions)); + streams.push(zlib__default["default"].createUnzip()); // remove the content-encoding in order to not confuse downstream operations delete res.headers['content-encoding']; break; case 'br': if (isBrotliSupported) { - streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions)); + streams.push(zlib__default["default"].createBrotliDecompress()); delete res.headers['content-encoding']; } } } + if (onDownloadProgress) { + const responseLength = +res.headers['content-length']; + + const transformStream = new AxiosTransformStream({ + length: utils.toFiniteNumber(responseLength), + maxRate: utils.toFiniteNumber(maxDownloadRate) + }); + + onDownloadProgress && transformStream.on('progress', progress => { + onDownloadProgress(Object.assign(progress, { + download: true + })); + }); + + streams.push(transformStream); + } + responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils.noop) : streams[0]; const offListeners = stream__default["default"].finished(responseStream, () => { @@ -13019,7 +12521,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { const response = { status: res.statusCode, statusText: res.statusMessage, - headers: new AxiosHeaders$1(res.headers), + headers: new AxiosHeaders(res.headers), config, request: lastRequest }; @@ -13172,7 +12674,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { req.end(data); } }); -}; +} const cookies = platform.isStandardBrowserEnv ? @@ -13304,8 +12806,7 @@ function progressEventReducer(listener, isDownloadStream) { progress: total ? (loaded / total) : undefined, bytes: progressBytes, rate: rate ? rate : undefined, - estimated: rate && total && inRange ? (total - loaded) / rate : undefined, - event: e + estimated: rate && total && inRange ? (total - loaded) / rate : undefined }; data[isDownloadStream ? 'download' : 'upload'] = true; @@ -13314,12 +12815,10 @@ function progressEventReducer(listener, isDownloadStream) { }; } -const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; - -const xhrAdapter = isXHRAdapterSupported && function (config) { +function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { let requestData = config.data; - const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); + const requestHeaders = AxiosHeaders.from(config.headers).normalize(); const responseType = config.responseType; let onCanceled; function done() { @@ -13332,7 +12831,7 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { } } - if (utils.isFormData(requestData) && (platform.isStandardBrowserEnv || platform.isStandardBrowserWebWorkerEnv)) { + if (utils.isFormData(requestData) && platform.isStandardBrowserEnv) { requestHeaders.setContentType(false); // Let the browser set it } @@ -13357,10 +12856,10 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { return; } // Prepare the response - const responseHeaders = AxiosHeaders$1.from( + const responseHeaders = AxiosHeaders.from( 'getAllResponseHeaders' in request && request.getAllResponseHeaders() ); - const responseData = !responseType || responseType === 'text' || responseType === 'json' ? + const responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; const response = { data: responseData, @@ -13517,63 +13016,238 @@ const xhrAdapter = isXHRAdapterSupported && function (config) { // Send the request request.send(requestData || null); }); -}; +} -const knownAdapters = { +const adapters = { http: httpAdapter, xhr: xhrAdapter }; -utils.forEach(knownAdapters, (fn, value) => { - if(fn) { +const adapters$1 = { + getAdapter: (nameOrAdapter) => { + if(utils.isString(nameOrAdapter)){ + const adapter = adapters[nameOrAdapter]; + + if (!nameOrAdapter) { + throw Error( + utils.hasOwnProp(nameOrAdapter) ? + `Adapter '${nameOrAdapter}' is not available in the build` : + `Can not resolve adapter '${nameOrAdapter}'` + ); + } + + return adapter + } + + if (!utils.isFunction(nameOrAdapter)) { + throw new TypeError('adapter is not a function'); + } + + return nameOrAdapter; + }, + adapters +}; + +const DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; + +/** + * If the browser has an XMLHttpRequest object, use the XHR adapter, otherwise use the HTTP + * adapter + * + * @returns {Function} + */ +function getDefaultAdapter() { + let adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = adapters$1.getAdapter('xhr'); + } else if (typeof process !== 'undefined' && utils.kindOf(process) === 'process') { + // For node use HTTP adapter + adapter = adapters$1.getAdapter('http'); + } + return adapter; +} + +/** + * It takes a string, tries to parse it, and if it fails, it returns the stringified version + * of the input + * + * @param {any} rawValue - The value to be stringified. + * @param {Function} parser - A function that parses a string into a JavaScript object. + * @param {Function} encoder - A function that takes a value and returns a string. + * + * @returns {string} A stringified version of the rawValue. + */ +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { try { - Object.defineProperty(fn, 'name', {value}); + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); } catch (e) { - // eslint-disable-next-line no-empty + if (e.name !== 'SyntaxError') { + throw e; + } } - Object.defineProperty(fn, 'adapterName', {value}); } -}); -const adapters = { - getAdapter: (adapters) => { - adapters = utils.isArray(adapters) ? adapters : [adapters]; + return (encoder || JSON.stringify)(rawValue); +} - const {length} = adapters; - let nameOrAdapter; - let adapter; +const defaults = { - for (let i = 0; i < length; i++) { - nameOrAdapter = adapters[i]; - if((adapter = utils.isString(nameOrAdapter) ? knownAdapters[nameOrAdapter.toLowerCase()] : nameOrAdapter)) { - break; + transitional: transitionalDefaults, + + adapter: getDefaultAdapter(), + + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ''; + const hasJSONContentType = contentType.indexOf('application/json') > -1; + const isObjectPayload = utils.isObject(data); + + if (isObjectPayload && utils.isHTMLForm(data)) { + data = new FormData(data); + } + + const isFormData = utils.isFormData(data); + + if (isFormData) { + if (!hasJSONContentType) { + return data; } + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } + + if (utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); } - if (!adapter) { - if (adapter === false) { - throw new AxiosError( - `Adapter ${nameOrAdapter} is not supported by the environment`, - 'ERR_NOT_SUPPORT' + let isFileList; + + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + + if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + const _FormData = this.env && this.env.FormData; + + return toFormData( + isFileList ? {'files[]': data} : data, + _FormData && new _FormData(), + this.formSerializer ); } + } - throw new Error( - utils.hasOwnProp(knownAdapters, nameOrAdapter) ? - `Adapter '${nameOrAdapter}' is not available in the build` : - `Unknown adapter '${nameOrAdapter}'` - ); + if (isObjectPayload || hasJSONContentType ) { + headers.setContentType('application/json', false); + return stringifySafely(data); } - if (!utils.isFunction(adapter)) { - throw new TypeError('adapter is not a function'); + return data; + }], + + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === 'json'; + + if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } } - return adapter; + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; }, - adapters: knownAdapters + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*' + } + } }; +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); + +/** + * Transform the data for a request or a response + * + * @param {Array|Function} fns A single function or Array of functions + * @param {?Object} response The response object + * + * @returns {*} The resulting transformed data + */ +function transformData(fns, response) { + const config = this || defaults; + const context = response || config; + const headers = AxiosHeaders.from(context.headers); + let data = context.data; + + utils.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); + + headers.normalize(); + + return data; +} + +function isCancel(value) { + return !!(value && value.__CANCEL__); +} + /** * Throws a `CanceledError` if cancellation has been requested. * @@ -13587,7 +13261,7 @@ function throwIfCancellationRequested(config) { } if (config.signal && config.signal.aborted) { - throw new CanceledError(null, config); + throw new CanceledError(); } } @@ -13601,7 +13275,7 @@ function throwIfCancellationRequested(config) { function dispatchRequest(config) { throwIfCancellationRequested(config); - config.headers = AxiosHeaders$1.from(config.headers); + config.headers = AxiosHeaders.from(config.headers); // Transform request data config.data = transformData.call( @@ -13609,11 +13283,7 @@ function dispatchRequest(config) { config.transformRequest ); - if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { - config.headers.setContentType('application/x-www-form-urlencoded', false); - } - - const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + const adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); @@ -13625,7 +13295,7 @@ function dispatchRequest(config) { response ); - response.headers = AxiosHeaders$1.from(response.headers); + response.headers = AxiosHeaders.from(response.headers); return response; }, function onAdapterRejection(reason) { @@ -13639,7 +13309,7 @@ function dispatchRequest(config) { config.transformResponse, reason.response ); - reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + reason.response.headers = AxiosHeaders.from(reason.response.headers); } } @@ -13647,8 +13317,6 @@ function dispatchRequest(config) { }); } -const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? thing.toJSON() : thing; - /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. @@ -13663,9 +13331,9 @@ function mergeConfig(config1, config2) { config2 = config2 || {}; const config = {}; - function getMergedValue(target, source, caseless) { + function getMergedValue(target, source) { if (utils.isPlainObject(target) && utils.isPlainObject(source)) { - return utils.merge.call({caseless}, target, source); + return utils.merge(target, source); } else if (utils.isPlainObject(source)) { return utils.merge({}, source); } else if (utils.isArray(source)) { @@ -13675,73 +13343,72 @@ function mergeConfig(config1, config2) { } // 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); + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + return getMergedValue(undefined, config1[prop]); } } // eslint-disable-next-line consistent-return - function valueFromConfig2(a, b) { - if (!utils.isUndefined(b)) { - return getMergedValue(undefined, b); + function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(undefined, config2[prop]); } } // 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); + function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + return getMergedValue(undefined, config1[prop]); } } // eslint-disable-next-line consistent-return - function mergeDirectKeys(a, b, prop) { + function mergeDirectKeys(prop) { if (prop in config2) { - return getMergedValue(a, b); + return getMergedValue(config1[prop], config2[prop]); } else if (prop in config1) { - return getMergedValue(undefined, a); + return getMergedValue(undefined, config1[prop]); } } 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) + '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 }; utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { const merge = mergeMap[prop] || mergeDeepProperties; - const configValue = merge(config1[prop], config2[prop], prop); + const configValue = merge(prop); (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); }); @@ -13848,8 +13515,8 @@ class Axios { constructor(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { - request: new InterceptorManager$1(), - response: new InterceptorManager$1() + request: new InterceptorManager(), + response: new InterceptorManager() }; } @@ -13873,7 +13540,7 @@ class Axios { config = mergeConfig(this.defaults, config); - const {transitional, paramsSerializer, headers} = config; + const {transitional, paramsSerializer} = config; if (transitional !== undefined) { validator.assertOptions(transitional, { @@ -13893,22 +13560,20 @@ class Axios { // Set config.method config.method = (config.method || this.defaults.method || 'get').toLowerCase(); - let contextHeaders; - // Flatten headers - contextHeaders = headers && utils.merge( - headers.common, - headers[config.method] + const defaultHeaders = config.headers && utils.merge( + config.headers.common, + config.headers[config.method] ); - contextHeaders && utils.forEach( + defaultHeaders && utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - (method) => { - delete headers[method]; + function cleanHeaderConfig(method) { + delete config.headers[method]; } ); - config.headers = AxiosHeaders$1.concat(contextHeaders, headers); + config.headers = new AxiosHeaders(config.headers, defaultHeaders); // filter out skipped interceptors const requestInterceptorChain = []; @@ -14020,8 +13685,6 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { Axios.prototype[method + 'Form'] = generateHTTPMethod(true); }); -const Axios$1 = Axios; - /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * @@ -14138,8 +13801,6 @@ class CancelToken { } } -const CancelToken$1 = CancelToken; - /** * Syntactic sugar for invoking a function and expanding an array for arguments. * @@ -14178,78 +13839,6 @@ function isAxiosError(payload) { return utils.isObject(payload) && (payload.isAxiosError === true); } -const HttpStatusCode = { - Continue: 100, - SwitchingProtocols: 101, - Processing: 102, - EarlyHints: 103, - Ok: 200, - Created: 201, - Accepted: 202, - NonAuthoritativeInformation: 203, - NoContent: 204, - ResetContent: 205, - PartialContent: 206, - MultiStatus: 207, - AlreadyReported: 208, - ImUsed: 226, - MultipleChoices: 300, - MovedPermanently: 301, - Found: 302, - SeeOther: 303, - NotModified: 304, - UseProxy: 305, - Unused: 306, - TemporaryRedirect: 307, - PermanentRedirect: 308, - BadRequest: 400, - Unauthorized: 401, - PaymentRequired: 402, - Forbidden: 403, - NotFound: 404, - MethodNotAllowed: 405, - NotAcceptable: 406, - ProxyAuthenticationRequired: 407, - RequestTimeout: 408, - Conflict: 409, - Gone: 410, - LengthRequired: 411, - PreconditionFailed: 412, - PayloadTooLarge: 413, - UriTooLong: 414, - UnsupportedMediaType: 415, - RangeNotSatisfiable: 416, - ExpectationFailed: 417, - ImATeapot: 418, - MisdirectedRequest: 421, - UnprocessableEntity: 422, - Locked: 423, - FailedDependency: 424, - TooEarly: 425, - UpgradeRequired: 426, - PreconditionRequired: 428, - TooManyRequests: 429, - RequestHeaderFieldsTooLarge: 431, - UnavailableForLegalReasons: 451, - InternalServerError: 500, - NotImplemented: 501, - BadGateway: 502, - ServiceUnavailable: 503, - GatewayTimeout: 504, - HttpVersionNotSupported: 505, - VariantAlsoNegotiates: 506, - InsufficientStorage: 507, - LoopDetected: 508, - NotExtended: 510, - NetworkAuthenticationRequired: 511, -}; - -Object.entries(HttpStatusCode).forEach(([key, value]) => { - HttpStatusCode[value] = key; -}); - -const HttpStatusCode$1 = HttpStatusCode; - /** * Create an instance of Axios * @@ -14258,11 +13847,11 @@ const HttpStatusCode$1 = HttpStatusCode; * @returns {Axios} A new instance of Axios */ function createInstance(defaultConfig) { - const context = new Axios$1(defaultConfig); - const instance = bind(Axios$1.prototype.request, context); + const context = new Axios(defaultConfig); + const instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance - utils.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); + utils.extend(instance, Axios.prototype, context, {allOwnKeys: true}); // Copy context to instance utils.extend(instance, context, null, {allOwnKeys: true}); @@ -14276,14 +13865,14 @@ function createInstance(defaultConfig) { } // Create the default instance to be exported -const axios = createInstance(defaults$1); +const axios = createInstance(defaults); // Expose Axios class to allow class inheritance -axios.Axios = Axios$1; +axios.Axios = Axios; // Expose Cancel & CancelToken axios.CanceledError = CanceledError; -axios.CancelToken = CancelToken$1; +axios.CancelToken = CancelToken; axios.isCancel = isCancel; axios.VERSION = VERSION; axios.toFormData = toFormData; @@ -14304,16 +13893,9 @@ axios.spread = spread; // Expose isAxiosError axios.isAxiosError = isAxiosError; -// Expose mergeConfig -axios.mergeConfig = mergeConfig; - -axios.AxiosHeaders = AxiosHeaders$1; - -axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); - -axios.HttpStatusCode = HttpStatusCode$1; - -axios.default = axios; +axios.formToJSON = thing => { + return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); +}; module.exports = axios; //# sourceMappingURL=axios.cjs.map @@ -14565,6 +14147,7 @@ function convertPrismaSeverity(severity) { case "low": return "none"; case "unimportant": + case "negligible": return "none"; default: throw new Error(`Unknown severity: ${severity}`); @@ -14731,4 +14314,4 @@ if (require.main === require.cache[eval('__filename')]) { module.exports = __webpack_exports__; /******/ })() -; +; \ No newline at end of file diff --git a/index.js b/index.js index dce7531..3ea9019 100644 --- a/index.js +++ b/index.js @@ -118,9 +118,16 @@ function formatSarifToolDriverRules(results) { const vulnerabilities = result.vulnerabilities; const compliances = result.compliances; + const vulnerabilitiesFiltered = (vulnerabilities || []).filter( + (thing, index, self) => + index === + self.findIndex((t) => t.id === thing.id ) + ); + + let vulns = []; - if (vulnerabilities) { - vulns = vulnerabilities.map(vuln => { + if (vulnerabilitiesFiltered) { + vulns = vulnerabilitiesFiltered.map(vuln => { return { id: `${vuln.id}`, shortDescription: { @@ -170,24 +177,30 @@ function formatSarifToolDriverRules(results) { * @returns string */ function convertPrismaSeverity(severity) { - // prisma: critical, high, important, medium, low + // prisma: critical, high, important, medium, moderate, unimportant, low // gh: error, warning, note, none switch (severity) { - case "important": - return "warning"; case "critical": return "error"; case "high": return "warning"; + case "important": + return "warning"; case "medium": return "note"; + case "moderate": + return "note"; case "low": return "none"; + case "unimportant": + case "negligible": + return "none"; default: - throw new Error(`Unknown severities: ${severity}`); + throw new Error(`Unknown severity: ${severity}`); } } + function formatSarifResults(results) { // Only 1 image can be scanned at a time const result = results[0];