source: node_modules/axios/dist/esm/axios.js@ 7deb3e2

Last change on this file since 7deb3e2 was ff72ad2, checked in by ste08 <sjovanoska@…>, 2 months ago

Adding review works\!

  • Property mode set to 100644
File size: 95.2 KB
Line 
1/*! Axios v1.8.4 Copyright (c) 2025 Matt Zabriskie and contributors */
2function bind(fn, thisArg) {
3 return function wrap() {
4 return fn.apply(thisArg, arguments);
5 };
6}
7
8// utils is a library of generic helper functions non-specific to axios
9
10const {toString} = Object.prototype;
11const {getPrototypeOf} = Object;
12
13const kindOf = (cache => thing => {
14 const str = toString.call(thing);
15 return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
16})(Object.create(null));
17
18const kindOfTest = (type) => {
19 type = type.toLowerCase();
20 return (thing) => kindOf(thing) === type
21};
22
23const typeOfTest = type => thing => typeof thing === type;
24
25/**
26 * Determine if a value is an Array
27 *
28 * @param {Object} val The value to test
29 *
30 * @returns {boolean} True if value is an Array, otherwise false
31 */
32const {isArray} = Array;
33
34/**
35 * Determine if a value is undefined
36 *
37 * @param {*} val The value to test
38 *
39 * @returns {boolean} True if the value is undefined, otherwise false
40 */
41const isUndefined = typeOfTest('undefined');
42
43/**
44 * Determine if a value is a Buffer
45 *
46 * @param {*} val The value to test
47 *
48 * @returns {boolean} True if value is a Buffer, otherwise false
49 */
50function isBuffer(val) {
51 return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
52 && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
53}
54
55/**
56 * Determine if a value is an ArrayBuffer
57 *
58 * @param {*} val The value to test
59 *
60 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
61 */
62const isArrayBuffer = kindOfTest('ArrayBuffer');
63
64
65/**
66 * Determine if a value is a view on an ArrayBuffer
67 *
68 * @param {*} val The value to test
69 *
70 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
71 */
72function isArrayBufferView(val) {
73 let result;
74 if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
75 result = ArrayBuffer.isView(val);
76 } else {
77 result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
78 }
79 return result;
80}
81
82/**
83 * Determine if a value is a String
84 *
85 * @param {*} val The value to test
86 *
87 * @returns {boolean} True if value is a String, otherwise false
88 */
89const isString = typeOfTest('string');
90
91/**
92 * Determine if a value is a Function
93 *
94 * @param {*} val The value to test
95 * @returns {boolean} True if value is a Function, otherwise false
96 */
97const isFunction = typeOfTest('function');
98
99/**
100 * Determine if a value is a Number
101 *
102 * @param {*} val The value to test
103 *
104 * @returns {boolean} True if value is a Number, otherwise false
105 */
106const isNumber = typeOfTest('number');
107
108/**
109 * Determine if a value is an Object
110 *
111 * @param {*} thing The value to test
112 *
113 * @returns {boolean} True if value is an Object, otherwise false
114 */
115const isObject = (thing) => thing !== null && typeof thing === 'object';
116
117/**
118 * Determine if a value is a Boolean
119 *
120 * @param {*} thing The value to test
121 * @returns {boolean} True if value is a Boolean, otherwise false
122 */
123const isBoolean = thing => thing === true || thing === false;
124
125/**
126 * Determine if a value is a plain Object
127 *
128 * @param {*} val The value to test
129 *
130 * @returns {boolean} True if value is a plain Object, otherwise false
131 */
132const isPlainObject = (val) => {
133 if (kindOf(val) !== 'object') {
134 return false;
135 }
136
137 const prototype = getPrototypeOf(val);
138 return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
139};
140
141/**
142 * Determine if a value is a Date
143 *
144 * @param {*} val The value to test
145 *
146 * @returns {boolean} True if value is a Date, otherwise false
147 */
148const isDate = kindOfTest('Date');
149
150/**
151 * Determine if a value is a File
152 *
153 * @param {*} val The value to test
154 *
155 * @returns {boolean} True if value is a File, otherwise false
156 */
157const isFile = kindOfTest('File');
158
159/**
160 * Determine if a value is a Blob
161 *
162 * @param {*} val The value to test
163 *
164 * @returns {boolean} True if value is a Blob, otherwise false
165 */
166const isBlob = kindOfTest('Blob');
167
168/**
169 * Determine if a value is a FileList
170 *
171 * @param {*} val The value to test
172 *
173 * @returns {boolean} True if value is a File, otherwise false
174 */
175const isFileList = kindOfTest('FileList');
176
177/**
178 * Determine if a value is a Stream
179 *
180 * @param {*} val The value to test
181 *
182 * @returns {boolean} True if value is a Stream, otherwise false
183 */
184const isStream = (val) => isObject(val) && isFunction(val.pipe);
185
186/**
187 * Determine if a value is a FormData
188 *
189 * @param {*} thing The value to test
190 *
191 * @returns {boolean} True if value is an FormData, otherwise false
192 */
193const isFormData = (thing) => {
194 let kind;
195 return thing && (
196 (typeof FormData === 'function' && thing instanceof FormData) || (
197 isFunction(thing.append) && (
198 (kind = kindOf(thing)) === 'formdata' ||
199 // detect form-data instance
200 (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
201 )
202 )
203 )
204};
205
206/**
207 * Determine if a value is a URLSearchParams object
208 *
209 * @param {*} val The value to test
210 *
211 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
212 */
213const isURLSearchParams = kindOfTest('URLSearchParams');
214
215const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
216
217/**
218 * Trim excess whitespace off the beginning and end of a string
219 *
220 * @param {String} str The String to trim
221 *
222 * @returns {String} The String freed of excess whitespace
223 */
224const trim = (str) => str.trim ?
225 str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
226
227/**
228 * Iterate over an Array or an Object invoking a function for each item.
229 *
230 * If `obj` is an Array callback will be called passing
231 * the value, index, and complete array for each item.
232 *
233 * If 'obj' is an Object callback will be called passing
234 * the value, key, and complete object for each property.
235 *
236 * @param {Object|Array} obj The object to iterate
237 * @param {Function} fn The callback to invoke for each item
238 *
239 * @param {Boolean} [allOwnKeys = false]
240 * @returns {any}
241 */
242function forEach(obj, fn, {allOwnKeys = false} = {}) {
243 // Don't bother if no value provided
244 if (obj === null || typeof obj === 'undefined') {
245 return;
246 }
247
248 let i;
249 let l;
250
251 // Force an array if not already something iterable
252 if (typeof obj !== 'object') {
253 /*eslint no-param-reassign:0*/
254 obj = [obj];
255 }
256
257 if (isArray(obj)) {
258 // Iterate over array values
259 for (i = 0, l = obj.length; i < l; i++) {
260 fn.call(null, obj[i], i, obj);
261 }
262 } else {
263 // Iterate over object keys
264 const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
265 const len = keys.length;
266 let key;
267
268 for (i = 0; i < len; i++) {
269 key = keys[i];
270 fn.call(null, obj[key], key, obj);
271 }
272 }
273}
274
275function findKey(obj, key) {
276 key = key.toLowerCase();
277 const keys = Object.keys(obj);
278 let i = keys.length;
279 let _key;
280 while (i-- > 0) {
281 _key = keys[i];
282 if (key === _key.toLowerCase()) {
283 return _key;
284 }
285 }
286 return null;
287}
288
289const _global = (() => {
290 /*eslint no-undef:0*/
291 if (typeof globalThis !== "undefined") return globalThis;
292 return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
293})();
294
295const isContextDefined = (context) => !isUndefined(context) && context !== _global;
296
297/**
298 * Accepts varargs expecting each argument to be an object, then
299 * immutably merges the properties of each object and returns result.
300 *
301 * When multiple objects contain the same key the later object in
302 * the arguments list will take precedence.
303 *
304 * Example:
305 *
306 * ```js
307 * var result = merge({foo: 123}, {foo: 456});
308 * console.log(result.foo); // outputs 456
309 * ```
310 *
311 * @param {Object} obj1 Object to merge
312 *
313 * @returns {Object} Result of all merge properties
314 */
315function merge(/* obj1, obj2, obj3, ... */) {
316 const {caseless} = isContextDefined(this) && this || {};
317 const result = {};
318 const assignValue = (val, key) => {
319 const targetKey = caseless && findKey(result, key) || key;
320 if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
321 result[targetKey] = merge(result[targetKey], val);
322 } else if (isPlainObject(val)) {
323 result[targetKey] = merge({}, val);
324 } else if (isArray(val)) {
325 result[targetKey] = val.slice();
326 } else {
327 result[targetKey] = val;
328 }
329 };
330
331 for (let i = 0, l = arguments.length; i < l; i++) {
332 arguments[i] && forEach(arguments[i], assignValue);
333 }
334 return result;
335}
336
337/**
338 * Extends object a by mutably adding to it the properties of object b.
339 *
340 * @param {Object} a The object to be extended
341 * @param {Object} b The object to copy properties from
342 * @param {Object} thisArg The object to bind function to
343 *
344 * @param {Boolean} [allOwnKeys]
345 * @returns {Object} The resulting value of object a
346 */
347const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
348 forEach(b, (val, key) => {
349 if (thisArg && isFunction(val)) {
350 a[key] = bind(val, thisArg);
351 } else {
352 a[key] = val;
353 }
354 }, {allOwnKeys});
355 return a;
356};
357
358/**
359 * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
360 *
361 * @param {string} content with BOM
362 *
363 * @returns {string} content value without BOM
364 */
365const stripBOM = (content) => {
366 if (content.charCodeAt(0) === 0xFEFF) {
367 content = content.slice(1);
368 }
369 return content;
370};
371
372/**
373 * Inherit the prototype methods from one constructor into another
374 * @param {function} constructor
375 * @param {function} superConstructor
376 * @param {object} [props]
377 * @param {object} [descriptors]
378 *
379 * @returns {void}
380 */
381const inherits = (constructor, superConstructor, props, descriptors) => {
382 constructor.prototype = Object.create(superConstructor.prototype, descriptors);
383 constructor.prototype.constructor = constructor;
384 Object.defineProperty(constructor, 'super', {
385 value: superConstructor.prototype
386 });
387 props && Object.assign(constructor.prototype, props);
388};
389
390/**
391 * Resolve object with deep prototype chain to a flat object
392 * @param {Object} sourceObj source object
393 * @param {Object} [destObj]
394 * @param {Function|Boolean} [filter]
395 * @param {Function} [propFilter]
396 *
397 * @returns {Object}
398 */
399const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
400 let props;
401 let i;
402 let prop;
403 const merged = {};
404
405 destObj = destObj || {};
406 // eslint-disable-next-line no-eq-null,eqeqeq
407 if (sourceObj == null) return destObj;
408
409 do {
410 props = Object.getOwnPropertyNames(sourceObj);
411 i = props.length;
412 while (i-- > 0) {
413 prop = props[i];
414 if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
415 destObj[prop] = sourceObj[prop];
416 merged[prop] = true;
417 }
418 }
419 sourceObj = filter !== false && getPrototypeOf(sourceObj);
420 } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
421
422 return destObj;
423};
424
425/**
426 * Determines whether a string ends with the characters of a specified string
427 *
428 * @param {String} str
429 * @param {String} searchString
430 * @param {Number} [position= 0]
431 *
432 * @returns {boolean}
433 */
434const endsWith = (str, searchString, position) => {
435 str = String(str);
436 if (position === undefined || position > str.length) {
437 position = str.length;
438 }
439 position -= searchString.length;
440 const lastIndex = str.indexOf(searchString, position);
441 return lastIndex !== -1 && lastIndex === position;
442};
443
444
445/**
446 * Returns new array from array like object or null if failed
447 *
448 * @param {*} [thing]
449 *
450 * @returns {?Array}
451 */
452const toArray = (thing) => {
453 if (!thing) return null;
454 if (isArray(thing)) return thing;
455 let i = thing.length;
456 if (!isNumber(i)) return null;
457 const arr = new Array(i);
458 while (i-- > 0) {
459 arr[i] = thing[i];
460 }
461 return arr;
462};
463
464/**
465 * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
466 * thing passed in is an instance of Uint8Array
467 *
468 * @param {TypedArray}
469 *
470 * @returns {Array}
471 */
472// eslint-disable-next-line func-names
473const isTypedArray = (TypedArray => {
474 // eslint-disable-next-line func-names
475 return thing => {
476 return TypedArray && thing instanceof TypedArray;
477 };
478})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
479
480/**
481 * For each entry in the object, call the function with the key and value.
482 *
483 * @param {Object<any, any>} obj - The object to iterate over.
484 * @param {Function} fn - The function to call for each entry.
485 *
486 * @returns {void}
487 */
488const forEachEntry = (obj, fn) => {
489 const generator = obj && obj[Symbol.iterator];
490
491 const iterator = generator.call(obj);
492
493 let result;
494
495 while ((result = iterator.next()) && !result.done) {
496 const pair = result.value;
497 fn.call(obj, pair[0], pair[1]);
498 }
499};
500
501/**
502 * It takes a regular expression and a string, and returns an array of all the matches
503 *
504 * @param {string} regExp - The regular expression to match against.
505 * @param {string} str - The string to search.
506 *
507 * @returns {Array<boolean>}
508 */
509const matchAll = (regExp, str) => {
510 let matches;
511 const arr = [];
512
513 while ((matches = regExp.exec(str)) !== null) {
514 arr.push(matches);
515 }
516
517 return arr;
518};
519
520/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
521const isHTMLForm = kindOfTest('HTMLFormElement');
522
523const toCamelCase = str => {
524 return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
525 function replacer(m, p1, p2) {
526 return p1.toUpperCase() + p2;
527 }
528 );
529};
530
531/* Creating a function that will check if an object has a property. */
532const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
533
534/**
535 * Determine if a value is a RegExp object
536 *
537 * @param {*} val The value to test
538 *
539 * @returns {boolean} True if value is a RegExp object, otherwise false
540 */
541const isRegExp = kindOfTest('RegExp');
542
543const reduceDescriptors = (obj, reducer) => {
544 const descriptors = Object.getOwnPropertyDescriptors(obj);
545 const reducedDescriptors = {};
546
547 forEach(descriptors, (descriptor, name) => {
548 let ret;
549 if ((ret = reducer(descriptor, name, obj)) !== false) {
550 reducedDescriptors[name] = ret || descriptor;
551 }
552 });
553
554 Object.defineProperties(obj, reducedDescriptors);
555};
556
557/**
558 * Makes all methods read-only
559 * @param {Object} obj
560 */
561
562const freezeMethods = (obj) => {
563 reduceDescriptors(obj, (descriptor, name) => {
564 // skip restricted props in strict mode
565 if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
566 return false;
567 }
568
569 const value = obj[name];
570
571 if (!isFunction(value)) return;
572
573 descriptor.enumerable = false;
574
575 if ('writable' in descriptor) {
576 descriptor.writable = false;
577 return;
578 }
579
580 if (!descriptor.set) {
581 descriptor.set = () => {
582 throw Error('Can not rewrite read-only method \'' + name + '\'');
583 };
584 }
585 });
586};
587
588const toObjectSet = (arrayOrString, delimiter) => {
589 const obj = {};
590
591 const define = (arr) => {
592 arr.forEach(value => {
593 obj[value] = true;
594 });
595 };
596
597 isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
598
599 return obj;
600};
601
602const noop = () => {};
603
604const toFiniteNumber = (value, defaultValue) => {
605 return value != null && Number.isFinite(value = +value) ? value : defaultValue;
606};
607
608/**
609 * If the thing is a FormData object, return true, otherwise return false.
610 *
611 * @param {unknown} thing - The thing to check.
612 *
613 * @returns {boolean}
614 */
615function isSpecCompliantForm(thing) {
616 return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
617}
618
619const toJSONObject = (obj) => {
620 const stack = new Array(10);
621
622 const visit = (source, i) => {
623
624 if (isObject(source)) {
625 if (stack.indexOf(source) >= 0) {
626 return;
627 }
628
629 if(!('toJSON' in source)) {
630 stack[i] = source;
631 const target = isArray(source) ? [] : {};
632
633 forEach(source, (value, key) => {
634 const reducedValue = visit(value, i + 1);
635 !isUndefined(reducedValue) && (target[key] = reducedValue);
636 });
637
638 stack[i] = undefined;
639
640 return target;
641 }
642 }
643
644 return source;
645 };
646
647 return visit(obj, 0);
648};
649
650const isAsyncFn = kindOfTest('AsyncFunction');
651
652const isThenable = (thing) =>
653 thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
654
655// original code
656// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
657
658const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
659 if (setImmediateSupported) {
660 return setImmediate;
661 }
662
663 return postMessageSupported ? ((token, callbacks) => {
664 _global.addEventListener("message", ({source, data}) => {
665 if (source === _global && data === token) {
666 callbacks.length && callbacks.shift()();
667 }
668 }, false);
669
670 return (cb) => {
671 callbacks.push(cb);
672 _global.postMessage(token, "*");
673 }
674 })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
675})(
676 typeof setImmediate === 'function',
677 isFunction(_global.postMessage)
678);
679
680const asap = typeof queueMicrotask !== 'undefined' ?
681 queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
682
683// *********************
684
685const utils$1 = {
686 isArray,
687 isArrayBuffer,
688 isBuffer,
689 isFormData,
690 isArrayBufferView,
691 isString,
692 isNumber,
693 isBoolean,
694 isObject,
695 isPlainObject,
696 isReadableStream,
697 isRequest,
698 isResponse,
699 isHeaders,
700 isUndefined,
701 isDate,
702 isFile,
703 isBlob,
704 isRegExp,
705 isFunction,
706 isStream,
707 isURLSearchParams,
708 isTypedArray,
709 isFileList,
710 forEach,
711 merge,
712 extend,
713 trim,
714 stripBOM,
715 inherits,
716 toFlatObject,
717 kindOf,
718 kindOfTest,
719 endsWith,
720 toArray,
721 forEachEntry,
722 matchAll,
723 isHTMLForm,
724 hasOwnProperty,
725 hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
726 reduceDescriptors,
727 freezeMethods,
728 toObjectSet,
729 toCamelCase,
730 noop,
731 toFiniteNumber,
732 findKey,
733 global: _global,
734 isContextDefined,
735 isSpecCompliantForm,
736 toJSONObject,
737 isAsyncFn,
738 isThenable,
739 setImmediate: _setImmediate,
740 asap
741};
742
743/**
744 * Create an Error with the specified message, config, error code, request and response.
745 *
746 * @param {string} message The error message.
747 * @param {string} [code] The error code (for example, 'ECONNABORTED').
748 * @param {Object} [config] The config.
749 * @param {Object} [request] The request.
750 * @param {Object} [response] The response.
751 *
752 * @returns {Error} The created error.
753 */
754function AxiosError$1(message, code, config, request, response) {
755 Error.call(this);
756
757 if (Error.captureStackTrace) {
758 Error.captureStackTrace(this, this.constructor);
759 } else {
760 this.stack = (new Error()).stack;
761 }
762
763 this.message = message;
764 this.name = 'AxiosError';
765 code && (this.code = code);
766 config && (this.config = config);
767 request && (this.request = request);
768 if (response) {
769 this.response = response;
770 this.status = response.status ? response.status : null;
771 }
772}
773
774utils$1.inherits(AxiosError$1, Error, {
775 toJSON: function toJSON() {
776 return {
777 // Standard
778 message: this.message,
779 name: this.name,
780 // Microsoft
781 description: this.description,
782 number: this.number,
783 // Mozilla
784 fileName: this.fileName,
785 lineNumber: this.lineNumber,
786 columnNumber: this.columnNumber,
787 stack: this.stack,
788 // Axios
789 config: utils$1.toJSONObject(this.config),
790 code: this.code,
791 status: this.status
792 };
793 }
794});
795
796const prototype$1 = AxiosError$1.prototype;
797const descriptors = {};
798
799[
800 'ERR_BAD_OPTION_VALUE',
801 'ERR_BAD_OPTION',
802 'ECONNABORTED',
803 'ETIMEDOUT',
804 'ERR_NETWORK',
805 'ERR_FR_TOO_MANY_REDIRECTS',
806 'ERR_DEPRECATED',
807 'ERR_BAD_RESPONSE',
808 'ERR_BAD_REQUEST',
809 'ERR_CANCELED',
810 'ERR_NOT_SUPPORT',
811 'ERR_INVALID_URL'
812// eslint-disable-next-line func-names
813].forEach(code => {
814 descriptors[code] = {value: code};
815});
816
817Object.defineProperties(AxiosError$1, descriptors);
818Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
819
820// eslint-disable-next-line func-names
821AxiosError$1.from = (error, code, config, request, response, customProps) => {
822 const axiosError = Object.create(prototype$1);
823
824 utils$1.toFlatObject(error, axiosError, function filter(obj) {
825 return obj !== Error.prototype;
826 }, prop => {
827 return prop !== 'isAxiosError';
828 });
829
830 AxiosError$1.call(axiosError, error.message, code, config, request, response);
831
832 axiosError.cause = error;
833
834 axiosError.name = error.name;
835
836 customProps && Object.assign(axiosError, customProps);
837
838 return axiosError;
839};
840
841// eslint-disable-next-line strict
842const httpAdapter = null;
843
844/**
845 * Determines if the given thing is a array or js object.
846 *
847 * @param {string} thing - The object or array to be visited.
848 *
849 * @returns {boolean}
850 */
851function isVisitable(thing) {
852 return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
853}
854
855/**
856 * It removes the brackets from the end of a string
857 *
858 * @param {string} key - The key of the parameter.
859 *
860 * @returns {string} the key without the brackets.
861 */
862function removeBrackets(key) {
863 return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
864}
865
866/**
867 * It takes a path, a key, and a boolean, and returns a string
868 *
869 * @param {string} path - The path to the current key.
870 * @param {string} key - The key of the current object being iterated over.
871 * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
872 *
873 * @returns {string} The path to the current key.
874 */
875function renderKey(path, key, dots) {
876 if (!path) return key;
877 return path.concat(key).map(function each(token, i) {
878 // eslint-disable-next-line no-param-reassign
879 token = removeBrackets(token);
880 return !dots && i ? '[' + token + ']' : token;
881 }).join(dots ? '.' : '');
882}
883
884/**
885 * If the array is an array and none of its elements are visitable, then it's a flat array.
886 *
887 * @param {Array<any>} arr - The array to check
888 *
889 * @returns {boolean}
890 */
891function isFlatArray(arr) {
892 return utils$1.isArray(arr) && !arr.some(isVisitable);
893}
894
895const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
896 return /^is[A-Z]/.test(prop);
897});
898
899/**
900 * Convert a data object to FormData
901 *
902 * @param {Object} obj
903 * @param {?Object} [formData]
904 * @param {?Object} [options]
905 * @param {Function} [options.visitor]
906 * @param {Boolean} [options.metaTokens = true]
907 * @param {Boolean} [options.dots = false]
908 * @param {?Boolean} [options.indexes = false]
909 *
910 * @returns {Object}
911 **/
912
913/**
914 * It converts an object into a FormData object
915 *
916 * @param {Object<any, any>} obj - The object to convert to form data.
917 * @param {string} formData - The FormData object to append to.
918 * @param {Object<string, any>} options
919 *
920 * @returns
921 */
922function toFormData$1(obj, formData, options) {
923 if (!utils$1.isObject(obj)) {
924 throw new TypeError('target must be an object');
925 }
926
927 // eslint-disable-next-line no-param-reassign
928 formData = formData || new (FormData)();
929
930 // eslint-disable-next-line no-param-reassign
931 options = utils$1.toFlatObject(options, {
932 metaTokens: true,
933 dots: false,
934 indexes: false
935 }, false, function defined(option, source) {
936 // eslint-disable-next-line no-eq-null,eqeqeq
937 return !utils$1.isUndefined(source[option]);
938 });
939
940 const metaTokens = options.metaTokens;
941 // eslint-disable-next-line no-use-before-define
942 const visitor = options.visitor || defaultVisitor;
943 const dots = options.dots;
944 const indexes = options.indexes;
945 const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
946 const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
947
948 if (!utils$1.isFunction(visitor)) {
949 throw new TypeError('visitor must be a function');
950 }
951
952 function convertValue(value) {
953 if (value === null) return '';
954
955 if (utils$1.isDate(value)) {
956 return value.toISOString();
957 }
958
959 if (!useBlob && utils$1.isBlob(value)) {
960 throw new AxiosError$1('Blob is not supported. Use a Buffer instead.');
961 }
962
963 if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
964 return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
965 }
966
967 return value;
968 }
969
970 /**
971 * Default visitor.
972 *
973 * @param {*} value
974 * @param {String|Number} key
975 * @param {Array<String|Number>} path
976 * @this {FormData}
977 *
978 * @returns {boolean} return true to visit the each prop of the value recursively
979 */
980 function defaultVisitor(value, key, path) {
981 let arr = value;
982
983 if (value && !path && typeof value === 'object') {
984 if (utils$1.endsWith(key, '{}')) {
985 // eslint-disable-next-line no-param-reassign
986 key = metaTokens ? key : key.slice(0, -2);
987 // eslint-disable-next-line no-param-reassign
988 value = JSON.stringify(value);
989 } else if (
990 (utils$1.isArray(value) && isFlatArray(value)) ||
991 ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
992 )) {
993 // eslint-disable-next-line no-param-reassign
994 key = removeBrackets(key);
995
996 arr.forEach(function each(el, index) {
997 !(utils$1.isUndefined(el) || el === null) && formData.append(
998 // eslint-disable-next-line no-nested-ternary
999 indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
1000 convertValue(el)
1001 );
1002 });
1003 return false;
1004 }
1005 }
1006
1007 if (isVisitable(value)) {
1008 return true;
1009 }
1010
1011 formData.append(renderKey(path, key, dots), convertValue(value));
1012
1013 return false;
1014 }
1015
1016 const stack = [];
1017
1018 const exposedHelpers = Object.assign(predicates, {
1019 defaultVisitor,
1020 convertValue,
1021 isVisitable
1022 });
1023
1024 function build(value, path) {
1025 if (utils$1.isUndefined(value)) return;
1026
1027 if (stack.indexOf(value) !== -1) {
1028 throw Error('Circular reference detected in ' + path.join('.'));
1029 }
1030
1031 stack.push(value);
1032
1033 utils$1.forEach(value, function each(el, key) {
1034 const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
1035 formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
1036 );
1037
1038 if (result === true) {
1039 build(el, path ? path.concat(key) : [key]);
1040 }
1041 });
1042
1043 stack.pop();
1044 }
1045
1046 if (!utils$1.isObject(obj)) {
1047 throw new TypeError('data must be an object');
1048 }
1049
1050 build(obj);
1051
1052 return formData;
1053}
1054
1055/**
1056 * It encodes a string by replacing all characters that are not in the unreserved set with
1057 * their percent-encoded equivalents
1058 *
1059 * @param {string} str - The string to encode.
1060 *
1061 * @returns {string} The encoded string.
1062 */
1063function encode$1(str) {
1064 const charMap = {
1065 '!': '%21',
1066 "'": '%27',
1067 '(': '%28',
1068 ')': '%29',
1069 '~': '%7E',
1070 '%20': '+',
1071 '%00': '\x00'
1072 };
1073 return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1074 return charMap[match];
1075 });
1076}
1077
1078/**
1079 * It takes a params object and converts it to a FormData object
1080 *
1081 * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
1082 * @param {Object<string, any>} options - The options object passed to the Axios constructor.
1083 *
1084 * @returns {void}
1085 */
1086function AxiosURLSearchParams(params, options) {
1087 this._pairs = [];
1088
1089 params && toFormData$1(params, this, options);
1090}
1091
1092const prototype = AxiosURLSearchParams.prototype;
1093
1094prototype.append = function append(name, value) {
1095 this._pairs.push([name, value]);
1096};
1097
1098prototype.toString = function toString(encoder) {
1099 const _encode = encoder ? function(value) {
1100 return encoder.call(this, value, encode$1);
1101 } : encode$1;
1102
1103 return this._pairs.map(function each(pair) {
1104 return _encode(pair[0]) + '=' + _encode(pair[1]);
1105 }, '').join('&');
1106};
1107
1108/**
1109 * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
1110 * URI encoded counterparts
1111 *
1112 * @param {string} val The value to be encoded.
1113 *
1114 * @returns {string} The encoded value.
1115 */
1116function encode(val) {
1117 return encodeURIComponent(val).
1118 replace(/%3A/gi, ':').
1119 replace(/%24/g, '$').
1120 replace(/%2C/gi, ',').
1121 replace(/%20/g, '+').
1122 replace(/%5B/gi, '[').
1123 replace(/%5D/gi, ']');
1124}
1125
1126/**
1127 * Build a URL by appending params to the end
1128 *
1129 * @param {string} url The base of the url (e.g., http://www.google.com)
1130 * @param {object} [params] The params to be appended
1131 * @param {?(object|Function)} options
1132 *
1133 * @returns {string} The formatted url
1134 */
1135function buildURL(url, params, options) {
1136 /*eslint no-param-reassign:0*/
1137 if (!params) {
1138 return url;
1139 }
1140
1141 const _encode = options && options.encode || encode;
1142
1143 if (utils$1.isFunction(options)) {
1144 options = {
1145 serialize: options
1146 };
1147 }
1148
1149 const serializeFn = options && options.serialize;
1150
1151 let serializedParams;
1152
1153 if (serializeFn) {
1154 serializedParams = serializeFn(params, options);
1155 } else {
1156 serializedParams = utils$1.isURLSearchParams(params) ?
1157 params.toString() :
1158 new AxiosURLSearchParams(params, options).toString(_encode);
1159 }
1160
1161 if (serializedParams) {
1162 const hashmarkIndex = url.indexOf("#");
1163
1164 if (hashmarkIndex !== -1) {
1165 url = url.slice(0, hashmarkIndex);
1166 }
1167 url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1168 }
1169
1170 return url;
1171}
1172
1173class InterceptorManager {
1174 constructor() {
1175 this.handlers = [];
1176 }
1177
1178 /**
1179 * Add a new interceptor to the stack
1180 *
1181 * @param {Function} fulfilled The function to handle `then` for a `Promise`
1182 * @param {Function} rejected The function to handle `reject` for a `Promise`
1183 *
1184 * @return {Number} An ID used to remove interceptor later
1185 */
1186 use(fulfilled, rejected, options) {
1187 this.handlers.push({
1188 fulfilled,
1189 rejected,
1190 synchronous: options ? options.synchronous : false,
1191 runWhen: options ? options.runWhen : null
1192 });
1193 return this.handlers.length - 1;
1194 }
1195
1196 /**
1197 * Remove an interceptor from the stack
1198 *
1199 * @param {Number} id The ID that was returned by `use`
1200 *
1201 * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
1202 */
1203 eject(id) {
1204 if (this.handlers[id]) {
1205 this.handlers[id] = null;
1206 }
1207 }
1208
1209 /**
1210 * Clear all interceptors from the stack
1211 *
1212 * @returns {void}
1213 */
1214 clear() {
1215 if (this.handlers) {
1216 this.handlers = [];
1217 }
1218 }
1219
1220 /**
1221 * Iterate over all the registered interceptors
1222 *
1223 * This method is particularly useful for skipping over any
1224 * interceptors that may have become `null` calling `eject`.
1225 *
1226 * @param {Function} fn The function to call for each interceptor
1227 *
1228 * @returns {void}
1229 */
1230 forEach(fn) {
1231 utils$1.forEach(this.handlers, function forEachHandler(h) {
1232 if (h !== null) {
1233 fn(h);
1234 }
1235 });
1236 }
1237}
1238
1239const InterceptorManager$1 = InterceptorManager;
1240
1241const transitionalDefaults = {
1242 silentJSONParsing: true,
1243 forcedJSONParsing: true,
1244 clarifyTimeoutError: false
1245};
1246
1247const URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
1248
1249const FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
1250
1251const Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
1252
1253const platform$1 = {
1254 isBrowser: true,
1255 classes: {
1256 URLSearchParams: URLSearchParams$1,
1257 FormData: FormData$1,
1258 Blob: Blob$1
1259 },
1260 protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
1261};
1262
1263const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
1264
1265const _navigator = typeof navigator === 'object' && navigator || undefined;
1266
1267/**
1268 * Determine if we're running in a standard browser environment
1269 *
1270 * This allows axios to run in a web worker, and react-native.
1271 * Both environments support XMLHttpRequest, but not fully standard globals.
1272 *
1273 * web workers:
1274 * typeof window -> undefined
1275 * typeof document -> undefined
1276 *
1277 * react-native:
1278 * navigator.product -> 'ReactNative'
1279 * nativescript
1280 * navigator.product -> 'NativeScript' or 'NS'
1281 *
1282 * @returns {boolean}
1283 */
1284const hasStandardBrowserEnv = hasBrowserEnv &&
1285 (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
1286
1287/**
1288 * Determine if we're running in a standard browser webWorker environment
1289 *
1290 * Although the `isStandardBrowserEnv` method indicates that
1291 * `allows axios to run in a web worker`, the WebWorker will still be
1292 * filtered out due to its judgment standard
1293 * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
1294 * This leads to a problem when axios post `FormData` in webWorker
1295 */
1296const hasStandardBrowserWebWorkerEnv = (() => {
1297 return (
1298 typeof WorkerGlobalScope !== 'undefined' &&
1299 // eslint-disable-next-line no-undef
1300 self instanceof WorkerGlobalScope &&
1301 typeof self.importScripts === 'function'
1302 );
1303})();
1304
1305const origin = hasBrowserEnv && window.location.href || 'http://localhost';
1306
1307const utils = /*#__PURE__*/Object.freeze({
1308 __proto__: null,
1309 hasBrowserEnv: hasBrowserEnv,
1310 hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
1311 hasStandardBrowserEnv: hasStandardBrowserEnv,
1312 navigator: _navigator,
1313 origin: origin
1314});
1315
1316const platform = {
1317 ...utils,
1318 ...platform$1
1319};
1320
1321function toURLEncodedForm(data, options) {
1322 return toFormData$1(data, new platform.classes.URLSearchParams(), Object.assign({
1323 visitor: function(value, key, path, helpers) {
1324 if (platform.isNode && utils$1.isBuffer(value)) {
1325 this.append(key, value.toString('base64'));
1326 return false;
1327 }
1328
1329 return helpers.defaultVisitor.apply(this, arguments);
1330 }
1331 }, options));
1332}
1333
1334/**
1335 * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
1336 *
1337 * @param {string} name - The name of the property to get.
1338 *
1339 * @returns An array of strings.
1340 */
1341function parsePropPath(name) {
1342 // foo[x][y][z]
1343 // foo.x.y.z
1344 // foo-x-y-z
1345 // foo x y z
1346 return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
1347 return match[0] === '[]' ? '' : match[1] || match[0];
1348 });
1349}
1350
1351/**
1352 * Convert an array to an object.
1353 *
1354 * @param {Array<any>} arr - The array to convert to an object.
1355 *
1356 * @returns An object with the same keys and values as the array.
1357 */
1358function arrayToObject(arr) {
1359 const obj = {};
1360 const keys = Object.keys(arr);
1361 let i;
1362 const len = keys.length;
1363 let key;
1364 for (i = 0; i < len; i++) {
1365 key = keys[i];
1366 obj[key] = arr[key];
1367 }
1368 return obj;
1369}
1370
1371/**
1372 * It takes a FormData object and returns a JavaScript object
1373 *
1374 * @param {string} formData The FormData object to convert to JSON.
1375 *
1376 * @returns {Object<string, any> | null} The converted object.
1377 */
1378function formDataToJSON(formData) {
1379 function buildPath(path, value, target, index) {
1380 let name = path[index++];
1381
1382 if (name === '__proto__') return true;
1383
1384 const isNumericKey = Number.isFinite(+name);
1385 const isLast = index >= path.length;
1386 name = !name && utils$1.isArray(target) ? target.length : name;
1387
1388 if (isLast) {
1389 if (utils$1.hasOwnProp(target, name)) {
1390 target[name] = [target[name], value];
1391 } else {
1392 target[name] = value;
1393 }
1394
1395 return !isNumericKey;
1396 }
1397
1398 if (!target[name] || !utils$1.isObject(target[name])) {
1399 target[name] = [];
1400 }
1401
1402 const result = buildPath(path, value, target[name], index);
1403
1404 if (result && utils$1.isArray(target[name])) {
1405 target[name] = arrayToObject(target[name]);
1406 }
1407
1408 return !isNumericKey;
1409 }
1410
1411 if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1412 const obj = {};
1413
1414 utils$1.forEachEntry(formData, (name, value) => {
1415 buildPath(parsePropPath(name), value, obj, 0);
1416 });
1417
1418 return obj;
1419 }
1420
1421 return null;
1422}
1423
1424/**
1425 * It takes a string, tries to parse it, and if it fails, it returns the stringified version
1426 * of the input
1427 *
1428 * @param {any} rawValue - The value to be stringified.
1429 * @param {Function} parser - A function that parses a string into a JavaScript object.
1430 * @param {Function} encoder - A function that takes a value and returns a string.
1431 *
1432 * @returns {string} A stringified version of the rawValue.
1433 */
1434function stringifySafely(rawValue, parser, encoder) {
1435 if (utils$1.isString(rawValue)) {
1436 try {
1437 (parser || JSON.parse)(rawValue);
1438 return utils$1.trim(rawValue);
1439 } catch (e) {
1440 if (e.name !== 'SyntaxError') {
1441 throw e;
1442 }
1443 }
1444 }
1445
1446 return (encoder || JSON.stringify)(rawValue);
1447}
1448
1449const defaults = {
1450
1451 transitional: transitionalDefaults,
1452
1453 adapter: ['xhr', 'http', 'fetch'],
1454
1455 transformRequest: [function transformRequest(data, headers) {
1456 const contentType = headers.getContentType() || '';
1457 const hasJSONContentType = contentType.indexOf('application/json') > -1;
1458 const isObjectPayload = utils$1.isObject(data);
1459
1460 if (isObjectPayload && utils$1.isHTMLForm(data)) {
1461 data = new FormData(data);
1462 }
1463
1464 const isFormData = utils$1.isFormData(data);
1465
1466 if (isFormData) {
1467 return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1468 }
1469
1470 if (utils$1.isArrayBuffer(data) ||
1471 utils$1.isBuffer(data) ||
1472 utils$1.isStream(data) ||
1473 utils$1.isFile(data) ||
1474 utils$1.isBlob(data) ||
1475 utils$1.isReadableStream(data)
1476 ) {
1477 return data;
1478 }
1479 if (utils$1.isArrayBufferView(data)) {
1480 return data.buffer;
1481 }
1482 if (utils$1.isURLSearchParams(data)) {
1483 headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
1484 return data.toString();
1485 }
1486
1487 let isFileList;
1488
1489 if (isObjectPayload) {
1490 if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
1491 return toURLEncodedForm(data, this.formSerializer).toString();
1492 }
1493
1494 if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
1495 const _FormData = this.env && this.env.FormData;
1496
1497 return toFormData$1(
1498 isFileList ? {'files[]': data} : data,
1499 _FormData && new _FormData(),
1500 this.formSerializer
1501 );
1502 }
1503 }
1504
1505 if (isObjectPayload || hasJSONContentType ) {
1506 headers.setContentType('application/json', false);
1507 return stringifySafely(data);
1508 }
1509
1510 return data;
1511 }],
1512
1513 transformResponse: [function transformResponse(data) {
1514 const transitional = this.transitional || defaults.transitional;
1515 const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1516 const JSONRequested = this.responseType === 'json';
1517
1518 if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1519 return data;
1520 }
1521
1522 if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
1523 const silentJSONParsing = transitional && transitional.silentJSONParsing;
1524 const strictJSONParsing = !silentJSONParsing && JSONRequested;
1525
1526 try {
1527 return JSON.parse(data);
1528 } catch (e) {
1529 if (strictJSONParsing) {
1530 if (e.name === 'SyntaxError') {
1531 throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
1532 }
1533 throw e;
1534 }
1535 }
1536 }
1537
1538 return data;
1539 }],
1540
1541 /**
1542 * A timeout in milliseconds to abort a request. If set to 0 (default) a
1543 * timeout is not created.
1544 */
1545 timeout: 0,
1546
1547 xsrfCookieName: 'XSRF-TOKEN',
1548 xsrfHeaderName: 'X-XSRF-TOKEN',
1549
1550 maxContentLength: -1,
1551 maxBodyLength: -1,
1552
1553 env: {
1554 FormData: platform.classes.FormData,
1555 Blob: platform.classes.Blob
1556 },
1557
1558 validateStatus: function validateStatus(status) {
1559 return status >= 200 && status < 300;
1560 },
1561
1562 headers: {
1563 common: {
1564 'Accept': 'application/json, text/plain, */*',
1565 'Content-Type': undefined
1566 }
1567 }
1568};
1569
1570utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
1571 defaults.headers[method] = {};
1572});
1573
1574const defaults$1 = defaults;
1575
1576// RawAxiosHeaders whose duplicates are ignored by node
1577// c.f. https://nodejs.org/api/http.html#http_message_headers
1578const ignoreDuplicateOf = utils$1.toObjectSet([
1579 'age', 'authorization', 'content-length', 'content-type', 'etag',
1580 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1581 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1582 'referer', 'retry-after', 'user-agent'
1583]);
1584
1585/**
1586 * Parse headers into an object
1587 *
1588 * ```
1589 * Date: Wed, 27 Aug 2014 08:58:49 GMT
1590 * Content-Type: application/json
1591 * Connection: keep-alive
1592 * Transfer-Encoding: chunked
1593 * ```
1594 *
1595 * @param {String} rawHeaders Headers needing to be parsed
1596 *
1597 * @returns {Object} Headers parsed into an object
1598 */
1599const parseHeaders = rawHeaders => {
1600 const parsed = {};
1601 let key;
1602 let val;
1603 let i;
1604
1605 rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
1606 i = line.indexOf(':');
1607 key = line.substring(0, i).trim().toLowerCase();
1608 val = line.substring(i + 1).trim();
1609
1610 if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
1611 return;
1612 }
1613
1614 if (key === 'set-cookie') {
1615 if (parsed[key]) {
1616 parsed[key].push(val);
1617 } else {
1618 parsed[key] = [val];
1619 }
1620 } else {
1621 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1622 }
1623 });
1624
1625 return parsed;
1626};
1627
1628const $internals = Symbol('internals');
1629
1630function normalizeHeader(header) {
1631 return header && String(header).trim().toLowerCase();
1632}
1633
1634function normalizeValue(value) {
1635 if (value === false || value == null) {
1636 return value;
1637 }
1638
1639 return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1640}
1641
1642function parseTokens(str) {
1643 const tokens = Object.create(null);
1644 const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1645 let match;
1646
1647 while ((match = tokensRE.exec(str))) {
1648 tokens[match[1]] = match[2];
1649 }
1650
1651 return tokens;
1652}
1653
1654const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1655
1656function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
1657 if (utils$1.isFunction(filter)) {
1658 return filter.call(this, value, header);
1659 }
1660
1661 if (isHeaderNameFilter) {
1662 value = header;
1663 }
1664
1665 if (!utils$1.isString(value)) return;
1666
1667 if (utils$1.isString(filter)) {
1668 return value.indexOf(filter) !== -1;
1669 }
1670
1671 if (utils$1.isRegExp(filter)) {
1672 return filter.test(value);
1673 }
1674}
1675
1676function formatHeader(header) {
1677 return header.trim()
1678 .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1679 return char.toUpperCase() + str;
1680 });
1681}
1682
1683function buildAccessors(obj, header) {
1684 const accessorName = utils$1.toCamelCase(' ' + header);
1685
1686 ['get', 'set', 'has'].forEach(methodName => {
1687 Object.defineProperty(obj, methodName + accessorName, {
1688 value: function(arg1, arg2, arg3) {
1689 return this[methodName].call(this, header, arg1, arg2, arg3);
1690 },
1691 configurable: true
1692 });
1693 });
1694}
1695
1696class AxiosHeaders$1 {
1697 constructor(headers) {
1698 headers && this.set(headers);
1699 }
1700
1701 set(header, valueOrRewrite, rewrite) {
1702 const self = this;
1703
1704 function setHeader(_value, _header, _rewrite) {
1705 const lHeader = normalizeHeader(_header);
1706
1707 if (!lHeader) {
1708 throw new Error('header name must be a non-empty string');
1709 }
1710
1711 const key = utils$1.findKey(self, lHeader);
1712
1713 if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
1714 self[key || _header] = normalizeValue(_value);
1715 }
1716 }
1717
1718 const setHeaders = (headers, _rewrite) =>
1719 utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1720
1721 if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1722 setHeaders(header, valueOrRewrite);
1723 } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1724 setHeaders(parseHeaders(header), valueOrRewrite);
1725 } else if (utils$1.isHeaders(header)) {
1726 for (const [key, value] of header.entries()) {
1727 setHeader(value, key, rewrite);
1728 }
1729 } else {
1730 header != null && setHeader(valueOrRewrite, header, rewrite);
1731 }
1732
1733 return this;
1734 }
1735
1736 get(header, parser) {
1737 header = normalizeHeader(header);
1738
1739 if (header) {
1740 const key = utils$1.findKey(this, header);
1741
1742 if (key) {
1743 const value = this[key];
1744
1745 if (!parser) {
1746 return value;
1747 }
1748
1749 if (parser === true) {
1750 return parseTokens(value);
1751 }
1752
1753 if (utils$1.isFunction(parser)) {
1754 return parser.call(this, value, key);
1755 }
1756
1757 if (utils$1.isRegExp(parser)) {
1758 return parser.exec(value);
1759 }
1760
1761 throw new TypeError('parser must be boolean|regexp|function');
1762 }
1763 }
1764 }
1765
1766 has(header, matcher) {
1767 header = normalizeHeader(header);
1768
1769 if (header) {
1770 const key = utils$1.findKey(this, header);
1771
1772 return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1773 }
1774
1775 return false;
1776 }
1777
1778 delete(header, matcher) {
1779 const self = this;
1780 let deleted = false;
1781
1782 function deleteHeader(_header) {
1783 _header = normalizeHeader(_header);
1784
1785 if (_header) {
1786 const key = utils$1.findKey(self, _header);
1787
1788 if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
1789 delete self[key];
1790
1791 deleted = true;
1792 }
1793 }
1794 }
1795
1796 if (utils$1.isArray(header)) {
1797 header.forEach(deleteHeader);
1798 } else {
1799 deleteHeader(header);
1800 }
1801
1802 return deleted;
1803 }
1804
1805 clear(matcher) {
1806 const keys = Object.keys(this);
1807 let i = keys.length;
1808 let deleted = false;
1809
1810 while (i--) {
1811 const key = keys[i];
1812 if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1813 delete this[key];
1814 deleted = true;
1815 }
1816 }
1817
1818 return deleted;
1819 }
1820
1821 normalize(format) {
1822 const self = this;
1823 const headers = {};
1824
1825 utils$1.forEach(this, (value, header) => {
1826 const key = utils$1.findKey(headers, header);
1827
1828 if (key) {
1829 self[key] = normalizeValue(value);
1830 delete self[header];
1831 return;
1832 }
1833
1834 const normalized = format ? formatHeader(header) : String(header).trim();
1835
1836 if (normalized !== header) {
1837 delete self[header];
1838 }
1839
1840 self[normalized] = normalizeValue(value);
1841
1842 headers[normalized] = true;
1843 });
1844
1845 return this;
1846 }
1847
1848 concat(...targets) {
1849 return this.constructor.concat(this, ...targets);
1850 }
1851
1852 toJSON(asStrings) {
1853 const obj = Object.create(null);
1854
1855 utils$1.forEach(this, (value, header) => {
1856 value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
1857 });
1858
1859 return obj;
1860 }
1861
1862 [Symbol.iterator]() {
1863 return Object.entries(this.toJSON())[Symbol.iterator]();
1864 }
1865
1866 toString() {
1867 return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
1868 }
1869
1870 get [Symbol.toStringTag]() {
1871 return 'AxiosHeaders';
1872 }
1873
1874 static from(thing) {
1875 return thing instanceof this ? thing : new this(thing);
1876 }
1877
1878 static concat(first, ...targets) {
1879 const computed = new this(first);
1880
1881 targets.forEach((target) => computed.set(target));
1882
1883 return computed;
1884 }
1885
1886 static accessor(header) {
1887 const internals = this[$internals] = (this[$internals] = {
1888 accessors: {}
1889 });
1890
1891 const accessors = internals.accessors;
1892 const prototype = this.prototype;
1893
1894 function defineAccessor(_header) {
1895 const lHeader = normalizeHeader(_header);
1896
1897 if (!accessors[lHeader]) {
1898 buildAccessors(prototype, _header);
1899 accessors[lHeader] = true;
1900 }
1901 }
1902
1903 utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1904
1905 return this;
1906 }
1907}
1908
1909AxiosHeaders$1.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
1910
1911// reserved names hotfix
1912utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({value}, key) => {
1913 let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
1914 return {
1915 get: () => value,
1916 set(headerValue) {
1917 this[mapped] = headerValue;
1918 }
1919 }
1920});
1921
1922utils$1.freezeMethods(AxiosHeaders$1);
1923
1924const AxiosHeaders$2 = AxiosHeaders$1;
1925
1926/**
1927 * Transform the data for a request or a response
1928 *
1929 * @param {Array|Function} fns A single function or Array of functions
1930 * @param {?Object} response The response object
1931 *
1932 * @returns {*} The resulting transformed data
1933 */
1934function transformData(fns, response) {
1935 const config = this || defaults$1;
1936 const context = response || config;
1937 const headers = AxiosHeaders$2.from(context.headers);
1938 let data = context.data;
1939
1940 utils$1.forEach(fns, function transform(fn) {
1941 data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
1942 });
1943
1944 headers.normalize();
1945
1946 return data;
1947}
1948
1949function isCancel$1(value) {
1950 return !!(value && value.__CANCEL__);
1951}
1952
1953/**
1954 * A `CanceledError` is an object that is thrown when an operation is canceled.
1955 *
1956 * @param {string=} message The message.
1957 * @param {Object=} config The config.
1958 * @param {Object=} request The request.
1959 *
1960 * @returns {CanceledError} The created error.
1961 */
1962function CanceledError$1(message, config, request) {
1963 // eslint-disable-next-line no-eq-null,eqeqeq
1964 AxiosError$1.call(this, message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request);
1965 this.name = 'CanceledError';
1966}
1967
1968utils$1.inherits(CanceledError$1, AxiosError$1, {
1969 __CANCEL__: true
1970});
1971
1972/**
1973 * Resolve or reject a Promise based on response status.
1974 *
1975 * @param {Function} resolve A function that resolves the promise.
1976 * @param {Function} reject A function that rejects the promise.
1977 * @param {object} response The response.
1978 *
1979 * @returns {object} The response.
1980 */
1981function settle(resolve, reject, response) {
1982 const validateStatus = response.config.validateStatus;
1983 if (!response.status || !validateStatus || validateStatus(response.status)) {
1984 resolve(response);
1985 } else {
1986 reject(new AxiosError$1(
1987 'Request failed with status code ' + response.status,
1988 [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
1989 response.config,
1990 response.request,
1991 response
1992 ));
1993 }
1994}
1995
1996function parseProtocol(url) {
1997 const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
1998 return match && match[1] || '';
1999}
2000
2001/**
2002 * Calculate data maxRate
2003 * @param {Number} [samplesCount= 10]
2004 * @param {Number} [min= 1000]
2005 * @returns {Function}
2006 */
2007function speedometer(samplesCount, min) {
2008 samplesCount = samplesCount || 10;
2009 const bytes = new Array(samplesCount);
2010 const timestamps = new Array(samplesCount);
2011 let head = 0;
2012 let tail = 0;
2013 let firstSampleTS;
2014
2015 min = min !== undefined ? min : 1000;
2016
2017 return function push(chunkLength) {
2018 const now = Date.now();
2019
2020 const startedAt = timestamps[tail];
2021
2022 if (!firstSampleTS) {
2023 firstSampleTS = now;
2024 }
2025
2026 bytes[head] = chunkLength;
2027 timestamps[head] = now;
2028
2029 let i = tail;
2030 let bytesCount = 0;
2031
2032 while (i !== head) {
2033 bytesCount += bytes[i++];
2034 i = i % samplesCount;
2035 }
2036
2037 head = (head + 1) % samplesCount;
2038
2039 if (head === tail) {
2040 tail = (tail + 1) % samplesCount;
2041 }
2042
2043 if (now - firstSampleTS < min) {
2044 return;
2045 }
2046
2047 const passed = startedAt && now - startedAt;
2048
2049 return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2050 };
2051}
2052
2053/**
2054 * Throttle decorator
2055 * @param {Function} fn
2056 * @param {Number} freq
2057 * @return {Function}
2058 */
2059function throttle(fn, freq) {
2060 let timestamp = 0;
2061 let threshold = 1000 / freq;
2062 let lastArgs;
2063 let timer;
2064
2065 const invoke = (args, now = Date.now()) => {
2066 timestamp = now;
2067 lastArgs = null;
2068 if (timer) {
2069 clearTimeout(timer);
2070 timer = null;
2071 }
2072 fn.apply(null, args);
2073 };
2074
2075 const throttled = (...args) => {
2076 const now = Date.now();
2077 const passed = now - timestamp;
2078 if ( passed >= threshold) {
2079 invoke(args, now);
2080 } else {
2081 lastArgs = args;
2082 if (!timer) {
2083 timer = setTimeout(() => {
2084 timer = null;
2085 invoke(lastArgs);
2086 }, threshold - passed);
2087 }
2088 }
2089 };
2090
2091 const flush = () => lastArgs && invoke(lastArgs);
2092
2093 return [throttled, flush];
2094}
2095
2096const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
2097 let bytesNotified = 0;
2098 const _speedometer = speedometer(50, 250);
2099
2100 return throttle(e => {
2101 const loaded = e.loaded;
2102 const total = e.lengthComputable ? e.total : undefined;
2103 const progressBytes = loaded - bytesNotified;
2104 const rate = _speedometer(progressBytes);
2105 const inRange = loaded <= total;
2106
2107 bytesNotified = loaded;
2108
2109 const data = {
2110 loaded,
2111 total,
2112 progress: total ? (loaded / total) : undefined,
2113 bytes: progressBytes,
2114 rate: rate ? rate : undefined,
2115 estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
2116 event: e,
2117 lengthComputable: total != null,
2118 [isDownloadStream ? 'download' : 'upload']: true
2119 };
2120
2121 listener(data);
2122 }, freq);
2123};
2124
2125const progressEventDecorator = (total, throttled) => {
2126 const lengthComputable = total != null;
2127
2128 return [(loaded) => throttled[0]({
2129 lengthComputable,
2130 total,
2131 loaded
2132 }), throttled[1]];
2133};
2134
2135const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
2136
2137const isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {
2138 url = new URL(url, platform.origin);
2139
2140 return (
2141 origin.protocol === url.protocol &&
2142 origin.host === url.host &&
2143 (isMSIE || origin.port === url.port)
2144 );
2145})(
2146 new URL(platform.origin),
2147 platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
2148) : () => true;
2149
2150const cookies = platform.hasStandardBrowserEnv ?
2151
2152 // Standard browser envs support document.cookie
2153 {
2154 write(name, value, expires, path, domain, secure) {
2155 const cookie = [name + '=' + encodeURIComponent(value)];
2156
2157 utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
2158
2159 utils$1.isString(path) && cookie.push('path=' + path);
2160
2161 utils$1.isString(domain) && cookie.push('domain=' + domain);
2162
2163 secure === true && cookie.push('secure');
2164
2165 document.cookie = cookie.join('; ');
2166 },
2167
2168 read(name) {
2169 const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
2170 return (match ? decodeURIComponent(match[3]) : null);
2171 },
2172
2173 remove(name) {
2174 this.write(name, '', Date.now() - 86400000);
2175 }
2176 }
2177
2178 :
2179
2180 // Non-standard browser env (web workers, react-native) lack needed support.
2181 {
2182 write() {},
2183 read() {
2184 return null;
2185 },
2186 remove() {}
2187 };
2188
2189/**
2190 * Determines whether the specified URL is absolute
2191 *
2192 * @param {string} url The URL to test
2193 *
2194 * @returns {boolean} True if the specified URL is absolute, otherwise false
2195 */
2196function isAbsoluteURL(url) {
2197 // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
2198 // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
2199 // by any combination of letters, digits, plus, period, or hyphen.
2200 return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
2201}
2202
2203/**
2204 * Creates a new URL by combining the specified URLs
2205 *
2206 * @param {string} baseURL The base URL
2207 * @param {string} relativeURL The relative URL
2208 *
2209 * @returns {string} The combined URL
2210 */
2211function combineURLs(baseURL, relativeURL) {
2212 return relativeURL
2213 ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
2214 : baseURL;
2215}
2216
2217/**
2218 * Creates a new URL by combining the baseURL with the requestedURL,
2219 * only when the requestedURL is not already an absolute URL.
2220 * If the requestURL is absolute, this function returns the requestedURL untouched.
2221 *
2222 * @param {string} baseURL The base URL
2223 * @param {string} requestedURL Absolute or relative URL to combine
2224 *
2225 * @returns {string} The combined full path
2226 */
2227function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
2228 let isRelativeUrl = !isAbsoluteURL(requestedURL);
2229 if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
2230 return combineURLs(baseURL, requestedURL);
2231 }
2232 return requestedURL;
2233}
2234
2235const headersToObject = (thing) => thing instanceof AxiosHeaders$2 ? { ...thing } : thing;
2236
2237/**
2238 * Config-specific merge-function which creates a new config-object
2239 * by merging two configuration objects together.
2240 *
2241 * @param {Object} config1
2242 * @param {Object} config2
2243 *
2244 * @returns {Object} New object resulting from merging config2 to config1
2245 */
2246function mergeConfig$1(config1, config2) {
2247 // eslint-disable-next-line no-param-reassign
2248 config2 = config2 || {};
2249 const config = {};
2250
2251 function getMergedValue(target, source, prop, caseless) {
2252 if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
2253 return utils$1.merge.call({caseless}, target, source);
2254 } else if (utils$1.isPlainObject(source)) {
2255 return utils$1.merge({}, source);
2256 } else if (utils$1.isArray(source)) {
2257 return source.slice();
2258 }
2259 return source;
2260 }
2261
2262 // eslint-disable-next-line consistent-return
2263 function mergeDeepProperties(a, b, prop , caseless) {
2264 if (!utils$1.isUndefined(b)) {
2265 return getMergedValue(a, b, prop , caseless);
2266 } else if (!utils$1.isUndefined(a)) {
2267 return getMergedValue(undefined, a, prop , caseless);
2268 }
2269 }
2270
2271 // eslint-disable-next-line consistent-return
2272 function valueFromConfig2(a, b) {
2273 if (!utils$1.isUndefined(b)) {
2274 return getMergedValue(undefined, b);
2275 }
2276 }
2277
2278 // eslint-disable-next-line consistent-return
2279 function defaultToConfig2(a, b) {
2280 if (!utils$1.isUndefined(b)) {
2281 return getMergedValue(undefined, b);
2282 } else if (!utils$1.isUndefined(a)) {
2283 return getMergedValue(undefined, a);
2284 }
2285 }
2286
2287 // eslint-disable-next-line consistent-return
2288 function mergeDirectKeys(a, b, prop) {
2289 if (prop in config2) {
2290 return getMergedValue(a, b);
2291 } else if (prop in config1) {
2292 return getMergedValue(undefined, a);
2293 }
2294 }
2295
2296 const mergeMap = {
2297 url: valueFromConfig2,
2298 method: valueFromConfig2,
2299 data: valueFromConfig2,
2300 baseURL: defaultToConfig2,
2301 transformRequest: defaultToConfig2,
2302 transformResponse: defaultToConfig2,
2303 paramsSerializer: defaultToConfig2,
2304 timeout: defaultToConfig2,
2305 timeoutMessage: defaultToConfig2,
2306 withCredentials: defaultToConfig2,
2307 withXSRFToken: defaultToConfig2,
2308 adapter: defaultToConfig2,
2309 responseType: defaultToConfig2,
2310 xsrfCookieName: defaultToConfig2,
2311 xsrfHeaderName: defaultToConfig2,
2312 onUploadProgress: defaultToConfig2,
2313 onDownloadProgress: defaultToConfig2,
2314 decompress: defaultToConfig2,
2315 maxContentLength: defaultToConfig2,
2316 maxBodyLength: defaultToConfig2,
2317 beforeRedirect: defaultToConfig2,
2318 transport: defaultToConfig2,
2319 httpAgent: defaultToConfig2,
2320 httpsAgent: defaultToConfig2,
2321 cancelToken: defaultToConfig2,
2322 socketPath: defaultToConfig2,
2323 responseEncoding: defaultToConfig2,
2324 validateStatus: mergeDirectKeys,
2325 headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)
2326 };
2327
2328 utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
2329 const merge = mergeMap[prop] || mergeDeepProperties;
2330 const configValue = merge(config1[prop], config2[prop], prop);
2331 (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
2332 });
2333
2334 return config;
2335}
2336
2337const resolveConfig = (config) => {
2338 const newConfig = mergeConfig$1({}, config);
2339
2340 let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;
2341
2342 newConfig.headers = headers = AxiosHeaders$2.from(headers);
2343
2344 newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
2345
2346 // HTTP basic authentication
2347 if (auth) {
2348 headers.set('Authorization', 'Basic ' +
2349 btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
2350 );
2351 }
2352
2353 let contentType;
2354
2355 if (utils$1.isFormData(data)) {
2356 if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
2357 headers.setContentType(undefined); // Let the browser set it
2358 } else if ((contentType = headers.getContentType()) !== false) {
2359 // fix semicolon duplication issue for ReactNative FormData implementation
2360 const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
2361 headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
2362 }
2363 }
2364
2365 // Add xsrf header
2366 // This is only done if running in a standard browser environment.
2367 // Specifically not if we're in a web worker, or react-native.
2368
2369 if (platform.hasStandardBrowserEnv) {
2370 withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
2371
2372 if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
2373 // Add xsrf header
2374 const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
2375
2376 if (xsrfValue) {
2377 headers.set(xsrfHeaderName, xsrfValue);
2378 }
2379 }
2380 }
2381
2382 return newConfig;
2383};
2384
2385const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
2386
2387const xhrAdapter = isXHRAdapterSupported && function (config) {
2388 return new Promise(function dispatchXhrRequest(resolve, reject) {
2389 const _config = resolveConfig(config);
2390 let requestData = _config.data;
2391 const requestHeaders = AxiosHeaders$2.from(_config.headers).normalize();
2392 let {responseType, onUploadProgress, onDownloadProgress} = _config;
2393 let onCanceled;
2394 let uploadThrottled, downloadThrottled;
2395 let flushUpload, flushDownload;
2396
2397 function done() {
2398 flushUpload && flushUpload(); // flush events
2399 flushDownload && flushDownload(); // flush events
2400
2401 _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
2402
2403 _config.signal && _config.signal.removeEventListener('abort', onCanceled);
2404 }
2405
2406 let request = new XMLHttpRequest();
2407
2408 request.open(_config.method.toUpperCase(), _config.url, true);
2409
2410 // Set the request timeout in MS
2411 request.timeout = _config.timeout;
2412
2413 function onloadend() {
2414 if (!request) {
2415 return;
2416 }
2417 // Prepare the response
2418 const responseHeaders = AxiosHeaders$2.from(
2419 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
2420 );
2421 const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
2422 request.responseText : request.response;
2423 const response = {
2424 data: responseData,
2425 status: request.status,
2426 statusText: request.statusText,
2427 headers: responseHeaders,
2428 config,
2429 request
2430 };
2431
2432 settle(function _resolve(value) {
2433 resolve(value);
2434 done();
2435 }, function _reject(err) {
2436 reject(err);
2437 done();
2438 }, response);
2439
2440 // Clean up request
2441 request = null;
2442 }
2443
2444 if ('onloadend' in request) {
2445 // Use onloadend if available
2446 request.onloadend = onloadend;
2447 } else {
2448 // Listen for ready state to emulate onloadend
2449 request.onreadystatechange = function handleLoad() {
2450 if (!request || request.readyState !== 4) {
2451 return;
2452 }
2453
2454 // The request errored out and we didn't get a response, this will be
2455 // handled by onerror instead
2456 // With one exception: request that using file: protocol, most browsers
2457 // will return status as 0 even though it's a successful request
2458 if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
2459 return;
2460 }
2461 // readystate handler is calling before onerror or ontimeout handlers,
2462 // so we should call onloadend on the next 'tick'
2463 setTimeout(onloadend);
2464 };
2465 }
2466
2467 // Handle browser request cancellation (as opposed to a manual cancellation)
2468 request.onabort = function handleAbort() {
2469 if (!request) {
2470 return;
2471 }
2472
2473 reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request));
2474
2475 // Clean up request
2476 request = null;
2477 };
2478
2479 // Handle low level network errors
2480 request.onerror = function handleError() {
2481 // Real errors are hidden from us by the browser
2482 // onerror should only fire if it's a network error
2483 reject(new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request));
2484
2485 // Clean up request
2486 request = null;
2487 };
2488
2489 // Handle timeout
2490 request.ontimeout = function handleTimeout() {
2491 let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
2492 const transitional = _config.transitional || transitionalDefaults;
2493 if (_config.timeoutErrorMessage) {
2494 timeoutErrorMessage = _config.timeoutErrorMessage;
2495 }
2496 reject(new AxiosError$1(
2497 timeoutErrorMessage,
2498 transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
2499 config,
2500 request));
2501
2502 // Clean up request
2503 request = null;
2504 };
2505
2506 // Remove Content-Type if data is undefined
2507 requestData === undefined && requestHeaders.setContentType(null);
2508
2509 // Add headers to the request
2510 if ('setRequestHeader' in request) {
2511 utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2512 request.setRequestHeader(key, val);
2513 });
2514 }
2515
2516 // Add withCredentials to request if needed
2517 if (!utils$1.isUndefined(_config.withCredentials)) {
2518 request.withCredentials = !!_config.withCredentials;
2519 }
2520
2521 // Add responseType to request if needed
2522 if (responseType && responseType !== 'json') {
2523 request.responseType = _config.responseType;
2524 }
2525
2526 // Handle progress if needed
2527 if (onDownloadProgress) {
2528 ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
2529 request.addEventListener('progress', downloadThrottled);
2530 }
2531
2532 // Not all browsers support upload events
2533 if (onUploadProgress && request.upload) {
2534 ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
2535
2536 request.upload.addEventListener('progress', uploadThrottled);
2537
2538 request.upload.addEventListener('loadend', flushUpload);
2539 }
2540
2541 if (_config.cancelToken || _config.signal) {
2542 // Handle cancellation
2543 // eslint-disable-next-line func-names
2544 onCanceled = cancel => {
2545 if (!request) {
2546 return;
2547 }
2548 reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel);
2549 request.abort();
2550 request = null;
2551 };
2552
2553 _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
2554 if (_config.signal) {
2555 _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
2556 }
2557 }
2558
2559 const protocol = parseProtocol(_config.url);
2560
2561 if (protocol && platform.protocols.indexOf(protocol) === -1) {
2562 reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config));
2563 return;
2564 }
2565
2566
2567 // Send the request
2568 request.send(requestData || null);
2569 });
2570};
2571
2572const composeSignals = (signals, timeout) => {
2573 const {length} = (signals = signals ? signals.filter(Boolean) : []);
2574
2575 if (timeout || length) {
2576 let controller = new AbortController();
2577
2578 let aborted;
2579
2580 const onabort = function (reason) {
2581 if (!aborted) {
2582 aborted = true;
2583 unsubscribe();
2584 const err = reason instanceof Error ? reason : this.reason;
2585 controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
2586 }
2587 };
2588
2589 let timer = timeout && setTimeout(() => {
2590 timer = null;
2591 onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT));
2592 }, timeout);
2593
2594 const unsubscribe = () => {
2595 if (signals) {
2596 timer && clearTimeout(timer);
2597 timer = null;
2598 signals.forEach(signal => {
2599 signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
2600 });
2601 signals = null;
2602 }
2603 };
2604
2605 signals.forEach((signal) => signal.addEventListener('abort', onabort));
2606
2607 const {signal} = controller;
2608
2609 signal.unsubscribe = () => utils$1.asap(unsubscribe);
2610
2611 return signal;
2612 }
2613};
2614
2615const composeSignals$1 = composeSignals;
2616
2617const streamChunk = function* (chunk, chunkSize) {
2618 let len = chunk.byteLength;
2619
2620 if (!chunkSize || len < chunkSize) {
2621 yield chunk;
2622 return;
2623 }
2624
2625 let pos = 0;
2626 let end;
2627
2628 while (pos < len) {
2629 end = pos + chunkSize;
2630 yield chunk.slice(pos, end);
2631 pos = end;
2632 }
2633};
2634
2635const readBytes = async function* (iterable, chunkSize) {
2636 for await (const chunk of readStream(iterable)) {
2637 yield* streamChunk(chunk, chunkSize);
2638 }
2639};
2640
2641const readStream = async function* (stream) {
2642 if (stream[Symbol.asyncIterator]) {
2643 yield* stream;
2644 return;
2645 }
2646
2647 const reader = stream.getReader();
2648 try {
2649 for (;;) {
2650 const {done, value} = await reader.read();
2651 if (done) {
2652 break;
2653 }
2654 yield value;
2655 }
2656 } finally {
2657 await reader.cancel();
2658 }
2659};
2660
2661const trackStream = (stream, chunkSize, onProgress, onFinish) => {
2662 const iterator = readBytes(stream, chunkSize);
2663
2664 let bytes = 0;
2665 let done;
2666 let _onFinish = (e) => {
2667 if (!done) {
2668 done = true;
2669 onFinish && onFinish(e);
2670 }
2671 };
2672
2673 return new ReadableStream({
2674 async pull(controller) {
2675 try {
2676 const {done, value} = await iterator.next();
2677
2678 if (done) {
2679 _onFinish();
2680 controller.close();
2681 return;
2682 }
2683
2684 let len = value.byteLength;
2685 if (onProgress) {
2686 let loadedBytes = bytes += len;
2687 onProgress(loadedBytes);
2688 }
2689 controller.enqueue(new Uint8Array(value));
2690 } catch (err) {
2691 _onFinish(err);
2692 throw err;
2693 }
2694 },
2695 cancel(reason) {
2696 _onFinish(reason);
2697 return iterator.return();
2698 }
2699 }, {
2700 highWaterMark: 2
2701 })
2702};
2703
2704const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
2705const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
2706
2707// used only inside the fetch adapter
2708const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
2709 ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
2710 async (str) => new Uint8Array(await new Response(str).arrayBuffer())
2711);
2712
2713const test = (fn, ...args) => {
2714 try {
2715 return !!fn(...args);
2716 } catch (e) {
2717 return false
2718 }
2719};
2720
2721const supportsRequestStream = isReadableStreamSupported && test(() => {
2722 let duplexAccessed = false;
2723
2724 const hasContentType = new Request(platform.origin, {
2725 body: new ReadableStream(),
2726 method: 'POST',
2727 get duplex() {
2728 duplexAccessed = true;
2729 return 'half';
2730 },
2731 }).headers.has('Content-Type');
2732
2733 return duplexAccessed && !hasContentType;
2734});
2735
2736const DEFAULT_CHUNK_SIZE = 64 * 1024;
2737
2738const supportsResponseStream = isReadableStreamSupported &&
2739 test(() => utils$1.isReadableStream(new Response('').body));
2740
2741
2742const resolvers = {
2743 stream: supportsResponseStream && ((res) => res.body)
2744};
2745
2746isFetchSupported && (((res) => {
2747 ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
2748 !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() :
2749 (_, config) => {
2750 throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config);
2751 });
2752 });
2753})(new Response));
2754
2755const getBodyLength = async (body) => {
2756 if (body == null) {
2757 return 0;
2758 }
2759
2760 if(utils$1.isBlob(body)) {
2761 return body.size;
2762 }
2763
2764 if(utils$1.isSpecCompliantForm(body)) {
2765 const _request = new Request(platform.origin, {
2766 method: 'POST',
2767 body,
2768 });
2769 return (await _request.arrayBuffer()).byteLength;
2770 }
2771
2772 if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
2773 return body.byteLength;
2774 }
2775
2776 if(utils$1.isURLSearchParams(body)) {
2777 body = body + '';
2778 }
2779
2780 if(utils$1.isString(body)) {
2781 return (await encodeText(body)).byteLength;
2782 }
2783};
2784
2785const resolveBodyLength = async (headers, body) => {
2786 const length = utils$1.toFiniteNumber(headers.getContentLength());
2787
2788 return length == null ? getBodyLength(body) : length;
2789};
2790
2791const fetchAdapter = isFetchSupported && (async (config) => {
2792 let {
2793 url,
2794 method,
2795 data,
2796 signal,
2797 cancelToken,
2798 timeout,
2799 onDownloadProgress,
2800 onUploadProgress,
2801 responseType,
2802 headers,
2803 withCredentials = 'same-origin',
2804 fetchOptions
2805 } = resolveConfig(config);
2806
2807 responseType = responseType ? (responseType + '').toLowerCase() : 'text';
2808
2809 let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
2810
2811 let request;
2812
2813 const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
2814 composedSignal.unsubscribe();
2815 });
2816
2817 let requestContentLength;
2818
2819 try {
2820 if (
2821 onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
2822 (requestContentLength = await resolveBodyLength(headers, data)) !== 0
2823 ) {
2824 let _request = new Request(url, {
2825 method: 'POST',
2826 body: data,
2827 duplex: "half"
2828 });
2829
2830 let contentTypeHeader;
2831
2832 if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
2833 headers.setContentType(contentTypeHeader);
2834 }
2835
2836 if (_request.body) {
2837 const [onProgress, flush] = progressEventDecorator(
2838 requestContentLength,
2839 progressEventReducer(asyncDecorator(onUploadProgress))
2840 );
2841
2842 data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
2843 }
2844 }
2845
2846 if (!utils$1.isString(withCredentials)) {
2847 withCredentials = withCredentials ? 'include' : 'omit';
2848 }
2849
2850 // Cloudflare Workers throws when credentials are defined
2851 // see https://github.com/cloudflare/workerd/issues/902
2852 const isCredentialsSupported = "credentials" in Request.prototype;
2853 request = new Request(url, {
2854 ...fetchOptions,
2855 signal: composedSignal,
2856 method: method.toUpperCase(),
2857 headers: headers.normalize().toJSON(),
2858 body: data,
2859 duplex: "half",
2860 credentials: isCredentialsSupported ? withCredentials : undefined
2861 });
2862
2863 let response = await fetch(request);
2864
2865 const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
2866
2867 if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
2868 const options = {};
2869
2870 ['status', 'statusText', 'headers'].forEach(prop => {
2871 options[prop] = response[prop];
2872 });
2873
2874 const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
2875
2876 const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
2877 responseContentLength,
2878 progressEventReducer(asyncDecorator(onDownloadProgress), true)
2879 ) || [];
2880
2881 response = new Response(
2882 trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
2883 flush && flush();
2884 unsubscribe && unsubscribe();
2885 }),
2886 options
2887 );
2888 }
2889
2890 responseType = responseType || 'text';
2891
2892 let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
2893
2894 !isStreamResponse && unsubscribe && unsubscribe();
2895
2896 return await new Promise((resolve, reject) => {
2897 settle(resolve, reject, {
2898 data: responseData,
2899 headers: AxiosHeaders$2.from(response.headers),
2900 status: response.status,
2901 statusText: response.statusText,
2902 config,
2903 request
2904 });
2905 })
2906 } catch (err) {
2907 unsubscribe && unsubscribe();
2908
2909 if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {
2910 throw Object.assign(
2911 new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request),
2912 {
2913 cause: err.cause || err
2914 }
2915 )
2916 }
2917
2918 throw AxiosError$1.from(err, err && err.code, config, request);
2919 }
2920});
2921
2922const knownAdapters = {
2923 http: httpAdapter,
2924 xhr: xhrAdapter,
2925 fetch: fetchAdapter
2926};
2927
2928utils$1.forEach(knownAdapters, (fn, value) => {
2929 if (fn) {
2930 try {
2931 Object.defineProperty(fn, 'name', {value});
2932 } catch (e) {
2933 // eslint-disable-next-line no-empty
2934 }
2935 Object.defineProperty(fn, 'adapterName', {value});
2936 }
2937});
2938
2939const renderReason = (reason) => `- ${reason}`;
2940
2941const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
2942
2943const adapters = {
2944 getAdapter: (adapters) => {
2945 adapters = utils$1.isArray(adapters) ? adapters : [adapters];
2946
2947 const {length} = adapters;
2948 let nameOrAdapter;
2949 let adapter;
2950
2951 const rejectedReasons = {};
2952
2953 for (let i = 0; i < length; i++) {
2954 nameOrAdapter = adapters[i];
2955 let id;
2956
2957 adapter = nameOrAdapter;
2958
2959 if (!isResolvedHandle(nameOrAdapter)) {
2960 adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
2961
2962 if (adapter === undefined) {
2963 throw new AxiosError$1(`Unknown adapter '${id}'`);
2964 }
2965 }
2966
2967 if (adapter) {
2968 break;
2969 }
2970
2971 rejectedReasons[id || '#' + i] = adapter;
2972 }
2973
2974 if (!adapter) {
2975
2976 const reasons = Object.entries(rejectedReasons)
2977 .map(([id, state]) => `adapter ${id} ` +
2978 (state === false ? 'is not supported by the environment' : 'is not available in the build')
2979 );
2980
2981 let s = length ?
2982 (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
2983 'as no adapter specified';
2984
2985 throw new AxiosError$1(
2986 `There is no suitable adapter to dispatch the request ` + s,
2987 'ERR_NOT_SUPPORT'
2988 );
2989 }
2990
2991 return adapter;
2992 },
2993 adapters: knownAdapters
2994};
2995
2996/**
2997 * Throws a `CanceledError` if cancellation has been requested.
2998 *
2999 * @param {Object} config The config that is to be used for the request
3000 *
3001 * @returns {void}
3002 */
3003function throwIfCancellationRequested(config) {
3004 if (config.cancelToken) {
3005 config.cancelToken.throwIfRequested();
3006 }
3007
3008 if (config.signal && config.signal.aborted) {
3009 throw new CanceledError$1(null, config);
3010 }
3011}
3012
3013/**
3014 * Dispatch a request to the server using the configured adapter.
3015 *
3016 * @param {object} config The config that is to be used for the request
3017 *
3018 * @returns {Promise} The Promise to be fulfilled
3019 */
3020function dispatchRequest(config) {
3021 throwIfCancellationRequested(config);
3022
3023 config.headers = AxiosHeaders$2.from(config.headers);
3024
3025 // Transform request data
3026 config.data = transformData.call(
3027 config,
3028 config.transformRequest
3029 );
3030
3031 if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
3032 config.headers.setContentType('application/x-www-form-urlencoded', false);
3033 }
3034
3035 const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter);
3036
3037 return adapter(config).then(function onAdapterResolution(response) {
3038 throwIfCancellationRequested(config);
3039
3040 // Transform response data
3041 response.data = transformData.call(
3042 config,
3043 config.transformResponse,
3044 response
3045 );
3046
3047 response.headers = AxiosHeaders$2.from(response.headers);
3048
3049 return response;
3050 }, function onAdapterRejection(reason) {
3051 if (!isCancel$1(reason)) {
3052 throwIfCancellationRequested(config);
3053
3054 // Transform response data
3055 if (reason && reason.response) {
3056 reason.response.data = transformData.call(
3057 config,
3058 config.transformResponse,
3059 reason.response
3060 );
3061 reason.response.headers = AxiosHeaders$2.from(reason.response.headers);
3062 }
3063 }
3064
3065 return Promise.reject(reason);
3066 });
3067}
3068
3069const VERSION$1 = "1.8.4";
3070
3071const validators$1 = {};
3072
3073// eslint-disable-next-line func-names
3074['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
3075 validators$1[type] = function validator(thing) {
3076 return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
3077 };
3078});
3079
3080const deprecatedWarnings = {};
3081
3082/**
3083 * Transitional option validator
3084 *
3085 * @param {function|boolean?} validator - set to false if the transitional option has been removed
3086 * @param {string?} version - deprecated version / removed since version
3087 * @param {string?} message - some message with additional info
3088 *
3089 * @returns {function}
3090 */
3091validators$1.transitional = function transitional(validator, version, message) {
3092 function formatMessage(opt, desc) {
3093 return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
3094 }
3095
3096 // eslint-disable-next-line func-names
3097 return (value, opt, opts) => {
3098 if (validator === false) {
3099 throw new AxiosError$1(
3100 formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
3101 AxiosError$1.ERR_DEPRECATED
3102 );
3103 }
3104
3105 if (version && !deprecatedWarnings[opt]) {
3106 deprecatedWarnings[opt] = true;
3107 // eslint-disable-next-line no-console
3108 console.warn(
3109 formatMessage(
3110 opt,
3111 ' has been deprecated since v' + version + ' and will be removed in the near future'
3112 )
3113 );
3114 }
3115
3116 return validator ? validator(value, opt, opts) : true;
3117 };
3118};
3119
3120validators$1.spelling = function spelling(correctSpelling) {
3121 return (value, opt) => {
3122 // eslint-disable-next-line no-console
3123 console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
3124 return true;
3125 }
3126};
3127
3128/**
3129 * Assert object's properties type
3130 *
3131 * @param {object} options
3132 * @param {object} schema
3133 * @param {boolean?} allowUnknown
3134 *
3135 * @returns {object}
3136 */
3137
3138function assertOptions(options, schema, allowUnknown) {
3139 if (typeof options !== 'object') {
3140 throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE);
3141 }
3142 const keys = Object.keys(options);
3143 let i = keys.length;
3144 while (i-- > 0) {
3145 const opt = keys[i];
3146 const validator = schema[opt];
3147 if (validator) {
3148 const value = options[opt];
3149 const result = value === undefined || validator(value, opt, options);
3150 if (result !== true) {
3151 throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
3152 }
3153 continue;
3154 }
3155 if (allowUnknown !== true) {
3156 throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION);
3157 }
3158 }
3159}
3160
3161const validator = {
3162 assertOptions,
3163 validators: validators$1
3164};
3165
3166const validators = validator.validators;
3167
3168/**
3169 * Create a new instance of Axios
3170 *
3171 * @param {Object} instanceConfig The default config for the instance
3172 *
3173 * @return {Axios} A new instance of Axios
3174 */
3175class Axios$1 {
3176 constructor(instanceConfig) {
3177 this.defaults = instanceConfig;
3178 this.interceptors = {
3179 request: new InterceptorManager$1(),
3180 response: new InterceptorManager$1()
3181 };
3182 }
3183
3184 /**
3185 * Dispatch a request
3186 *
3187 * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
3188 * @param {?Object} config
3189 *
3190 * @returns {Promise} The Promise to be fulfilled
3191 */
3192 async request(configOrUrl, config) {
3193 try {
3194 return await this._request(configOrUrl, config);
3195 } catch (err) {
3196 if (err instanceof Error) {
3197 let dummy = {};
3198
3199 Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());
3200
3201 // slice off the Error: ... line
3202 const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
3203 try {
3204 if (!err.stack) {
3205 err.stack = stack;
3206 // match without the 2 top stack lines
3207 } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
3208 err.stack += '\n' + stack;
3209 }
3210 } catch (e) {
3211 // ignore the case where "stack" is an un-writable property
3212 }
3213 }
3214
3215 throw err;
3216 }
3217 }
3218
3219 _request(configOrUrl, config) {
3220 /*eslint no-param-reassign:0*/
3221 // Allow for axios('example/url'[, config]) a la fetch API
3222 if (typeof configOrUrl === 'string') {
3223 config = config || {};
3224 config.url = configOrUrl;
3225 } else {
3226 config = configOrUrl || {};
3227 }
3228
3229 config = mergeConfig$1(this.defaults, config);
3230
3231 const {transitional, paramsSerializer, headers} = config;
3232
3233 if (transitional !== undefined) {
3234 validator.assertOptions(transitional, {
3235 silentJSONParsing: validators.transitional(validators.boolean),
3236 forcedJSONParsing: validators.transitional(validators.boolean),
3237 clarifyTimeoutError: validators.transitional(validators.boolean)
3238 }, false);
3239 }
3240
3241 if (paramsSerializer != null) {
3242 if (utils$1.isFunction(paramsSerializer)) {
3243 config.paramsSerializer = {
3244 serialize: paramsSerializer
3245 };
3246 } else {
3247 validator.assertOptions(paramsSerializer, {
3248 encode: validators.function,
3249 serialize: validators.function
3250 }, true);
3251 }
3252 }
3253
3254 // Set config.allowAbsoluteUrls
3255 if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
3256 config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
3257 } else {
3258 config.allowAbsoluteUrls = true;
3259 }
3260
3261 validator.assertOptions(config, {
3262 baseUrl: validators.spelling('baseURL'),
3263 withXsrfToken: validators.spelling('withXSRFToken')
3264 }, true);
3265
3266 // Set config.method
3267 config.method = (config.method || this.defaults.method || 'get').toLowerCase();
3268
3269 // Flatten headers
3270 let contextHeaders = headers && utils$1.merge(
3271 headers.common,
3272 headers[config.method]
3273 );
3274
3275 headers && utils$1.forEach(
3276 ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
3277 (method) => {
3278 delete headers[method];
3279 }
3280 );
3281
3282 config.headers = AxiosHeaders$2.concat(contextHeaders, headers);
3283
3284 // filter out skipped interceptors
3285 const requestInterceptorChain = [];
3286 let synchronousRequestInterceptors = true;
3287 this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
3288 if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
3289 return;
3290 }
3291
3292 synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
3293
3294 requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3295 });
3296
3297 const responseInterceptorChain = [];
3298 this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
3299 responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3300 });
3301
3302 let promise;
3303 let i = 0;
3304 let len;
3305
3306 if (!synchronousRequestInterceptors) {
3307 const chain = [dispatchRequest.bind(this), undefined];
3308 chain.unshift.apply(chain, requestInterceptorChain);
3309 chain.push.apply(chain, responseInterceptorChain);
3310 len = chain.length;
3311
3312 promise = Promise.resolve(config);
3313
3314 while (i < len) {
3315 promise = promise.then(chain[i++], chain[i++]);
3316 }
3317
3318 return promise;
3319 }
3320
3321 len = requestInterceptorChain.length;
3322
3323 let newConfig = config;
3324
3325 i = 0;
3326
3327 while (i < len) {
3328 const onFulfilled = requestInterceptorChain[i++];
3329 const onRejected = requestInterceptorChain[i++];
3330 try {
3331 newConfig = onFulfilled(newConfig);
3332 } catch (error) {
3333 onRejected.call(this, error);
3334 break;
3335 }
3336 }
3337
3338 try {
3339 promise = dispatchRequest.call(this, newConfig);
3340 } catch (error) {
3341 return Promise.reject(error);
3342 }
3343
3344 i = 0;
3345 len = responseInterceptorChain.length;
3346
3347 while (i < len) {
3348 promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3349 }
3350
3351 return promise;
3352 }
3353
3354 getUri(config) {
3355 config = mergeConfig$1(this.defaults, config);
3356 const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
3357 return buildURL(fullPath, config.params, config.paramsSerializer);
3358 }
3359}
3360
3361// Provide aliases for supported request methods
3362utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
3363 /*eslint func-names:0*/
3364 Axios$1.prototype[method] = function(url, config) {
3365 return this.request(mergeConfig$1(config || {}, {
3366 method,
3367 url,
3368 data: (config || {}).data
3369 }));
3370 };
3371});
3372
3373utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
3374 /*eslint func-names:0*/
3375
3376 function generateHTTPMethod(isForm) {
3377 return function httpMethod(url, data, config) {
3378 return this.request(mergeConfig$1(config || {}, {
3379 method,
3380 headers: isForm ? {
3381 'Content-Type': 'multipart/form-data'
3382 } : {},
3383 url,
3384 data
3385 }));
3386 };
3387 }
3388
3389 Axios$1.prototype[method] = generateHTTPMethod();
3390
3391 Axios$1.prototype[method + 'Form'] = generateHTTPMethod(true);
3392});
3393
3394const Axios$2 = Axios$1;
3395
3396/**
3397 * A `CancelToken` is an object that can be used to request cancellation of an operation.
3398 *
3399 * @param {Function} executor The executor function.
3400 *
3401 * @returns {CancelToken}
3402 */
3403class CancelToken$1 {
3404 constructor(executor) {
3405 if (typeof executor !== 'function') {
3406 throw new TypeError('executor must be a function.');
3407 }
3408
3409 let resolvePromise;
3410
3411 this.promise = new Promise(function promiseExecutor(resolve) {
3412 resolvePromise = resolve;
3413 });
3414
3415 const token = this;
3416
3417 // eslint-disable-next-line func-names
3418 this.promise.then(cancel => {
3419 if (!token._listeners) return;
3420
3421 let i = token._listeners.length;
3422
3423 while (i-- > 0) {
3424 token._listeners[i](cancel);
3425 }
3426 token._listeners = null;
3427 });
3428
3429 // eslint-disable-next-line func-names
3430 this.promise.then = onfulfilled => {
3431 let _resolve;
3432 // eslint-disable-next-line func-names
3433 const promise = new Promise(resolve => {
3434 token.subscribe(resolve);
3435 _resolve = resolve;
3436 }).then(onfulfilled);
3437
3438 promise.cancel = function reject() {
3439 token.unsubscribe(_resolve);
3440 };
3441
3442 return promise;
3443 };
3444
3445 executor(function cancel(message, config, request) {
3446 if (token.reason) {
3447 // Cancellation has already been requested
3448 return;
3449 }
3450
3451 token.reason = new CanceledError$1(message, config, request);
3452 resolvePromise(token.reason);
3453 });
3454 }
3455
3456 /**
3457 * Throws a `CanceledError` if cancellation has been requested.
3458 */
3459 throwIfRequested() {
3460 if (this.reason) {
3461 throw this.reason;
3462 }
3463 }
3464
3465 /**
3466 * Subscribe to the cancel signal
3467 */
3468
3469 subscribe(listener) {
3470 if (this.reason) {
3471 listener(this.reason);
3472 return;
3473 }
3474
3475 if (this._listeners) {
3476 this._listeners.push(listener);
3477 } else {
3478 this._listeners = [listener];
3479 }
3480 }
3481
3482 /**
3483 * Unsubscribe from the cancel signal
3484 */
3485
3486 unsubscribe(listener) {
3487 if (!this._listeners) {
3488 return;
3489 }
3490 const index = this._listeners.indexOf(listener);
3491 if (index !== -1) {
3492 this._listeners.splice(index, 1);
3493 }
3494 }
3495
3496 toAbortSignal() {
3497 const controller = new AbortController();
3498
3499 const abort = (err) => {
3500 controller.abort(err);
3501 };
3502
3503 this.subscribe(abort);
3504
3505 controller.signal.unsubscribe = () => this.unsubscribe(abort);
3506
3507 return controller.signal;
3508 }
3509
3510 /**
3511 * Returns an object that contains a new `CancelToken` and a function that, when called,
3512 * cancels the `CancelToken`.
3513 */
3514 static source() {
3515 let cancel;
3516 const token = new CancelToken$1(function executor(c) {
3517 cancel = c;
3518 });
3519 return {
3520 token,
3521 cancel
3522 };
3523 }
3524}
3525
3526const CancelToken$2 = CancelToken$1;
3527
3528/**
3529 * Syntactic sugar for invoking a function and expanding an array for arguments.
3530 *
3531 * Common use case would be to use `Function.prototype.apply`.
3532 *
3533 * ```js
3534 * function f(x, y, z) {}
3535 * var args = [1, 2, 3];
3536 * f.apply(null, args);
3537 * ```
3538 *
3539 * With `spread` this example can be re-written.
3540 *
3541 * ```js
3542 * spread(function(x, y, z) {})([1, 2, 3]);
3543 * ```
3544 *
3545 * @param {Function} callback
3546 *
3547 * @returns {Function}
3548 */
3549function spread$1(callback) {
3550 return function wrap(arr) {
3551 return callback.apply(null, arr);
3552 };
3553}
3554
3555/**
3556 * Determines whether the payload is an error thrown by Axios
3557 *
3558 * @param {*} payload The value to test
3559 *
3560 * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3561 */
3562function isAxiosError$1(payload) {
3563 return utils$1.isObject(payload) && (payload.isAxiosError === true);
3564}
3565
3566const HttpStatusCode$1 = {
3567 Continue: 100,
3568 SwitchingProtocols: 101,
3569 Processing: 102,
3570 EarlyHints: 103,
3571 Ok: 200,
3572 Created: 201,
3573 Accepted: 202,
3574 NonAuthoritativeInformation: 203,
3575 NoContent: 204,
3576 ResetContent: 205,
3577 PartialContent: 206,
3578 MultiStatus: 207,
3579 AlreadyReported: 208,
3580 ImUsed: 226,
3581 MultipleChoices: 300,
3582 MovedPermanently: 301,
3583 Found: 302,
3584 SeeOther: 303,
3585 NotModified: 304,
3586 UseProxy: 305,
3587 Unused: 306,
3588 TemporaryRedirect: 307,
3589 PermanentRedirect: 308,
3590 BadRequest: 400,
3591 Unauthorized: 401,
3592 PaymentRequired: 402,
3593 Forbidden: 403,
3594 NotFound: 404,
3595 MethodNotAllowed: 405,
3596 NotAcceptable: 406,
3597 ProxyAuthenticationRequired: 407,
3598 RequestTimeout: 408,
3599 Conflict: 409,
3600 Gone: 410,
3601 LengthRequired: 411,
3602 PreconditionFailed: 412,
3603 PayloadTooLarge: 413,
3604 UriTooLong: 414,
3605 UnsupportedMediaType: 415,
3606 RangeNotSatisfiable: 416,
3607 ExpectationFailed: 417,
3608 ImATeapot: 418,
3609 MisdirectedRequest: 421,
3610 UnprocessableEntity: 422,
3611 Locked: 423,
3612 FailedDependency: 424,
3613 TooEarly: 425,
3614 UpgradeRequired: 426,
3615 PreconditionRequired: 428,
3616 TooManyRequests: 429,
3617 RequestHeaderFieldsTooLarge: 431,
3618 UnavailableForLegalReasons: 451,
3619 InternalServerError: 500,
3620 NotImplemented: 501,
3621 BadGateway: 502,
3622 ServiceUnavailable: 503,
3623 GatewayTimeout: 504,
3624 HttpVersionNotSupported: 505,
3625 VariantAlsoNegotiates: 506,
3626 InsufficientStorage: 507,
3627 LoopDetected: 508,
3628 NotExtended: 510,
3629 NetworkAuthenticationRequired: 511,
3630};
3631
3632Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
3633 HttpStatusCode$1[value] = key;
3634});
3635
3636const HttpStatusCode$2 = HttpStatusCode$1;
3637
3638/**
3639 * Create an instance of Axios
3640 *
3641 * @param {Object} defaultConfig The default config for the instance
3642 *
3643 * @returns {Axios} A new instance of Axios
3644 */
3645function createInstance(defaultConfig) {
3646 const context = new Axios$2(defaultConfig);
3647 const instance = bind(Axios$2.prototype.request, context);
3648
3649 // Copy axios.prototype to instance
3650 utils$1.extend(instance, Axios$2.prototype, context, {allOwnKeys: true});
3651
3652 // Copy context to instance
3653 utils$1.extend(instance, context, null, {allOwnKeys: true});
3654
3655 // Factory for creating new instances
3656 instance.create = function create(instanceConfig) {
3657 return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
3658 };
3659
3660 return instance;
3661}
3662
3663// Create the default instance to be exported
3664const axios = createInstance(defaults$1);
3665
3666// Expose Axios class to allow class inheritance
3667axios.Axios = Axios$2;
3668
3669// Expose Cancel & CancelToken
3670axios.CanceledError = CanceledError$1;
3671axios.CancelToken = CancelToken$2;
3672axios.isCancel = isCancel$1;
3673axios.VERSION = VERSION$1;
3674axios.toFormData = toFormData$1;
3675
3676// Expose AxiosError class
3677axios.AxiosError = AxiosError$1;
3678
3679// alias for CanceledError for backward compatibility
3680axios.Cancel = axios.CanceledError;
3681
3682// Expose all/spread
3683axios.all = function all(promises) {
3684 return Promise.all(promises);
3685};
3686
3687axios.spread = spread$1;
3688
3689// Expose isAxiosError
3690axios.isAxiosError = isAxiosError$1;
3691
3692// Expose mergeConfig
3693axios.mergeConfig = mergeConfig$1;
3694
3695axios.AxiosHeaders = AxiosHeaders$2;
3696
3697axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
3698
3699axios.getAdapter = adapters.getAdapter;
3700
3701axios.HttpStatusCode = HttpStatusCode$2;
3702
3703axios.default = axios;
3704
3705// this module should only have a default export
3706const axios$1 = axios;
3707
3708// This module is intended to unwrap Axios default export as named.
3709// Keep top-level export same with static properties
3710// so that it can keep same with es module or cjs
3711const {
3712 Axios,
3713 AxiosError,
3714 CanceledError,
3715 isCancel,
3716 CancelToken,
3717 VERSION,
3718 all,
3719 Cancel,
3720 isAxiosError,
3721 spread,
3722 toFormData,
3723 AxiosHeaders,
3724 HttpStatusCode,
3725 formToJSON,
3726 getAdapter,
3727 mergeConfig
3728} = axios$1;
3729
3730export { Axios, AxiosError, AxiosHeaders, Cancel, CancelToken, CanceledError, HttpStatusCode, VERSION, all, axios$1 as default, formToJSON, getAdapter, isAxiosError, isCancel, mergeConfig, spread, toFormData };
3731//# sourceMappingURL=axios.js.map
Note: See TracBrowser for help on using the repository browser.