axios 1.15.2 → 1.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +103 -6
  2. package/README.md +396 -25
  3. package/dist/axios.js +1455 -1109
  4. package/dist/axios.js.map +1 -1
  5. package/dist/axios.min.js +3 -3
  6. package/dist/axios.min.js.map +1 -1
  7. package/dist/browser/axios.cjs +1569 -1174
  8. package/dist/browser/axios.cjs.map +1 -1
  9. package/dist/esm/axios.js +1569 -1173
  10. package/dist/esm/axios.js.map +1 -1
  11. package/dist/esm/axios.min.js +2 -2
  12. package/dist/esm/axios.min.js.map +1 -1
  13. package/dist/node/axios.cjs +1395 -915
  14. package/dist/node/axios.cjs.map +1 -1
  15. package/index.d.cts +25 -13
  16. package/index.d.ts +21 -4
  17. package/index.js +2 -0
  18. package/lib/adapters/adapters.js +4 -2
  19. package/lib/adapters/fetch.js +131 -11
  20. package/lib/adapters/http.js +298 -69
  21. package/lib/adapters/xhr.js +8 -3
  22. package/lib/core/Axios.js +7 -3
  23. package/lib/core/AxiosError.js +86 -1
  24. package/lib/core/AxiosHeaders.js +4 -33
  25. package/lib/core/dispatchRequest.js +19 -7
  26. package/lib/core/mergeConfig.js +6 -3
  27. package/lib/core/settle.js +7 -11
  28. package/lib/defaults/index.js +1 -1
  29. package/lib/env/data.js +1 -1
  30. package/lib/helpers/buildURL.js +1 -1
  31. package/lib/helpers/composeSignals.js +48 -47
  32. package/lib/helpers/cookies.js +14 -2
  33. package/lib/helpers/estimateDataURLDecodedBytes.js +28 -1
  34. package/lib/helpers/formDataToJSON.js +1 -1
  35. package/lib/helpers/formDataToStream.js +1 -1
  36. package/lib/helpers/fromDataURI.js +18 -5
  37. package/lib/helpers/parseProtocol.js +1 -1
  38. package/lib/helpers/progressEventReducer.js +3 -0
  39. package/lib/helpers/resolveConfig.js +33 -17
  40. package/lib/helpers/sanitizeHeaderValue.js +60 -0
  41. package/lib/helpers/shouldBypassProxy.js +26 -1
  42. package/lib/helpers/validator.js +1 -1
  43. package/lib/utils.js +35 -22
  44. package/package.json +19 -24
@@ -1,9 +1,10 @@
1
- /*! Axios v1.15.2 Copyright (c) 2026 Matt Zabriskie and contributors */
1
+ /*! Axios v1.16.1 Copyright (c) 2026 Matt Zabriskie and contributors */
2
2
  'use strict';
3
3
 
4
4
  var FormData$1 = require('form-data');
5
5
  var crypto = require('crypto');
6
6
  var url = require('url');
7
+ var HttpsProxyAgent = require('https-proxy-agent');
7
8
  var http = require('http');
8
9
  var https = require('https');
9
10
  var http2 = require('http2');
@@ -208,9 +209,9 @@ const isFile = kindOfTest('File');
208
209
  * also have a `name` and `type` attribute to specify filename and content type
209
210
  *
210
211
  * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
211
- *
212
+ *
212
213
  * @param {*} value The value to test
213
- *
214
+ *
214
215
  * @returns {boolean} True if value is a React Native Blob, otherwise false
215
216
  */
216
217
  const isReactNativeBlob = value => {
@@ -220,9 +221,9 @@ const isReactNativeBlob = value => {
220
221
  /**
221
222
  * Determine if environment is React Native
222
223
  * ReactNative `FormData` has a non-standard `getParts()` method
223
- *
224
+ *
224
225
  * @param {*} formData The formData to test
225
- *
226
+ *
226
227
  * @returns {boolean} True if environment is React Native, otherwise false
227
228
  */
228
229
  const isReactNative = formData => formData && typeof formData.getParts !== 'undefined';
@@ -241,7 +242,7 @@ const isBlob = kindOfTest('Blob');
241
242
  *
242
243
  * @param {*} val The value to test
243
244
  *
244
- * @returns {boolean} True if value is a File, otherwise false
245
+ * @returns {boolean} True if value is a FileList, otherwise false
245
246
  */
246
247
  const isFileList = kindOfTest('FileList');
247
248
 
@@ -273,7 +274,7 @@ const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
273
274
  const isFormData = thing => {
274
275
  if (!thing) return false;
275
276
  if (FormDataCtor && thing instanceof FormDataCtor) return true;
276
- // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData (GHSA-6chq-wfr3-2hj9).
277
+ // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
277
278
  const proto = getPrototypeOf(thing);
278
279
  if (!proto || proto === Object.prototype) return false;
279
280
  if (!isFunction$1(thing.append)) return false;
@@ -405,8 +406,7 @@ const isContextDefined = context => !isUndefined(context) && context !== _global
405
406
  *
406
407
  * @returns {Object} Result of all merge properties
407
408
  */
408
- function merge(/* obj1, obj2, obj3, ... */
409
- ) {
409
+ function merge(...objs) {
410
410
  const {
411
411
  caseless,
412
412
  skipUndefined
@@ -418,8 +418,12 @@ function merge(/* obj1, obj2, obj3, ... */
418
418
  return;
419
419
  }
420
420
  const targetKey = caseless && findKey(result, key) || key;
421
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
422
- result[targetKey] = merge(result[targetKey], val);
421
+ // Read via own-prop only — a bare `result[targetKey]` walks the prototype
422
+ // chain, so a polluted Object.prototype value could surface here and get
423
+ // copied into the merged result.
424
+ const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
425
+ if (isPlainObject(existing) && isPlainObject(val)) {
426
+ result[targetKey] = merge(existing, val);
423
427
  } else if (isPlainObject(val)) {
424
428
  result[targetKey] = merge({}, val);
425
429
  } else if (isArray(val)) {
@@ -428,8 +432,8 @@ function merge(/* obj1, obj2, obj3, ... */
428
432
  result[targetKey] = val;
429
433
  }
430
434
  };
431
- for (let i = 0, l = arguments.length; i < l; i++) {
432
- arguments[i] && forEach(arguments[i], assignValue);
435
+ for (let i = 0, l = objs.length; i < l; i++) {
436
+ objs[i] && forEach(objs[i], assignValue);
433
437
  }
434
438
  return result;
435
439
  }
@@ -451,6 +455,9 @@ const extend = (a, b, thisArg, {
451
455
  forEach(b, (val, key) => {
452
456
  if (thisArg && isFunction$1(val)) {
453
457
  Object.defineProperty(a, key, {
458
+ // Null-proto descriptor so a polluted Object.prototype.get cannot
459
+ // hijack defineProperty's accessor-vs-data resolution.
460
+ __proto__: null,
454
461
  value: bind(val, thisArg),
455
462
  writable: true,
456
463
  enumerable: true,
@@ -458,6 +465,7 @@ const extend = (a, b, thisArg, {
458
465
  });
459
466
  } else {
460
467
  Object.defineProperty(a, key, {
468
+ __proto__: null,
461
469
  value: val,
462
470
  writable: true,
463
471
  enumerable: true,
@@ -496,12 +504,14 @@ const stripBOM = content => {
496
504
  const inherits = (constructor, superConstructor, props, descriptors) => {
497
505
  constructor.prototype = Object.create(superConstructor.prototype, descriptors);
498
506
  Object.defineProperty(constructor.prototype, 'constructor', {
507
+ __proto__: null,
499
508
  value: constructor,
500
509
  writable: true,
501
510
  enumerable: false,
502
511
  configurable: true
503
512
  });
504
513
  Object.defineProperty(constructor, 'super', {
514
+ __proto__: null,
505
515
  value: superConstructor.prototype
506
516
  });
507
517
  props && Object.assign(constructor.prototype, props);
@@ -669,7 +679,7 @@ const reduceDescriptors = (obj, reducer) => {
669
679
  const freezeMethods = obj => {
670
680
  reduceDescriptors(obj, (descriptor, name) => {
671
681
  // skip restricted props in strict mode
672
- if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
682
+ if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
673
683
  return false;
674
684
  }
675
685
  const value = obj[name];
@@ -728,10 +738,10 @@ function isSpecCompliantForm(thing) {
728
738
  * @returns {Object} The JSON-compatible object.
729
739
  */
730
740
  const toJSONObject = obj => {
731
- const stack = new Array(10);
732
- const visit = (source, i) => {
741
+ const visited = new WeakSet();
742
+ const visit = source => {
733
743
  if (isObject(source)) {
734
- if (stack.indexOf(source) >= 0) {
744
+ if (visited.has(source)) {
735
745
  return;
736
746
  }
737
747
 
@@ -740,19 +750,20 @@ const toJSONObject = obj => {
740
750
  return source;
741
751
  }
742
752
  if (!('toJSON' in source)) {
743
- stack[i] = source;
753
+ // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
754
+ visited.add(source);
744
755
  const target = isArray(source) ? [] : {};
745
756
  forEach(source, (value, key) => {
746
- const reducedValue = visit(value, i + 1);
757
+ const reducedValue = visit(value);
747
758
  !isUndefined(reducedValue) && (target[key] = reducedValue);
748
759
  });
749
- stack[i] = undefined;
760
+ visited.delete(source);
750
761
  return target;
751
762
  }
752
763
  }
753
764
  return source;
754
765
  };
755
- return visit(obj, 0);
766
+ return visit(obj);
756
767
  };
757
768
 
758
769
  /**
@@ -876,395 +887,782 @@ var utils$1 = {
876
887
  isIterable
877
888
  };
878
889
 
879
- class AxiosError extends Error {
880
- static from(error, code, config, request, response, customProps) {
881
- const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
882
- axiosError.cause = error;
883
- axiosError.name = error.name;
890
+ // RawAxiosHeaders whose duplicates are ignored by node
891
+ // c.f. https://nodejs.org/api/http.html#http_message_headers
892
+ const ignoreDuplicateOf = utils$1.toObjectSet(['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']);
884
893
 
885
- // Preserve status from the original error if not already set from response
886
- if (error.status != null && axiosError.status == null) {
887
- axiosError.status = error.status;
894
+ /**
895
+ * Parse headers into an object
896
+ *
897
+ * ```
898
+ * Date: Wed, 27 Aug 2014 08:58:49 GMT
899
+ * Content-Type: application/json
900
+ * Connection: keep-alive
901
+ * Transfer-Encoding: chunked
902
+ * ```
903
+ *
904
+ * @param {String} rawHeaders Headers needing to be parsed
905
+ *
906
+ * @returns {Object} Headers parsed into an object
907
+ */
908
+ var parseHeaders = rawHeaders => {
909
+ const parsed = {};
910
+ let key;
911
+ let val;
912
+ let i;
913
+ rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
914
+ i = line.indexOf(':');
915
+ key = line.substring(0, i).trim().toLowerCase();
916
+ val = line.substring(i + 1).trim();
917
+ if (!key || parsed[key] && ignoreDuplicateOf[key]) {
918
+ return;
888
919
  }
889
- customProps && Object.assign(axiosError, customProps);
890
- return axiosError;
891
- }
892
-
893
- /**
894
- * Create an Error with the specified message, config, error code, request and response.
895
- *
896
- * @param {string} message The error message.
897
- * @param {string} [code] The error code (for example, 'ECONNABORTED').
898
- * @param {Object} [config] The config.
899
- * @param {Object} [request] The request.
900
- * @param {Object} [response] The response.
901
- *
902
- * @returns {Error} The created error.
903
- */
904
- constructor(message, code, config, request, response) {
905
- super(message);
920
+ if (key === 'set-cookie') {
921
+ if (parsed[key]) {
922
+ parsed[key].push(val);
923
+ } else {
924
+ parsed[key] = [val];
925
+ }
926
+ } else {
927
+ parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
928
+ }
929
+ });
930
+ return parsed;
931
+ };
906
932
 
907
- // Make message enumerable to maintain backward compatibility
908
- // The native Error constructor sets message as non-enumerable,
909
- // but axios < v1.13.3 had it as enumerable
910
- Object.defineProperty(this, 'message', {
911
- value: message,
912
- enumerable: true,
913
- writable: true,
914
- configurable: true
915
- });
916
- this.name = 'AxiosError';
917
- this.isAxiosError = true;
918
- code && (this.code = code);
919
- config && (this.config = config);
920
- request && (this.request = request);
921
- if (response) {
922
- this.response = response;
923
- this.status = response.status;
933
+ function trimSPorHTAB(str) {
934
+ let start = 0;
935
+ let end = str.length;
936
+ while (start < end) {
937
+ const code = str.charCodeAt(start);
938
+ if (code !== 0x09 && code !== 0x20) {
939
+ break;
924
940
  }
941
+ start += 1;
925
942
  }
926
- toJSON() {
927
- return {
928
- // Standard
929
- message: this.message,
930
- name: this.name,
931
- // Microsoft
932
- description: this.description,
933
- number: this.number,
934
- // Mozilla
935
- fileName: this.fileName,
936
- lineNumber: this.lineNumber,
937
- columnNumber: this.columnNumber,
938
- stack: this.stack,
939
- // Axios
940
- config: utils$1.toJSONObject(this.config),
941
- code: this.code,
942
- status: this.status
943
- };
943
+ while (end > start) {
944
+ const code = str.charCodeAt(end - 1);
945
+ if (code !== 0x09 && code !== 0x20) {
946
+ break;
947
+ }
948
+ end -= 1;
944
949
  }
950
+ return start === 0 && end === str.length ? str : str.slice(start, end);
945
951
  }
946
952
 
947
- // This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
948
- AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
949
- AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
950
- AxiosError.ECONNABORTED = 'ECONNABORTED';
951
- AxiosError.ETIMEDOUT = 'ETIMEDOUT';
952
- AxiosError.ERR_NETWORK = 'ERR_NETWORK';
953
- AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
954
- AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';
955
- AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
956
- AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
957
- AxiosError.ERR_CANCELED = 'ERR_CANCELED';
958
- AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
959
- AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
960
- AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
961
-
962
- /**
963
- * Determines if the given thing is a array or js object.
964
- *
965
- * @param {string} thing - The object or array to be visited.
966
- *
967
- * @returns {boolean}
968
- */
969
- function isVisitable(thing) {
970
- return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
953
+ // The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
954
+ // eslint-disable-next-line no-control-regex
955
+ const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g');
956
+ // eslint-disable-next-line no-control-regex
957
+ const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g');
958
+ function sanitizeValue(value, invalidChars) {
959
+ if (utils$1.isArray(value)) {
960
+ return value.map(item => sanitizeValue(item, invalidChars));
961
+ }
962
+ return trimSPorHTAB(String(value).replace(invalidChars, ''));
971
963
  }
972
-
973
- /**
974
- * It removes the brackets from the end of a string
975
- *
976
- * @param {string} key - The key of the parameter.
977
- *
978
- * @returns {string} the key without the brackets.
979
- */
980
- function removeBrackets(key) {
981
- return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
964
+ const sanitizeHeaderValue = value => sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
965
+ const sanitizeByteStringHeaderValue = value => sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
966
+ function toByteStringHeaderObject(headers) {
967
+ const byteStringHeaders = Object.create(null);
968
+ utils$1.forEach(headers.toJSON(), (value, header) => {
969
+ byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
970
+ });
971
+ return byteStringHeaders;
982
972
  }
983
973
 
984
- /**
985
- * It takes a path, a key, and a boolean, and returns a string
986
- *
987
- * @param {string} path - The path to the current key.
988
- * @param {string} key - The key of the current object being iterated over.
989
- * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
990
- *
991
- * @returns {string} The path to the current key.
992
- */
993
- function renderKey(path, key, dots) {
994
- if (!path) return key;
995
- return path.concat(key).map(function each(token, i) {
996
- // eslint-disable-next-line no-param-reassign
997
- token = removeBrackets(token);
998
- return !dots && i ? '[' + token + ']' : token;
999
- }).join(dots ? '.' : '');
974
+ const $internals = Symbol('internals');
975
+ function normalizeHeader(header) {
976
+ return header && String(header).trim().toLowerCase();
1000
977
  }
1001
-
1002
- /**
1003
- * If the array is an array and none of its elements are visitable, then it's a flat array.
1004
- *
1005
- * @param {Array<any>} arr - The array to check
1006
- *
1007
- * @returns {boolean}
1008
- */
1009
- function isFlatArray(arr) {
1010
- return utils$1.isArray(arr) && !arr.some(isVisitable);
978
+ function normalizeValue(value) {
979
+ if (value === false || value == null) {
980
+ return value;
981
+ }
982
+ return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
1011
983
  }
1012
- const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
1013
- return /^is[A-Z]/.test(prop);
1014
- });
1015
-
1016
- /**
1017
- * Convert a data object to FormData
1018
- *
1019
- * @param {Object} obj
1020
- * @param {?Object} [formData]
1021
- * @param {?Object} [options]
1022
- * @param {Function} [options.visitor]
1023
- * @param {Boolean} [options.metaTokens = true]
1024
- * @param {Boolean} [options.dots = false]
1025
- * @param {?Boolean} [options.indexes = false]
1026
- *
1027
- * @returns {Object}
1028
- **/
1029
-
1030
- /**
1031
- * It converts an object into a FormData object
1032
- *
1033
- * @param {Object<any, any>} obj - The object to convert to form data.
1034
- * @param {string} formData - The FormData object to append to.
1035
- * @param {Object<string, any>} options
1036
- *
1037
- * @returns
1038
- */
1039
- function toFormData(obj, formData, options) {
1040
- if (!utils$1.isObject(obj)) {
1041
- throw new TypeError('target must be an object');
984
+ function parseTokens(str) {
985
+ const tokens = Object.create(null);
986
+ const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
987
+ let match;
988
+ while (match = tokensRE.exec(str)) {
989
+ tokens[match[1]] = match[2];
1042
990
  }
1043
-
1044
- // eslint-disable-next-line no-param-reassign
1045
- formData = formData || new (FormData$1 || FormData)();
1046
-
1047
- // eslint-disable-next-line no-param-reassign
1048
- options = utils$1.toFlatObject(options, {
1049
- metaTokens: true,
1050
- dots: false,
1051
- indexes: false
1052
- }, false, function defined(option, source) {
1053
- // eslint-disable-next-line no-eq-null,eqeqeq
1054
- return !utils$1.isUndefined(source[option]);
1055
- });
1056
- const metaTokens = options.metaTokens;
1057
- // eslint-disable-next-line no-use-before-define
1058
- const visitor = options.visitor || defaultVisitor;
1059
- const dots = options.dots;
1060
- const indexes = options.indexes;
1061
- const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
1062
- const maxDepth = options.maxDepth === undefined ? 100 : options.maxDepth;
1063
- const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
1064
- if (!utils$1.isFunction(visitor)) {
1065
- throw new TypeError('visitor must be a function');
991
+ return tokens;
992
+ }
993
+ const isValidHeaderName = str => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
994
+ function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
995
+ if (utils$1.isFunction(filter)) {
996
+ return filter.call(this, value, header);
1066
997
  }
1067
- function convertValue(value) {
1068
- if (value === null) return '';
1069
- if (utils$1.isDate(value)) {
1070
- return value.toISOString();
1071
- }
1072
- if (utils$1.isBoolean(value)) {
1073
- return value.toString();
1074
- }
1075
- if (!useBlob && utils$1.isBlob(value)) {
1076
- throw new AxiosError('Blob is not supported. Use a Buffer instead.');
998
+ if (isHeaderNameFilter) {
999
+ value = header;
1000
+ }
1001
+ if (!utils$1.isString(value)) return;
1002
+ if (utils$1.isString(filter)) {
1003
+ return value.indexOf(filter) !== -1;
1004
+ }
1005
+ if (utils$1.isRegExp(filter)) {
1006
+ return filter.test(value);
1007
+ }
1008
+ }
1009
+ function formatHeader(header) {
1010
+ return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1011
+ return char.toUpperCase() + str;
1012
+ });
1013
+ }
1014
+ function buildAccessors(obj, header) {
1015
+ const accessorName = utils$1.toCamelCase(' ' + header);
1016
+ ['get', 'set', 'has'].forEach(methodName => {
1017
+ Object.defineProperty(obj, methodName + accessorName, {
1018
+ // Null-proto descriptor so a polluted Object.prototype.get cannot turn
1019
+ // this data descriptor into an accessor descriptor on the way in.
1020
+ __proto__: null,
1021
+ value: function (arg1, arg2, arg3) {
1022
+ return this[methodName].call(this, header, arg1, arg2, arg3);
1023
+ },
1024
+ configurable: true
1025
+ });
1026
+ });
1027
+ }
1028
+ class AxiosHeaders {
1029
+ constructor(headers) {
1030
+ headers && this.set(headers);
1031
+ }
1032
+ set(header, valueOrRewrite, rewrite) {
1033
+ const self = this;
1034
+ function setHeader(_value, _header, _rewrite) {
1035
+ const lHeader = normalizeHeader(_header);
1036
+ if (!lHeader) {
1037
+ throw new Error('header name must be a non-empty string');
1038
+ }
1039
+ const key = utils$1.findKey(self, lHeader);
1040
+ if (!key || self[key] === undefined || _rewrite === true || _rewrite === undefined && self[key] !== false) {
1041
+ self[key || _header] = normalizeValue(_value);
1042
+ }
1077
1043
  }
1078
- if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
1079
- return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
1044
+ const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1045
+ if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1046
+ setHeaders(header, valueOrRewrite);
1047
+ } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1048
+ setHeaders(parseHeaders(header), valueOrRewrite);
1049
+ } else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
1050
+ let obj = {},
1051
+ dest,
1052
+ key;
1053
+ for (const entry of header) {
1054
+ if (!utils$1.isArray(entry)) {
1055
+ throw TypeError('Object iterator must return a key-value pair');
1056
+ }
1057
+ obj[key = entry[0]] = (dest = obj[key]) ? utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
1058
+ }
1059
+ setHeaders(obj, valueOrRewrite);
1060
+ } else {
1061
+ header != null && setHeader(valueOrRewrite, header, rewrite);
1080
1062
  }
1081
- return value;
1063
+ return this;
1082
1064
  }
1083
-
1084
- /**
1085
- * Default visitor.
1086
- *
1087
- * @param {*} value
1088
- * @param {String|Number} key
1089
- * @param {Array<String|Number>} path
1090
- * @this {FormData}
1091
- *
1092
- * @returns {boolean} return true to visit the each prop of the value recursively
1093
- */
1094
- function defaultVisitor(value, key, path) {
1095
- let arr = value;
1096
- if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
1097
- formData.append(renderKey(path, key, dots), convertValue(value));
1098
- return false;
1099
- }
1100
- if (value && !path && typeof value === 'object') {
1101
- if (utils$1.endsWith(key, '{}')) {
1102
- // eslint-disable-next-line no-param-reassign
1103
- key = metaTokens ? key : key.slice(0, -2);
1104
- // eslint-disable-next-line no-param-reassign
1105
- value = JSON.stringify(value);
1106
- } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))) {
1107
- // eslint-disable-next-line no-param-reassign
1108
- key = removeBrackets(key);
1109
- arr.forEach(function each(el, index) {
1110
- !(utils$1.isUndefined(el) || el === null) && formData.append(
1111
- // eslint-disable-next-line no-nested-ternary
1112
- indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + '[]', convertValue(el));
1113
- });
1114
- return false;
1065
+ get(header, parser) {
1066
+ header = normalizeHeader(header);
1067
+ if (header) {
1068
+ const key = utils$1.findKey(this, header);
1069
+ if (key) {
1070
+ const value = this[key];
1071
+ if (!parser) {
1072
+ return value;
1073
+ }
1074
+ if (parser === true) {
1075
+ return parseTokens(value);
1076
+ }
1077
+ if (utils$1.isFunction(parser)) {
1078
+ return parser.call(this, value, key);
1079
+ }
1080
+ if (utils$1.isRegExp(parser)) {
1081
+ return parser.exec(value);
1082
+ }
1083
+ throw new TypeError('parser must be boolean|regexp|function');
1115
1084
  }
1116
1085
  }
1117
- if (isVisitable(value)) {
1118
- return true;
1086
+ }
1087
+ has(header, matcher) {
1088
+ header = normalizeHeader(header);
1089
+ if (header) {
1090
+ const key = utils$1.findKey(this, header);
1091
+ return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1119
1092
  }
1120
- formData.append(renderKey(path, key, dots), convertValue(value));
1121
1093
  return false;
1122
1094
  }
1123
- const stack = [];
1124
- const exposedHelpers = Object.assign(predicates, {
1125
- defaultVisitor,
1126
- convertValue,
1127
- isVisitable
1128
- });
1129
- function build(value, path, depth = 0) {
1130
- if (utils$1.isUndefined(value)) return;
1131
- if (depth > maxDepth) {
1132
- throw new AxiosError('Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
1095
+ delete(header, matcher) {
1096
+ const self = this;
1097
+ let deleted = false;
1098
+ function deleteHeader(_header) {
1099
+ _header = normalizeHeader(_header);
1100
+ if (_header) {
1101
+ const key = utils$1.findKey(self, _header);
1102
+ if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
1103
+ delete self[key];
1104
+ deleted = true;
1105
+ }
1106
+ }
1133
1107
  }
1134
- if (stack.indexOf(value) !== -1) {
1135
- throw Error('Circular reference detected in ' + path.join('.'));
1108
+ if (utils$1.isArray(header)) {
1109
+ header.forEach(deleteHeader);
1110
+ } else {
1111
+ deleteHeader(header);
1136
1112
  }
1137
- stack.push(value);
1138
- utils$1.forEach(value, function each(el, key) {
1139
- const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
1140
- if (result === true) {
1141
- build(el, path ? path.concat(key) : [key], depth + 1);
1113
+ return deleted;
1114
+ }
1115
+ clear(matcher) {
1116
+ const keys = Object.keys(this);
1117
+ let i = keys.length;
1118
+ let deleted = false;
1119
+ while (i--) {
1120
+ const key = keys[i];
1121
+ if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1122
+ delete this[key];
1123
+ deleted = true;
1124
+ }
1125
+ }
1126
+ return deleted;
1127
+ }
1128
+ normalize(format) {
1129
+ const self = this;
1130
+ const headers = {};
1131
+ utils$1.forEach(this, (value, header) => {
1132
+ const key = utils$1.findKey(headers, header);
1133
+ if (key) {
1134
+ self[key] = normalizeValue(value);
1135
+ delete self[header];
1136
+ return;
1137
+ }
1138
+ const normalized = format ? formatHeader(header) : String(header).trim();
1139
+ if (normalized !== header) {
1140
+ delete self[header];
1142
1141
  }
1142
+ self[normalized] = normalizeValue(value);
1143
+ headers[normalized] = true;
1143
1144
  });
1144
- stack.pop();
1145
+ return this;
1145
1146
  }
1146
- if (!utils$1.isObject(obj)) {
1147
- throw new TypeError('data must be an object');
1147
+ concat(...targets) {
1148
+ return this.constructor.concat(this, ...targets);
1149
+ }
1150
+ toJSON(asStrings) {
1151
+ const obj = Object.create(null);
1152
+ utils$1.forEach(this, (value, header) => {
1153
+ value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
1154
+ });
1155
+ return obj;
1156
+ }
1157
+ [Symbol.iterator]() {
1158
+ return Object.entries(this.toJSON())[Symbol.iterator]();
1159
+ }
1160
+ toString() {
1161
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
1162
+ }
1163
+ getSetCookie() {
1164
+ return this.get('set-cookie') || [];
1165
+ }
1166
+ get [Symbol.toStringTag]() {
1167
+ return 'AxiosHeaders';
1168
+ }
1169
+ static from(thing) {
1170
+ return thing instanceof this ? thing : new this(thing);
1171
+ }
1172
+ static concat(first, ...targets) {
1173
+ const computed = new this(first);
1174
+ targets.forEach(target => computed.set(target));
1175
+ return computed;
1176
+ }
1177
+ static accessor(header) {
1178
+ const internals = this[$internals] = this[$internals] = {
1179
+ accessors: {}
1180
+ };
1181
+ const accessors = internals.accessors;
1182
+ const prototype = this.prototype;
1183
+ function defineAccessor(_header) {
1184
+ const lHeader = normalizeHeader(_header);
1185
+ if (!accessors[lHeader]) {
1186
+ buildAccessors(prototype, _header);
1187
+ accessors[lHeader] = true;
1188
+ }
1189
+ }
1190
+ utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1191
+ return this;
1148
1192
  }
1149
- build(obj);
1150
- return formData;
1151
1193
  }
1194
+ AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
1152
1195
 
1153
- /**
1154
- * It encodes a string by replacing all characters that are not in the unreserved set with
1155
- * their percent-encoded equivalents
1156
- *
1157
- * @param {string} str - The string to encode.
1158
- *
1159
- * @returns {string} The encoded string.
1160
- */
1161
- function encode$1(str) {
1162
- const charMap = {
1163
- '!': '%21',
1164
- "'": '%27',
1165
- '(': '%28',
1166
- ')': '%29',
1167
- '~': '%7E',
1168
- '%20': '+'
1196
+ // reserved names hotfix
1197
+ utils$1.reduceDescriptors(AxiosHeaders.prototype, ({
1198
+ value
1199
+ }, key) => {
1200
+ let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
1201
+ return {
1202
+ get: () => value,
1203
+ set(headerValue) {
1204
+ this[mapped] = headerValue;
1205
+ }
1169
1206
  };
1170
- return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
1171
- return charMap[match];
1172
- });
1207
+ });
1208
+ utils$1.freezeMethods(AxiosHeaders);
1209
+
1210
+ const REDACTED = '[REDACTED ****]';
1211
+ function hasOwnOrPrototypeToJSON(source) {
1212
+ if (utils$1.hasOwnProp(source, 'toJSON')) {
1213
+ return true;
1214
+ }
1215
+ let prototype = Object.getPrototypeOf(source);
1216
+ while (prototype && prototype !== Object.prototype) {
1217
+ if (utils$1.hasOwnProp(prototype, 'toJSON')) {
1218
+ return true;
1219
+ }
1220
+ prototype = Object.getPrototypeOf(prototype);
1221
+ }
1222
+ return false;
1223
+ }
1224
+
1225
+ // Build a plain-object snapshot of `config` and replace the value of any key
1226
+ // (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays
1227
+ // and AxiosHeaders, and short-circuits on circular references.
1228
+ function redactConfig(config, redactKeys) {
1229
+ const lowerKeys = new Set(redactKeys.map(k => String(k).toLowerCase()));
1230
+ const seen = [];
1231
+ const visit = source => {
1232
+ if (source === null || typeof source !== 'object') return source;
1233
+ if (utils$1.isBuffer(source)) return source;
1234
+ if (seen.indexOf(source) !== -1) return undefined;
1235
+ if (source instanceof AxiosHeaders) {
1236
+ source = source.toJSON();
1237
+ }
1238
+ seen.push(source);
1239
+ let result;
1240
+ if (utils$1.isArray(source)) {
1241
+ result = [];
1242
+ source.forEach((v, i) => {
1243
+ const reducedValue = visit(v);
1244
+ if (!utils$1.isUndefined(reducedValue)) {
1245
+ result[i] = reducedValue;
1246
+ }
1247
+ });
1248
+ } else {
1249
+ if (!utils$1.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
1250
+ seen.pop();
1251
+ return source;
1252
+ }
1253
+ result = Object.create(null);
1254
+ for (const [key, value] of Object.entries(source)) {
1255
+ const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
1256
+ if (!utils$1.isUndefined(reducedValue)) {
1257
+ result[key] = reducedValue;
1258
+ }
1259
+ }
1260
+ }
1261
+ seen.pop();
1262
+ return result;
1263
+ };
1264
+ return visit(config);
1265
+ }
1266
+ class AxiosError extends Error {
1267
+ static from(error, code, config, request, response, customProps) {
1268
+ const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
1269
+ axiosError.cause = error;
1270
+ axiosError.name = error.name;
1271
+
1272
+ // Preserve status from the original error if not already set from response
1273
+ if (error.status != null && axiosError.status == null) {
1274
+ axiosError.status = error.status;
1275
+ }
1276
+ customProps && Object.assign(axiosError, customProps);
1277
+ return axiosError;
1278
+ }
1279
+
1280
+ /**
1281
+ * Create an Error with the specified message, config, error code, request and response.
1282
+ *
1283
+ * @param {string} message The error message.
1284
+ * @param {string} [code] The error code (for example, 'ECONNABORTED').
1285
+ * @param {Object} [config] The config.
1286
+ * @param {Object} [request] The request.
1287
+ * @param {Object} [response] The response.
1288
+ *
1289
+ * @returns {Error} The created error.
1290
+ */
1291
+ constructor(message, code, config, request, response) {
1292
+ super(message);
1293
+
1294
+ // Make message enumerable to maintain backward compatibility
1295
+ // The native Error constructor sets message as non-enumerable,
1296
+ // but axios < v1.13.3 had it as enumerable
1297
+ Object.defineProperty(this, 'message', {
1298
+ // Null-proto descriptor so a polluted Object.prototype.get cannot turn
1299
+ // this data descriptor into an accessor descriptor on the way in.
1300
+ __proto__: null,
1301
+ value: message,
1302
+ enumerable: true,
1303
+ writable: true,
1304
+ configurable: true
1305
+ });
1306
+ this.name = 'AxiosError';
1307
+ this.isAxiosError = true;
1308
+ code && (this.code = code);
1309
+ config && (this.config = config);
1310
+ request && (this.request = request);
1311
+ if (response) {
1312
+ this.response = response;
1313
+ this.status = response.status;
1314
+ }
1315
+ }
1316
+ toJSON() {
1317
+ // Opt-in redaction: when the request config carries a `redact` array, the
1318
+ // value of any matching key (case-insensitive, at any depth) is replaced
1319
+ // with REDACTED in the serialized snapshot. Undefined or empty leaves the
1320
+ // existing serialization behavior unchanged.
1321
+ const config = this.config;
1322
+ const redactKeys = config && utils$1.hasOwnProp(config, 'redact') ? config.redact : undefined;
1323
+ const serializedConfig = utils$1.isArray(redactKeys) && redactKeys.length > 0 ? redactConfig(config, redactKeys) : utils$1.toJSONObject(config);
1324
+ return {
1325
+ // Standard
1326
+ message: this.message,
1327
+ name: this.name,
1328
+ // Microsoft
1329
+ description: this.description,
1330
+ number: this.number,
1331
+ // Mozilla
1332
+ fileName: this.fileName,
1333
+ lineNumber: this.lineNumber,
1334
+ columnNumber: this.columnNumber,
1335
+ stack: this.stack,
1336
+ // Axios
1337
+ config: serializedConfig,
1338
+ code: this.code,
1339
+ status: this.status
1340
+ };
1341
+ }
1173
1342
  }
1174
1343
 
1344
+ // This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
1345
+ AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
1346
+ AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
1347
+ AxiosError.ECONNABORTED = 'ECONNABORTED';
1348
+ AxiosError.ETIMEDOUT = 'ETIMEDOUT';
1349
+ AxiosError.ECONNREFUSED = 'ECONNREFUSED';
1350
+ AxiosError.ERR_NETWORK = 'ERR_NETWORK';
1351
+ AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
1352
+ AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';
1353
+ AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
1354
+ AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
1355
+ AxiosError.ERR_CANCELED = 'ERR_CANCELED';
1356
+ AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
1357
+ AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
1358
+ AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
1359
+
1175
1360
  /**
1176
- * It takes a params object and converts it to a FormData object
1361
+ * Determines if the given thing is a array or js object.
1177
1362
  *
1178
- * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
1179
- * @param {Object<string, any>} options - The options object passed to the Axios constructor.
1363
+ * @param {string} thing - The object or array to be visited.
1180
1364
  *
1181
- * @returns {void}
1365
+ * @returns {boolean}
1182
1366
  */
1183
- function AxiosURLSearchParams(params, options) {
1184
- this._pairs = [];
1185
- params && toFormData(params, this, options);
1367
+ function isVisitable(thing) {
1368
+ return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
1186
1369
  }
1187
- const prototype = AxiosURLSearchParams.prototype;
1188
- prototype.append = function append(name, value) {
1189
- this._pairs.push([name, value]);
1190
- };
1191
- prototype.toString = function toString(encoder) {
1192
- const _encode = encoder ? function (value) {
1193
- return encoder.call(this, value, encode$1);
1194
- } : encode$1;
1195
- return this._pairs.map(function each(pair) {
1196
- return _encode(pair[0]) + '=' + _encode(pair[1]);
1197
- }, '').join('&');
1198
- };
1199
1370
 
1200
1371
  /**
1201
- * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
1202
- * their plain counterparts (`:`, `$`, `,`, `+`).
1372
+ * It removes the brackets from the end of a string
1203
1373
  *
1204
- * @param {string} val The value to be encoded.
1374
+ * @param {string} key - The key of the parameter.
1205
1375
  *
1206
- * @returns {string} The encoded value.
1376
+ * @returns {string} the key without the brackets.
1207
1377
  */
1208
- function encode(val) {
1209
- return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+');
1378
+ function removeBrackets(key) {
1379
+ return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
1210
1380
  }
1211
1381
 
1212
1382
  /**
1213
- * Build a URL by appending params to the end
1383
+ * It takes a path, a key, and a boolean, and returns a string
1214
1384
  *
1215
- * @param {string} url The base of the url (e.g., http://www.google.com)
1216
- * @param {object} [params] The params to be appended
1217
- * @param {?(object|Function)} options
1385
+ * @param {string} path - The path to the current key.
1386
+ * @param {string} key - The key of the current object being iterated over.
1387
+ * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
1218
1388
  *
1219
- * @returns {string} The formatted url
1389
+ * @returns {string} The path to the current key.
1220
1390
  */
1221
- function buildURL(url, params, options) {
1222
- if (!params) {
1223
- return url;
1224
- }
1225
- const _encode = options && options.encode || encode;
1226
- const _options = utils$1.isFunction(options) ? {
1227
- serialize: options
1228
- } : options;
1229
- const serializeFn = _options && _options.serialize;
1230
- let serializedParams;
1231
- if (serializeFn) {
1232
- serializedParams = serializeFn(params, _options);
1233
- } else {
1234
- serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode);
1235
- }
1236
- if (serializedParams) {
1237
- const hashmarkIndex = url.indexOf('#');
1238
- if (hashmarkIndex !== -1) {
1239
- url = url.slice(0, hashmarkIndex);
1240
- }
1241
- url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1242
- }
1243
- return url;
1391
+ function renderKey(path, key, dots) {
1392
+ if (!path) return key;
1393
+ return path.concat(key).map(function each(token, i) {
1394
+ // eslint-disable-next-line no-param-reassign
1395
+ token = removeBrackets(token);
1396
+ return !dots && i ? '[' + token + ']' : token;
1397
+ }).join(dots ? '.' : '');
1244
1398
  }
1245
1399
 
1246
- class InterceptorManager {
1247
- constructor() {
1248
- this.handlers = [];
1249
- }
1400
+ /**
1401
+ * If the array is an array and none of its elements are visitable, then it's a flat array.
1402
+ *
1403
+ * @param {Array<any>} arr - The array to check
1404
+ *
1405
+ * @returns {boolean}
1406
+ */
1407
+ function isFlatArray(arr) {
1408
+ return utils$1.isArray(arr) && !arr.some(isVisitable);
1409
+ }
1410
+ const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
1411
+ return /^is[A-Z]/.test(prop);
1412
+ });
1250
1413
 
1251
- /**
1252
- * Add a new interceptor to the stack
1253
- *
1254
- * @param {Function} fulfilled The function to handle `then` for a `Promise`
1255
- * @param {Function} rejected The function to handle `reject` for a `Promise`
1256
- * @param {Object} options The options for the interceptor, synchronous and runWhen
1257
- *
1258
- * @return {Number} An ID used to remove interceptor later
1259
- */
1260
- use(fulfilled, rejected, options) {
1261
- this.handlers.push({
1262
- fulfilled,
1263
- rejected,
1264
- synchronous: options ? options.synchronous : false,
1265
- runWhen: options ? options.runWhen : null
1266
- });
1267
- return this.handlers.length - 1;
1414
+ /**
1415
+ * Convert a data object to FormData
1416
+ *
1417
+ * @param {Object} obj
1418
+ * @param {?Object} [formData]
1419
+ * @param {?Object} [options]
1420
+ * @param {Function} [options.visitor]
1421
+ * @param {Boolean} [options.metaTokens = true]
1422
+ * @param {Boolean} [options.dots = false]
1423
+ * @param {?Boolean} [options.indexes = false]
1424
+ *
1425
+ * @returns {Object}
1426
+ **/
1427
+
1428
+ /**
1429
+ * It converts an object into a FormData object
1430
+ *
1431
+ * @param {Object<any, any>} obj - The object to convert to form data.
1432
+ * @param {string} formData - The FormData object to append to.
1433
+ * @param {Object<string, any>} options
1434
+ *
1435
+ * @returns
1436
+ */
1437
+ function toFormData(obj, formData, options) {
1438
+ if (!utils$1.isObject(obj)) {
1439
+ throw new TypeError('target must be an object');
1440
+ }
1441
+
1442
+ // eslint-disable-next-line no-param-reassign
1443
+ formData = formData || new (FormData$1 || FormData)();
1444
+
1445
+ // eslint-disable-next-line no-param-reassign
1446
+ options = utils$1.toFlatObject(options, {
1447
+ metaTokens: true,
1448
+ dots: false,
1449
+ indexes: false
1450
+ }, false, function defined(option, source) {
1451
+ // eslint-disable-next-line no-eq-null,eqeqeq
1452
+ return !utils$1.isUndefined(source[option]);
1453
+ });
1454
+ const metaTokens = options.metaTokens;
1455
+ // eslint-disable-next-line no-use-before-define
1456
+ const visitor = options.visitor || defaultVisitor;
1457
+ const dots = options.dots;
1458
+ const indexes = options.indexes;
1459
+ const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
1460
+ const maxDepth = options.maxDepth === undefined ? 100 : options.maxDepth;
1461
+ const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
1462
+ if (!utils$1.isFunction(visitor)) {
1463
+ throw new TypeError('visitor must be a function');
1464
+ }
1465
+ function convertValue(value) {
1466
+ if (value === null) return '';
1467
+ if (utils$1.isDate(value)) {
1468
+ return value.toISOString();
1469
+ }
1470
+ if (utils$1.isBoolean(value)) {
1471
+ return value.toString();
1472
+ }
1473
+ if (!useBlob && utils$1.isBlob(value)) {
1474
+ throw new AxiosError('Blob is not supported. Use a Buffer instead.');
1475
+ }
1476
+ if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
1477
+ return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
1478
+ }
1479
+ return value;
1480
+ }
1481
+
1482
+ /**
1483
+ * Default visitor.
1484
+ *
1485
+ * @param {*} value
1486
+ * @param {String|Number} key
1487
+ * @param {Array<String|Number>} path
1488
+ * @this {FormData}
1489
+ *
1490
+ * @returns {boolean} return true to visit the each prop of the value recursively
1491
+ */
1492
+ function defaultVisitor(value, key, path) {
1493
+ let arr = value;
1494
+ if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
1495
+ formData.append(renderKey(path, key, dots), convertValue(value));
1496
+ return false;
1497
+ }
1498
+ if (value && !path && typeof value === 'object') {
1499
+ if (utils$1.endsWith(key, '{}')) {
1500
+ // eslint-disable-next-line no-param-reassign
1501
+ key = metaTokens ? key : key.slice(0, -2);
1502
+ // eslint-disable-next-line no-param-reassign
1503
+ value = JSON.stringify(value);
1504
+ } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))) {
1505
+ // eslint-disable-next-line no-param-reassign
1506
+ key = removeBrackets(key);
1507
+ arr.forEach(function each(el, index) {
1508
+ !(utils$1.isUndefined(el) || el === null) && formData.append(
1509
+ // eslint-disable-next-line no-nested-ternary
1510
+ indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + '[]', convertValue(el));
1511
+ });
1512
+ return false;
1513
+ }
1514
+ }
1515
+ if (isVisitable(value)) {
1516
+ return true;
1517
+ }
1518
+ formData.append(renderKey(path, key, dots), convertValue(value));
1519
+ return false;
1520
+ }
1521
+ const stack = [];
1522
+ const exposedHelpers = Object.assign(predicates, {
1523
+ defaultVisitor,
1524
+ convertValue,
1525
+ isVisitable
1526
+ });
1527
+ function build(value, path, depth = 0) {
1528
+ if (utils$1.isUndefined(value)) return;
1529
+ if (depth > maxDepth) {
1530
+ throw new AxiosError('Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
1531
+ }
1532
+ if (stack.indexOf(value) !== -1) {
1533
+ throw Error('Circular reference detected in ' + path.join('.'));
1534
+ }
1535
+ stack.push(value);
1536
+ utils$1.forEach(value, function each(el, key) {
1537
+ const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
1538
+ if (result === true) {
1539
+ build(el, path ? path.concat(key) : [key], depth + 1);
1540
+ }
1541
+ });
1542
+ stack.pop();
1543
+ }
1544
+ if (!utils$1.isObject(obj)) {
1545
+ throw new TypeError('data must be an object');
1546
+ }
1547
+ build(obj);
1548
+ return formData;
1549
+ }
1550
+
1551
+ /**
1552
+ * It encodes a string by replacing all characters that are not in the unreserved set with
1553
+ * their percent-encoded equivalents
1554
+ *
1555
+ * @param {string} str - The string to encode.
1556
+ *
1557
+ * @returns {string} The encoded string.
1558
+ */
1559
+ function encode$1(str) {
1560
+ const charMap = {
1561
+ '!': '%21',
1562
+ "'": '%27',
1563
+ '(': '%28',
1564
+ ')': '%29',
1565
+ '~': '%7E',
1566
+ '%20': '+'
1567
+ };
1568
+ return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
1569
+ return charMap[match];
1570
+ });
1571
+ }
1572
+
1573
+ /**
1574
+ * It takes a params object and converts it to a FormData object
1575
+ *
1576
+ * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
1577
+ * @param {Object<string, any>} options - The options object passed to the Axios constructor.
1578
+ *
1579
+ * @returns {void}
1580
+ */
1581
+ function AxiosURLSearchParams(params, options) {
1582
+ this._pairs = [];
1583
+ params && toFormData(params, this, options);
1584
+ }
1585
+ const prototype = AxiosURLSearchParams.prototype;
1586
+ prototype.append = function append(name, value) {
1587
+ this._pairs.push([name, value]);
1588
+ };
1589
+ prototype.toString = function toString(encoder) {
1590
+ const _encode = encoder ? function (value) {
1591
+ return encoder.call(this, value, encode$1);
1592
+ } : encode$1;
1593
+ return this._pairs.map(function each(pair) {
1594
+ return _encode(pair[0]) + '=' + _encode(pair[1]);
1595
+ }, '').join('&');
1596
+ };
1597
+
1598
+ /**
1599
+ * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
1600
+ * their plain counterparts (`:`, `$`, `,`, `+`).
1601
+ *
1602
+ * @param {string} val The value to be encoded.
1603
+ *
1604
+ * @returns {string} The encoded value.
1605
+ */
1606
+ function encode(val) {
1607
+ return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+');
1608
+ }
1609
+
1610
+ /**
1611
+ * Build a URL by appending params to the end
1612
+ *
1613
+ * @param {string} url The base of the url (e.g., http://www.google.com)
1614
+ * @param {object} [params] The params to be appended
1615
+ * @param {?(object|Function)} options
1616
+ *
1617
+ * @returns {string} The formatted url
1618
+ */
1619
+ function buildURL(url, params, options) {
1620
+ if (!params) {
1621
+ return url;
1622
+ }
1623
+ const _encode = options && options.encode || encode;
1624
+ const _options = utils$1.isFunction(options) ? {
1625
+ serialize: options
1626
+ } : options;
1627
+ const serializeFn = _options && _options.serialize;
1628
+ let serializedParams;
1629
+ if (serializeFn) {
1630
+ serializedParams = serializeFn(params, _options);
1631
+ } else {
1632
+ serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode);
1633
+ }
1634
+ if (serializedParams) {
1635
+ const hashmarkIndex = url.indexOf('#');
1636
+ if (hashmarkIndex !== -1) {
1637
+ url = url.slice(0, hashmarkIndex);
1638
+ }
1639
+ url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1640
+ }
1641
+ return url;
1642
+ }
1643
+
1644
+ class InterceptorManager {
1645
+ constructor() {
1646
+ this.handlers = [];
1647
+ }
1648
+
1649
+ /**
1650
+ * Add a new interceptor to the stack
1651
+ *
1652
+ * @param {Function} fulfilled The function to handle `then` for a `Promise`
1653
+ * @param {Function} rejected The function to handle `reject` for a `Promise`
1654
+ * @param {Object} options The options for the interceptor, synchronous and runWhen
1655
+ *
1656
+ * @return {Number} An ID used to remove interceptor later
1657
+ */
1658
+ use(fulfilled, rejected, options) {
1659
+ this.handlers.push({
1660
+ fulfilled,
1661
+ rejected,
1662
+ synchronous: options ? options.synchronous : false,
1663
+ runWhen: options ? options.runWhen : null
1664
+ });
1665
+ return this.handlers.length - 1;
1268
1666
  }
1269
1667
 
1270
1668
  /**
@@ -1474,7 +1872,7 @@ function formDataToJSON(formData) {
1474
1872
  }
1475
1873
  return !isNumericKey;
1476
1874
  }
1477
- if (!target[name] || !utils$1.isObject(target[name])) {
1875
+ if (!utils$1.hasOwnProp(target, name) || !utils$1.isObject(target[name])) {
1478
1876
  target[name] = [];
1479
1877
  }
1480
1878
  const result = buildPath(path, value, target[name], index);
@@ -1485,432 +1883,133 @@ function formDataToJSON(formData) {
1485
1883
  }
1486
1884
  if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1487
1885
  const obj = {};
1488
- utils$1.forEachEntry(formData, (name, value) => {
1489
- buildPath(parsePropPath(name), value, obj, 0);
1490
- });
1491
- return obj;
1492
- }
1493
- return null;
1494
- }
1495
-
1496
- const own = (obj, key) => obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : undefined;
1497
-
1498
- /**
1499
- * It takes a string, tries to parse it, and if it fails, it returns the stringified version
1500
- * of the input
1501
- *
1502
- * @param {any} rawValue - The value to be stringified.
1503
- * @param {Function} parser - A function that parses a string into a JavaScript object.
1504
- * @param {Function} encoder - A function that takes a value and returns a string.
1505
- *
1506
- * @returns {string} A stringified version of the rawValue.
1507
- */
1508
- function stringifySafely(rawValue, parser, encoder) {
1509
- if (utils$1.isString(rawValue)) {
1510
- try {
1511
- (parser || JSON.parse)(rawValue);
1512
- return utils$1.trim(rawValue);
1513
- } catch (e) {
1514
- if (e.name !== 'SyntaxError') {
1515
- throw e;
1516
- }
1517
- }
1518
- }
1519
- return (encoder || JSON.stringify)(rawValue);
1520
- }
1521
- const defaults = {
1522
- transitional: transitionalDefaults,
1523
- adapter: ['xhr', 'http', 'fetch'],
1524
- transformRequest: [function transformRequest(data, headers) {
1525
- const contentType = headers.getContentType() || '';
1526
- const hasJSONContentType = contentType.indexOf('application/json') > -1;
1527
- const isObjectPayload = utils$1.isObject(data);
1528
- if (isObjectPayload && utils$1.isHTMLForm(data)) {
1529
- data = new FormData(data);
1530
- }
1531
- const isFormData = utils$1.isFormData(data);
1532
- if (isFormData) {
1533
- return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1534
- }
1535
- if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
1536
- return data;
1537
- }
1538
- if (utils$1.isArrayBufferView(data)) {
1539
- return data.buffer;
1540
- }
1541
- if (utils$1.isURLSearchParams(data)) {
1542
- headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
1543
- return data.toString();
1544
- }
1545
- let isFileList;
1546
- if (isObjectPayload) {
1547
- const formSerializer = own(this, 'formSerializer');
1548
- if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
1549
- return toURLEncodedForm(data, formSerializer).toString();
1550
- }
1551
- if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
1552
- const env = own(this, 'env');
1553
- const _FormData = env && env.FormData;
1554
- return toFormData(isFileList ? {
1555
- 'files[]': data
1556
- } : data, _FormData && new _FormData(), formSerializer);
1557
- }
1558
- }
1559
- if (isObjectPayload || hasJSONContentType) {
1560
- headers.setContentType('application/json', false);
1561
- return stringifySafely(data);
1562
- }
1563
- return data;
1564
- }],
1565
- transformResponse: [function transformResponse(data) {
1566
- const transitional = own(this, 'transitional') || defaults.transitional;
1567
- const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1568
- const responseType = own(this, 'responseType');
1569
- const JSONRequested = responseType === 'json';
1570
- if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1571
- return data;
1572
- }
1573
- if (data && utils$1.isString(data) && (forcedJSONParsing && !responseType || JSONRequested)) {
1574
- const silentJSONParsing = transitional && transitional.silentJSONParsing;
1575
- const strictJSONParsing = !silentJSONParsing && JSONRequested;
1576
- try {
1577
- return JSON.parse(data, own(this, 'parseReviver'));
1578
- } catch (e) {
1579
- if (strictJSONParsing) {
1580
- if (e.name === 'SyntaxError') {
1581
- throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
1582
- }
1583
- throw e;
1584
- }
1585
- }
1586
- }
1587
- return data;
1588
- }],
1589
- /**
1590
- * A timeout in milliseconds to abort a request. If set to 0 (default) a
1591
- * timeout is not created.
1592
- */
1593
- timeout: 0,
1594
- xsrfCookieName: 'XSRF-TOKEN',
1595
- xsrfHeaderName: 'X-XSRF-TOKEN',
1596
- maxContentLength: -1,
1597
- maxBodyLength: -1,
1598
- env: {
1599
- FormData: platform.classes.FormData,
1600
- Blob: platform.classes.Blob
1601
- },
1602
- validateStatus: function validateStatus(status) {
1603
- return status >= 200 && status < 300;
1604
- },
1605
- headers: {
1606
- common: {
1607
- Accept: 'application/json, text/plain, */*',
1608
- 'Content-Type': undefined
1609
- }
1610
- }
1611
- };
1612
- utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], method => {
1613
- defaults.headers[method] = {};
1614
- });
1615
-
1616
- // RawAxiosHeaders whose duplicates are ignored by node
1617
- // c.f. https://nodejs.org/api/http.html#http_message_headers
1618
- const ignoreDuplicateOf = utils$1.toObjectSet(['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']);
1619
-
1620
- /**
1621
- * Parse headers into an object
1622
- *
1623
- * ```
1624
- * Date: Wed, 27 Aug 2014 08:58:49 GMT
1625
- * Content-Type: application/json
1626
- * Connection: keep-alive
1627
- * Transfer-Encoding: chunked
1628
- * ```
1629
- *
1630
- * @param {String} rawHeaders Headers needing to be parsed
1631
- *
1632
- * @returns {Object} Headers parsed into an object
1633
- */
1634
- var parseHeaders = rawHeaders => {
1635
- const parsed = {};
1636
- let key;
1637
- let val;
1638
- let i;
1639
- rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
1640
- i = line.indexOf(':');
1641
- key = line.substring(0, i).trim().toLowerCase();
1642
- val = line.substring(i + 1).trim();
1643
- if (!key || parsed[key] && ignoreDuplicateOf[key]) {
1644
- return;
1645
- }
1646
- if (key === 'set-cookie') {
1647
- if (parsed[key]) {
1648
- parsed[key].push(val);
1649
- } else {
1650
- parsed[key] = [val];
1651
- }
1652
- } else {
1653
- parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1654
- }
1655
- });
1656
- return parsed;
1657
- };
1658
-
1659
- const $internals = Symbol('internals');
1660
- const INVALID_HEADER_VALUE_CHARS_RE = /[^\x09\x20-\x7E\x80-\xFF]/g;
1661
- function trimSPorHTAB(str) {
1662
- let start = 0;
1663
- let end = str.length;
1664
- while (start < end) {
1665
- const code = str.charCodeAt(start);
1666
- if (code !== 0x09 && code !== 0x20) {
1667
- break;
1668
- }
1669
- start += 1;
1670
- }
1671
- while (end > start) {
1672
- const code = str.charCodeAt(end - 1);
1673
- if (code !== 0x09 && code !== 0x20) {
1674
- break;
1675
- }
1676
- end -= 1;
1677
- }
1678
- return start === 0 && end === str.length ? str : str.slice(start, end);
1679
- }
1680
- function normalizeHeader(header) {
1681
- return header && String(header).trim().toLowerCase();
1682
- }
1683
- function sanitizeHeaderValue(str) {
1684
- return trimSPorHTAB(str.replace(INVALID_HEADER_VALUE_CHARS_RE, ''));
1685
- }
1686
- function normalizeValue(value) {
1687
- if (value === false || value == null) {
1688
- return value;
1689
- }
1690
- return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
1691
- }
1692
- function parseTokens(str) {
1693
- const tokens = Object.create(null);
1694
- const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1695
- let match;
1696
- while (match = tokensRE.exec(str)) {
1697
- tokens[match[1]] = match[2];
1698
- }
1699
- return tokens;
1700
- }
1701
- const isValidHeaderName = str => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1702
- function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
1703
- if (utils$1.isFunction(filter)) {
1704
- return filter.call(this, value, header);
1705
- }
1706
- if (isHeaderNameFilter) {
1707
- value = header;
1708
- }
1709
- if (!utils$1.isString(value)) return;
1710
- if (utils$1.isString(filter)) {
1711
- return value.indexOf(filter) !== -1;
1712
- }
1713
- if (utils$1.isRegExp(filter)) {
1714
- return filter.test(value);
1715
- }
1716
- }
1717
- function formatHeader(header) {
1718
- return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1719
- return char.toUpperCase() + str;
1720
- });
1721
- }
1722
- function buildAccessors(obj, header) {
1723
- const accessorName = utils$1.toCamelCase(' ' + header);
1724
- ['get', 'set', 'has'].forEach(methodName => {
1725
- Object.defineProperty(obj, methodName + accessorName, {
1726
- value: function (arg1, arg2, arg3) {
1727
- return this[methodName].call(this, header, arg1, arg2, arg3);
1728
- },
1729
- configurable: true
1730
- });
1731
- });
1732
- }
1733
- class AxiosHeaders {
1734
- constructor(headers) {
1735
- headers && this.set(headers);
1736
- }
1737
- set(header, valueOrRewrite, rewrite) {
1738
- const self = this;
1739
- function setHeader(_value, _header, _rewrite) {
1740
- const lHeader = normalizeHeader(_header);
1741
- if (!lHeader) {
1742
- throw new Error('header name must be a non-empty string');
1743
- }
1744
- const key = utils$1.findKey(self, lHeader);
1745
- if (!key || self[key] === undefined || _rewrite === true || _rewrite === undefined && self[key] !== false) {
1746
- self[key || _header] = normalizeValue(_value);
1747
- }
1748
- }
1749
- const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1750
- if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1751
- setHeaders(header, valueOrRewrite);
1752
- } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1753
- setHeaders(parseHeaders(header), valueOrRewrite);
1754
- } else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
1755
- let obj = {},
1756
- dest,
1757
- key;
1758
- for (const entry of header) {
1759
- if (!utils$1.isArray(entry)) {
1760
- throw TypeError('Object iterator must return a key-value pair');
1761
- }
1762
- obj[key = entry[0]] = (dest = obj[key]) ? utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
1763
- }
1764
- setHeaders(obj, valueOrRewrite);
1765
- } else {
1766
- header != null && setHeader(valueOrRewrite, header, rewrite);
1767
- }
1768
- return this;
1769
- }
1770
- get(header, parser) {
1771
- header = normalizeHeader(header);
1772
- if (header) {
1773
- const key = utils$1.findKey(this, header);
1774
- if (key) {
1775
- const value = this[key];
1776
- if (!parser) {
1777
- return value;
1778
- }
1779
- if (parser === true) {
1780
- return parseTokens(value);
1781
- }
1782
- if (utils$1.isFunction(parser)) {
1783
- return parser.call(this, value, key);
1784
- }
1785
- if (utils$1.isRegExp(parser)) {
1786
- return parser.exec(value);
1787
- }
1788
- throw new TypeError('parser must be boolean|regexp|function');
1789
- }
1790
- }
1791
- }
1792
- has(header, matcher) {
1793
- header = normalizeHeader(header);
1794
- if (header) {
1795
- const key = utils$1.findKey(this, header);
1796
- return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1797
- }
1798
- return false;
1799
- }
1800
- delete(header, matcher) {
1801
- const self = this;
1802
- let deleted = false;
1803
- function deleteHeader(_header) {
1804
- _header = normalizeHeader(_header);
1805
- if (_header) {
1806
- const key = utils$1.findKey(self, _header);
1807
- if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
1808
- delete self[key];
1809
- deleted = true;
1810
- }
1811
- }
1812
- }
1813
- if (utils$1.isArray(header)) {
1814
- header.forEach(deleteHeader);
1815
- } else {
1816
- deleteHeader(header);
1817
- }
1818
- return deleted;
1819
- }
1820
- clear(matcher) {
1821
- const keys = Object.keys(this);
1822
- let i = keys.length;
1823
- let deleted = false;
1824
- while (i--) {
1825
- const key = keys[i];
1826
- if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1827
- delete this[key];
1828
- deleted = true;
1829
- }
1830
- }
1831
- return deleted;
1832
- }
1833
- normalize(format) {
1834
- const self = this;
1835
- const headers = {};
1836
- utils$1.forEach(this, (value, header) => {
1837
- const key = utils$1.findKey(headers, header);
1838
- if (key) {
1839
- self[key] = normalizeValue(value);
1840
- delete self[header];
1841
- return;
1842
- }
1843
- const normalized = format ? formatHeader(header) : String(header).trim();
1844
- if (normalized !== header) {
1845
- delete self[header];
1846
- }
1847
- self[normalized] = normalizeValue(value);
1848
- headers[normalized] = true;
1849
- });
1850
- return this;
1851
- }
1852
- concat(...targets) {
1853
- return this.constructor.concat(this, ...targets);
1854
- }
1855
- toJSON(asStrings) {
1856
- const obj = Object.create(null);
1857
- utils$1.forEach(this, (value, header) => {
1858
- value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
1859
- });
1860
- return obj;
1861
- }
1862
- [Symbol.iterator]() {
1863
- return Object.entries(this.toJSON())[Symbol.iterator]();
1864
- }
1865
- toString() {
1866
- return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
1867
- }
1868
- getSetCookie() {
1869
- return this.get('set-cookie') || [];
1870
- }
1871
- get [Symbol.toStringTag]() {
1872
- return 'AxiosHeaders';
1873
- }
1874
- static from(thing) {
1875
- return thing instanceof this ? thing : new this(thing);
1876
- }
1877
- static concat(first, ...targets) {
1878
- const computed = new this(first);
1879
- targets.forEach(target => computed.set(target));
1880
- return computed;
1881
- }
1882
- static accessor(header) {
1883
- const internals = this[$internals] = this[$internals] = {
1884
- accessors: {}
1885
- };
1886
- const accessors = internals.accessors;
1887
- const prototype = this.prototype;
1888
- function defineAccessor(_header) {
1889
- const lHeader = normalizeHeader(_header);
1890
- if (!accessors[lHeader]) {
1891
- buildAccessors(prototype, _header);
1892
- accessors[lHeader] = true;
1886
+ utils$1.forEachEntry(formData, (name, value) => {
1887
+ buildPath(parsePropPath(name), value, obj, 0);
1888
+ });
1889
+ return obj;
1890
+ }
1891
+ return null;
1892
+ }
1893
+
1894
+ const own = (obj, key) => obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : undefined;
1895
+
1896
+ /**
1897
+ * It takes a string, tries to parse it, and if it fails, it returns the stringified version
1898
+ * of the input
1899
+ *
1900
+ * @param {any} rawValue - The value to be stringified.
1901
+ * @param {Function} parser - A function that parses a string into a JavaScript object.
1902
+ * @param {Function} encoder - A function that takes a value and returns a string.
1903
+ *
1904
+ * @returns {string} A stringified version of the rawValue.
1905
+ */
1906
+ function stringifySafely(rawValue, parser, encoder) {
1907
+ if (utils$1.isString(rawValue)) {
1908
+ try {
1909
+ (parser || JSON.parse)(rawValue);
1910
+ return utils$1.trim(rawValue);
1911
+ } catch (e) {
1912
+ if (e.name !== 'SyntaxError') {
1913
+ throw e;
1893
1914
  }
1894
1915
  }
1895
- utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1896
- return this;
1897
1916
  }
1917
+ return (encoder || JSON.stringify)(rawValue);
1898
1918
  }
1899
- AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
1900
-
1901
- // reserved names hotfix
1902
- utils$1.reduceDescriptors(AxiosHeaders.prototype, ({
1903
- value
1904
- }, key) => {
1905
- let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
1906
- return {
1907
- get: () => value,
1908
- set(headerValue) {
1909
- this[mapped] = headerValue;
1919
+ const defaults = {
1920
+ transitional: transitionalDefaults,
1921
+ adapter: ['xhr', 'http', 'fetch'],
1922
+ transformRequest: [function transformRequest(data, headers) {
1923
+ const contentType = headers.getContentType() || '';
1924
+ const hasJSONContentType = contentType.indexOf('application/json') > -1;
1925
+ const isObjectPayload = utils$1.isObject(data);
1926
+ if (isObjectPayload && utils$1.isHTMLForm(data)) {
1927
+ data = new FormData(data);
1910
1928
  }
1911
- };
1929
+ const isFormData = utils$1.isFormData(data);
1930
+ if (isFormData) {
1931
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1932
+ }
1933
+ if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
1934
+ return data;
1935
+ }
1936
+ if (utils$1.isArrayBufferView(data)) {
1937
+ return data.buffer;
1938
+ }
1939
+ if (utils$1.isURLSearchParams(data)) {
1940
+ headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
1941
+ return data.toString();
1942
+ }
1943
+ let isFileList;
1944
+ if (isObjectPayload) {
1945
+ const formSerializer = own(this, 'formSerializer');
1946
+ if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
1947
+ return toURLEncodedForm(data, formSerializer).toString();
1948
+ }
1949
+ if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
1950
+ const env = own(this, 'env');
1951
+ const _FormData = env && env.FormData;
1952
+ return toFormData(isFileList ? {
1953
+ 'files[]': data
1954
+ } : data, _FormData && new _FormData(), formSerializer);
1955
+ }
1956
+ }
1957
+ if (isObjectPayload || hasJSONContentType) {
1958
+ headers.setContentType('application/json', false);
1959
+ return stringifySafely(data);
1960
+ }
1961
+ return data;
1962
+ }],
1963
+ transformResponse: [function transformResponse(data) {
1964
+ const transitional = own(this, 'transitional') || defaults.transitional;
1965
+ const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1966
+ const responseType = own(this, 'responseType');
1967
+ const JSONRequested = responseType === 'json';
1968
+ if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1969
+ return data;
1970
+ }
1971
+ if (data && utils$1.isString(data) && (forcedJSONParsing && !responseType || JSONRequested)) {
1972
+ const silentJSONParsing = transitional && transitional.silentJSONParsing;
1973
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
1974
+ try {
1975
+ return JSON.parse(data, own(this, 'parseReviver'));
1976
+ } catch (e) {
1977
+ if (strictJSONParsing) {
1978
+ if (e.name === 'SyntaxError') {
1979
+ throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
1980
+ }
1981
+ throw e;
1982
+ }
1983
+ }
1984
+ }
1985
+ return data;
1986
+ }],
1987
+ /**
1988
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
1989
+ * timeout is not created.
1990
+ */
1991
+ timeout: 0,
1992
+ xsrfCookieName: 'XSRF-TOKEN',
1993
+ xsrfHeaderName: 'X-XSRF-TOKEN',
1994
+ maxContentLength: -1,
1995
+ maxBodyLength: -1,
1996
+ env: {
1997
+ FormData: platform.classes.FormData,
1998
+ Blob: platform.classes.Blob
1999
+ },
2000
+ validateStatus: function validateStatus(status) {
2001
+ return status >= 200 && status < 300;
2002
+ },
2003
+ headers: {
2004
+ common: {
2005
+ Accept: 'application/json, text/plain, */*',
2006
+ 'Content-Type': undefined
2007
+ }
2008
+ }
2009
+ };
2010
+ utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], method => {
2011
+ defaults.headers[method] = {};
1912
2012
  });
1913
- utils$1.freezeMethods(AxiosHeaders);
1914
2013
 
1915
2014
  /**
1916
2015
  * Transform the data for a request or a response
@@ -1967,7 +2066,7 @@ function settle(resolve, reject, response) {
1967
2066
  if (!response.status || !validateStatus || validateStatus(response.status)) {
1968
2067
  resolve(response);
1969
2068
  } else {
1970
- reject(new AxiosError('Request failed with status code ' + response.status, [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response));
2069
+ reject(new AxiosError('Request failed with status code ' + response.status, response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE, response.config, response.request, response));
1971
2070
  }
1972
2071
  }
1973
2072
 
@@ -2114,14 +2213,16 @@ function getEnv(key) {
2114
2213
  return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
2115
2214
  }
2116
2215
 
2117
- const VERSION = "1.15.2";
2216
+ const VERSION = "1.16.1";
2118
2217
 
2119
2218
  function parseProtocol(url) {
2120
- const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2219
+ const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
2121
2220
  return match && match[1] || '';
2122
2221
  }
2123
2222
 
2124
- const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
2223
+ // RFC 2397: data:[<mediatype>][;base64],<data>
2224
+ // mediatype = type/subtype followed by optional ;name=value parameters
2225
+ const DATA_URL_PATTERN = /^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;
2125
2226
 
2126
2227
  /**
2127
2228
  * Parse data uri to a Buffer or Blob
@@ -2145,10 +2246,20 @@ function fromDataURI(uri, asBlob, options) {
2145
2246
  if (!match) {
2146
2247
  throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
2147
2248
  }
2148
- const mime = match[1];
2149
- const isBase64 = match[2];
2150
- const body = match[3];
2151
- const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
2249
+ const type = match[1];
2250
+ const params = match[2];
2251
+ const encoding = match[3] ? 'base64' : 'utf8';
2252
+ const body = match[4];
2253
+
2254
+ // RFC 2397 section 3: default mediatype is text/plain;charset=US-ASCII
2255
+ // Bare `data:,` leaves mime undefined; Blob normalises that to "" per spec.
2256
+ let mime;
2257
+ if (type) {
2258
+ mime = params ? type + params : type;
2259
+ } else if (params) {
2260
+ mime = 'text/plain' + params;
2261
+ }
2262
+ const buffer = Buffer.from(decodeURIComponent(body), encoding);
2152
2263
  if (asBlob) {
2153
2264
  if (!_Blob) {
2154
2265
  throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
@@ -2344,7 +2455,7 @@ const formDataToStream = (form, headersHandler, options) => {
2344
2455
  throw TypeError('FormData instance required');
2345
2456
  }
2346
2457
  if (boundary.length < 1 || boundary.length > 70) {
2347
- throw Error('boundary must be 10-70 characters long');
2458
+ throw Error('boundary must be 1-70 characters long');
2348
2459
  }
2349
2460
  const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);
2350
2461
  const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF);
@@ -2477,6 +2588,27 @@ const parseNoProxyEntry = entry => {
2477
2588
  }
2478
2589
  return [entryHost, entryPort];
2479
2590
  };
2591
+
2592
+ // Convert IPv4-mapped IPv6 (::ffff:0:0/96 prefix) to IPv4 dotted form so both
2593
+ // sides of a NO_PROXY comparison see the same canonical address. Without this,
2594
+ // `NO_PROXY=192.168.1.5` would not match a request to `http://[::ffff:192.168.1.5]/`
2595
+ // (Node's URL parser normalises that to `[::ffff:c0a8:105]`), and vice-versa,
2596
+ // allowing the proxy-bypass policy to be circumvented by using the alternate
2597
+ // representation. Returns the input unchanged when not IPv4-mapped.
2598
+ const IPV4_MAPPED_DOTTED_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i;
2599
+ const IPV4_MAPPED_HEX_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;
2600
+ const unmapIPv4MappedIPv6 = host => {
2601
+ if (typeof host !== 'string' || host.indexOf(':') === -1) return host;
2602
+ const dotted = host.match(IPV4_MAPPED_DOTTED_RE);
2603
+ if (dotted) return dotted[1];
2604
+ const hex = host.match(IPV4_MAPPED_HEX_RE);
2605
+ if (hex) {
2606
+ const high = parseInt(hex[1], 16);
2607
+ const low = parseInt(hex[2], 16);
2608
+ return `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;
2609
+ }
2610
+ return host;
2611
+ };
2480
2612
  const normalizeNoProxyHost = hostname => {
2481
2613
  if (!hostname) {
2482
2614
  return hostname;
@@ -2484,7 +2616,7 @@ const normalizeNoProxyHost = hostname => {
2484
2616
  if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') {
2485
2617
  hostname = hostname.slice(1, -1);
2486
2618
  }
2487
- return hostname.replace(/\.+$/, '');
2619
+ return unmapIPv4MappedIPv6(hostname.replace(/\.+$/, ''));
2488
2620
  };
2489
2621
  function shouldBypassProxy(location) {
2490
2622
  let parsed;
@@ -2607,6 +2739,9 @@ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
2607
2739
  let bytesNotified = 0;
2608
2740
  const _speedometer = speedometer(50, 250);
2609
2741
  return throttle(e => {
2742
+ if (!e || typeof e.loaded !== 'number') {
2743
+ return;
2744
+ }
2610
2745
  const rawLoaded = e.loaded;
2611
2746
  const total = e.lengthComputable ? e.total : undefined;
2612
2747
  const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
@@ -2697,7 +2832,34 @@ function estimateDataURLDecodedBytes(url) {
2697
2832
  const bytes = groups * 3 - (pad || 0);
2698
2833
  return bytes > 0 ? bytes : 0;
2699
2834
  }
2700
- return Buffer.byteLength(body, 'utf8');
2835
+ if (typeof Buffer !== 'undefined' && typeof Buffer.byteLength === 'function') {
2836
+ return Buffer.byteLength(body, 'utf8');
2837
+ }
2838
+
2839
+ // Compute UTF-8 byte length directly from UTF-16 code units without allocating
2840
+ // a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
2841
+ // Using body.length here would undercount non-ASCII (e.g. '€' is 1 code unit
2842
+ // but 3 UTF-8 bytes).
2843
+ let bytes = 0;
2844
+ for (let i = 0, len = body.length; i < len; i++) {
2845
+ const c = body.charCodeAt(i);
2846
+ if (c < 0x80) {
2847
+ bytes += 1;
2848
+ } else if (c < 0x800) {
2849
+ bytes += 2;
2850
+ } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
2851
+ const next = body.charCodeAt(i + 1);
2852
+ if (next >= 0xdc00 && next <= 0xdfff) {
2853
+ bytes += 4;
2854
+ i++;
2855
+ } else {
2856
+ bytes += 3;
2857
+ }
2858
+ } else {
2859
+ bytes += 3;
2860
+ }
2861
+ }
2862
+ return bytes;
2701
2863
  }
2702
2864
 
2703
2865
  const zlibOptions = {
@@ -2714,14 +2876,70 @@ const {
2714
2876
  https: httpsFollow
2715
2877
  } = followRedirects;
2716
2878
  const isHttps = /https:?/;
2879
+ const FORM_DATA_CONTENT_HEADERS$1 = ['content-type', 'content-length'];
2880
+ function setFormDataHeaders$1(headers, formHeaders, policy) {
2881
+ if (policy !== 'content-only') {
2882
+ headers.set(formHeaders);
2883
+ return;
2884
+ }
2885
+ Object.entries(formHeaders).forEach(([key, val]) => {
2886
+ if (FORM_DATA_CONTENT_HEADERS$1.includes(key.toLowerCase())) {
2887
+ headers.set(key, val);
2888
+ }
2889
+ });
2890
+ }
2717
2891
 
2718
2892
  // Symbols used to bind a single 'error' listener to a pooled socket and track
2719
2893
  // the request currently owning that socket across keep-alive reuse (issue #10780).
2720
2894
  const kAxiosSocketListener = Symbol('axios.http.socketListener');
2721
2895
  const kAxiosCurrentReq = Symbol('axios.http.currentReq');
2896
+
2897
+ // Tags HttpsProxyAgent instances installed by setProxy() so the redirect path
2898
+ // can strip them without clobbering a user-supplied agent that happens to be
2899
+ // an HttpsProxyAgent.
2900
+ const kAxiosInstalledTunnel = Symbol('axios.http.installedTunnel');
2901
+
2902
+ // Cache of CONNECT-tunneling agents keyed by proxy config so repeat requests
2903
+ // through the same proxy reuse a single agent (and its socket pool). The
2904
+ // keyspace is bounded by the set of distinct proxy configs the process uses,
2905
+ // so unbounded growth is not a concern in practice.
2906
+ const tunnelingAgentCache = new Map();
2907
+ const tunnelingAgentCacheUser = new WeakMap();
2908
+ function getTunnelingAgent(agentOptions, userHttpsAgent) {
2909
+ const key = agentOptions.protocol + '//' + agentOptions.hostname + ':' + (agentOptions.port || '') + '#' + (agentOptions.auth || '');
2910
+ const cache = userHttpsAgent ? tunnelingAgentCacheUser.get(userHttpsAgent) || tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent) : tunnelingAgentCache;
2911
+ let agent = cache.get(key);
2912
+ if (agent) return agent;
2913
+ // Forward the user's TLS options (custom CA, rejectUnauthorized, client cert,
2914
+ // etc.) into the tunneling agent so they apply to the origin TLS upgrade
2915
+ // performed after CONNECT. Our proxy fields take precedence on conflict.
2916
+ const merged = userHttpsAgent && userHttpsAgent.options ? {
2917
+ ...userHttpsAgent.options,
2918
+ ...agentOptions
2919
+ } : agentOptions;
2920
+ agent = new HttpsProxyAgent(merged);
2921
+ agent[kAxiosInstalledTunnel] = true;
2922
+ cache.set(key, agent);
2923
+ return agent;
2924
+ }
2722
2925
  const supportedProtocols = platform.protocols.map(protocol => {
2723
2926
  return protocol + ':';
2724
2927
  });
2928
+
2929
+ // Node's WHATWG URL parser returns `username` and `password` percent-encoded.
2930
+ // Decode before composing the `auth` option so credentials such as
2931
+ // `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
2932
+ // original value for malformed input so a bad encoding never throws.
2933
+ const decodeURIComponentSafe = value => {
2934
+ if (!utils$1.isString(value)) {
2935
+ return value;
2936
+ }
2937
+ try {
2938
+ return decodeURIComponent(value);
2939
+ } catch (error) {
2940
+ return value;
2941
+ }
2942
+ };
2725
2943
  const flushOnFinish = (stream, [throttled, flush]) => {
2726
2944
  stream.on('end', flush).on('error', flush);
2727
2945
  return throttled;
@@ -2809,12 +3027,12 @@ const http2Sessions = new Http2Sessions();
2809
3027
  *
2810
3028
  * @returns {Object<string, any>}
2811
3029
  */
2812
- function dispatchBeforeRedirect(options, responseDetails) {
3030
+ function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
2813
3031
  if (options.beforeRedirects.proxy) {
2814
3032
  options.beforeRedirects.proxy(options);
2815
3033
  }
2816
3034
  if (options.beforeRedirects.config) {
2817
- options.beforeRedirects.config(options, responseDetails);
3035
+ options.beforeRedirects.config(options, responseDetails, requestDetails);
2818
3036
  }
2819
3037
  }
2820
3038
 
@@ -2827,7 +3045,7 @@ function dispatchBeforeRedirect(options, responseDetails) {
2827
3045
  *
2828
3046
  * @returns {http.ClientRequestArgs}
2829
3047
  */
2830
- function setProxy(options, configProxy, location) {
3048
+ function setProxy(options, configProxy, location, isRedirect, configHttpsAgent) {
2831
3049
  let proxy = configProxy;
2832
3050
  if (!proxy && proxy !== false) {
2833
3051
  const proxyUrl = getProxyForUrl(location);
@@ -2837,39 +3055,134 @@ function setProxy(options, configProxy, location) {
2837
3055
  }
2838
3056
  }
2839
3057
  }
3058
+ // On redirect re-invocation, strip any stale Proxy-Authorization header carried
3059
+ // over from the prior request (e.g. new target no longer uses a proxy, or uses
3060
+ // a different proxy). Skip on the initial request so user-supplied headers are
3061
+ // preserved. Header names are case-insensitive, so remove every case variant.
3062
+ if (isRedirect && options.headers) {
3063
+ for (const name of Object.keys(options.headers)) {
3064
+ if (name.toLowerCase() === 'proxy-authorization') {
3065
+ delete options.headers[name];
3066
+ }
3067
+ }
3068
+ }
3069
+ // Strip any tunneling agent we installed for the previous hop so a redirect
3070
+ // that drops the proxy or crosses an HTTPS↔HTTP boundary doesn't reuse a
3071
+ // stale one. Match on our Symbol marker so a user-supplied HttpsProxyAgent
3072
+ // (which won't carry the marker) is left alone.
3073
+ if (isRedirect && options.agent && options.agent[kAxiosInstalledTunnel]) {
3074
+ options.agent = undefined;
3075
+ }
2840
3076
  if (proxy) {
3077
+ // Read proxy fields without traversing the prototype chain. URL instances expose
3078
+ // username/password/hostname/host/port/protocol via getters on URL.prototype (so
3079
+ // direct reads are shielded), but plain object proxies — and the `auth` field
3080
+ // (which URL does not expose) — must be guarded so a polluted Object.prototype
3081
+ // (e.g. Object.prototype.auth = { username, password }) cannot inject
3082
+ // attacker-controlled credentials into the Proxy-Authorization header or
3083
+ // redirect proxying to an attacker-controlled host.
3084
+ const isProxyURL = proxy instanceof URL;
3085
+ const readProxyField = key => isProxyURL || utils$1.hasOwnProp(proxy, key) ? proxy[key] : undefined;
3086
+ const proxyUsername = readProxyField('username');
3087
+ const proxyPassword = readProxyField('password');
3088
+ let proxyAuth = utils$1.hasOwnProp(proxy, 'auth') ? proxy.auth : undefined;
3089
+
2841
3090
  // Basic proxy authorization
2842
- if (proxy.username) {
2843
- proxy.auth = (proxy.username || '') + ':' + (proxy.password || '');
2844
- }
2845
- if (proxy.auth) {
2846
- // Support proxy auth object form
2847
- const validProxyAuth = Boolean(proxy.auth.username || proxy.auth.password);
3091
+ if (proxyUsername) {
3092
+ proxyAuth = (proxyUsername || '') + ':' + (proxyPassword || '');
3093
+ }
3094
+ if (proxyAuth) {
3095
+ // Support proxy auth object form. Read sub-fields via own-prop checks so a
3096
+ // plain object inheriting from polluted Object.prototype cannot leak creds.
3097
+ const authIsObject = typeof proxyAuth === 'object';
3098
+ const authUsername = authIsObject && utils$1.hasOwnProp(proxyAuth, 'username') ? proxyAuth.username : undefined;
3099
+ const authPassword = authIsObject && utils$1.hasOwnProp(proxyAuth, 'password') ? proxyAuth.password : undefined;
3100
+ const validProxyAuth = Boolean(authUsername || authPassword);
2848
3101
  if (validProxyAuth) {
2849
- proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
2850
- } else if (typeof proxy.auth === 'object') {
3102
+ proxyAuth = (authUsername || '') + ':' + (authPassword || '');
3103
+ } else if (authIsObject) {
2851
3104
  throw new AxiosError('Invalid proxy authorization', AxiosError.ERR_BAD_OPTION, {
2852
3105
  proxy
2853
3106
  });
2854
3107
  }
2855
- const base64 = Buffer.from(proxy.auth, 'utf8').toString('base64');
2856
- options.headers['Proxy-Authorization'] = 'Basic ' + base64;
2857
3108
  }
2858
- options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
2859
- const proxyHost = proxy.hostname || proxy.host;
2860
- options.hostname = proxyHost;
2861
- // Replace 'host' since options is not a URL object
2862
- options.host = proxyHost;
2863
- options.port = proxy.port;
2864
- options.path = location;
2865
- if (proxy.protocol) {
2866
- options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`;
3109
+ const targetIsHttps = isHttps.test(options.protocol);
3110
+ if (targetIsHttps) {
3111
+ // CONNECT-tunneling path for HTTPS targets. Preserves end-to-end TLS to
3112
+ // the origin so the proxy cannot inspect the URL, headers, or body — the
3113
+ // behavior already promised by THREATMODEL.md (T-R9). HttpsProxyAgent
3114
+ // sends Proxy-Authorization on the CONNECT request only, never on the
3115
+ // wrapped TLS request, which is why we don't stamp it onto
3116
+ // options.headers here. If the user already supplied an HttpsProxyAgent,
3117
+ // they own tunneling end-to-end and we leave them alone; otherwise we
3118
+ // install our own tunneling agent and forward their TLS options (if any)
3119
+ // so a custom httpsAgent for cert pinning / rejectUnauthorized still
3120
+ // applies to the origin TLS upgrade.
3121
+ if (!(configHttpsAgent instanceof HttpsProxyAgent)) {
3122
+ const proxyHost = readProxyField('hostname') || readProxyField('host');
3123
+ const proxyPort = readProxyField('port');
3124
+ const rawProxyProtocol = readProxyField('protocol');
3125
+ const normalizedProtocol = rawProxyProtocol ? rawProxyProtocol.includes(':') ? rawProxyProtocol : `${rawProxyProtocol}:` : 'http:';
3126
+ // Bracket IPv6 literals for URL parsing; URL.hostname strips the
3127
+ // brackets again on read so the agent receives the raw form.
3128
+ const proxyHostForURL = proxyHost && proxyHost.includes(':') && !proxyHost.startsWith('[') ? `[${proxyHost}]` : proxyHost;
3129
+ const proxyURL = new URL(`${normalizedProtocol}//${proxyHostForURL}${proxyPort ? ':' + proxyPort : ''}`);
3130
+ const agentOptions = {
3131
+ protocol: proxyURL.protocol,
3132
+ hostname: proxyURL.hostname.replace(/^\[|\]$/g, ''),
3133
+ port: proxyURL.port,
3134
+ auth: proxyAuth && typeof proxyAuth === 'string' ? proxyAuth : undefined
3135
+ };
3136
+ if (proxyURL.protocol === 'https:') {
3137
+ agentOptions.ALPNProtocols = ['http/1.1'];
3138
+ }
3139
+ const tunnelingAgent = getTunnelingAgent(agentOptions, configHttpsAgent);
3140
+ // Set both: `options.agent` is consumed by the native https.request path
3141
+ // (config.maxRedirects === 0); `options.agents.https` is consumed by
3142
+ // follow-redirects, which ignores `options.agent` when `options.agents`
3143
+ // is present.
3144
+ options.agent = tunnelingAgent;
3145
+ if (options.agents) {
3146
+ options.agents.https = tunnelingAgent;
3147
+ }
3148
+ }
3149
+ } else {
3150
+ // Forward-proxy mode for plaintext HTTP targets. The request line carries
3151
+ // the absolute URL and the proxy sees everything — acceptable for plain
3152
+ // HTTP since the wire was already plaintext.
3153
+ if (proxyAuth) {
3154
+ const base64 = Buffer.from(proxyAuth, 'utf8').toString('base64');
3155
+ options.headers['Proxy-Authorization'] = 'Basic ' + base64;
3156
+ }
3157
+
3158
+ // Preserve a user-supplied Host header (case-insensitive) so callers can override
3159
+ // the value forwarded to the proxy; otherwise default to the request URL's host.
3160
+ let hasUserHostHeader = false;
3161
+ for (const name of Object.keys(options.headers)) {
3162
+ if (name.toLowerCase() === 'host') {
3163
+ hasUserHostHeader = true;
3164
+ break;
3165
+ }
3166
+ }
3167
+ if (!hasUserHostHeader) {
3168
+ options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
3169
+ }
3170
+ const proxyHost = readProxyField('hostname') || readProxyField('host');
3171
+ options.hostname = proxyHost;
3172
+ // Replace 'host' since options is not a URL object
3173
+ options.host = proxyHost;
3174
+ options.port = readProxyField('port');
3175
+ options.path = location;
3176
+ const proxyProtocol = readProxyField('protocol');
3177
+ if (proxyProtocol) {
3178
+ options.protocol = proxyProtocol.includes(':') ? proxyProtocol : `${proxyProtocol}:`;
3179
+ }
2867
3180
  }
2868
3181
  }
2869
3182
  options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
2870
3183
  // Configure proxy for redirected request, passing the original config proxy to apply
2871
3184
  // the exact same logic as if the redirected request was performed by axios directly.
2872
- setProxy(redirectOptions, configProxy, redirectOptions.href);
3185
+ setProxy(redirectOptions, configProxy, redirectOptions.href, true, configHttpsAgent);
2873
3186
  };
2874
3187
  }
2875
3188
  const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process';
@@ -2965,6 +3278,7 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2965
3278
  let isDone;
2966
3279
  let rejected = false;
2967
3280
  let req;
3281
+ let connectPhaseTimer;
2968
3282
  httpVersion = +httpVersion;
2969
3283
  if (Number.isNaN(httpVersion)) {
2970
3284
  throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);
@@ -2994,8 +3308,23 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2994
3308
  console.warn('emit error', err);
2995
3309
  }
2996
3310
  }
3311
+ function clearConnectPhaseTimer() {
3312
+ if (connectPhaseTimer) {
3313
+ clearTimeout(connectPhaseTimer);
3314
+ connectPhaseTimer = null;
3315
+ }
3316
+ }
3317
+ function createTimeoutError() {
3318
+ let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
3319
+ const transitional = config.transitional || transitionalDefaults;
3320
+ if (config.timeoutErrorMessage) {
3321
+ timeoutErrorMessage = config.timeoutErrorMessage;
3322
+ }
3323
+ return new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, req);
3324
+ }
2997
3325
  abortEmitter.once('abort', reject);
2998
3326
  const onFinished = () => {
3327
+ clearConnectPhaseTimer();
2999
3328
  if (config.cancelToken) {
3000
3329
  config.cancelToken.unsubscribe(abort);
3001
3330
  }
@@ -3012,6 +3341,7 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3012
3341
  }
3013
3342
  onDone((response, isRejected) => {
3014
3343
  isDone = true;
3344
+ clearConnectPhaseTimer();
3015
3345
  if (isRejected) {
3016
3346
  rejected = true;
3017
3347
  onFinished();
@@ -3105,7 +3435,7 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3105
3435
  });
3106
3436
  // support for https://www.npmjs.com/package/form-data api
3107
3437
  } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders) && data.getHeaders !== Object.prototype.getHeaders) {
3108
- headers.set(data.getHeaders());
3438
+ setFormDataHeaders$1(headers, data.getHeaders(), own('formDataHeaderPolicy'));
3109
3439
  if (!headers.hasContentLength()) {
3110
3440
  try {
3111
3441
  const knownLength = await util.promisify(data.getLength).call(data);
@@ -3160,8 +3490,8 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3160
3490
  auth = username + ':' + password;
3161
3491
  }
3162
3492
  if (!auth && parsed.username) {
3163
- const urlUsername = parsed.username;
3164
- const urlPassword = parsed.password;
3493
+ const urlUsername = decodeURIComponentSafe(parsed.username);
3494
+ const urlPassword = decodeURIComponentSafe(parsed.password);
3165
3495
  auth = urlUsername + ':' + urlPassword;
3166
3496
  }
3167
3497
  auth && headers.delete('authorization');
@@ -3179,11 +3509,10 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3179
3509
 
3180
3510
  // Null-prototype to block prototype pollution gadgets on properties read
3181
3511
  // directly by Node's http.request (e.g. insecureHTTPParser, lookup).
3182
- // See GHSA-q8qp-cvcw-x6jj.
3183
3512
  const options = Object.assign(Object.create(null), {
3184
3513
  path: path$1,
3185
3514
  method: method,
3186
- headers: headers.toJSON(),
3515
+ headers: toByteStringHeaderObject(headers),
3187
3516
  agents: {
3188
3517
  http: config.httpAgent,
3189
3518
  https: config.httpsAgent
@@ -3214,11 +3543,16 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3214
3543
  } else {
3215
3544
  options.hostname = parsed.hostname.startsWith('[') ? parsed.hostname.slice(1, -1) : parsed.hostname;
3216
3545
  options.port = parsed.port;
3217
- setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
3546
+ setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path, false, config.httpsAgent);
3218
3547
  }
3219
3548
  let transport;
3549
+ let isNativeTransport = false;
3220
3550
  const isHttpsRequest = isHttps.test(options.protocol);
3221
- options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
3551
+ // Don't clobber a CONNECT-tunneling agent installed by setProxy() for an
3552
+ // HTTPS target.
3553
+ if (options.agent == null) {
3554
+ options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
3555
+ }
3222
3556
  if (isHttp2) {
3223
3557
  transport = http2Transport;
3224
3558
  } else {
@@ -3227,6 +3561,7 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3227
3561
  transport = configTransport;
3228
3562
  } else if (config.maxRedirects === 0) {
3229
3563
  transport = isHttpsRequest ? https : http;
3564
+ isNativeTransport = true;
3230
3565
  } else {
3231
3566
  if (config.maxRedirects) {
3232
3567
  options.maxRedirects = config.maxRedirects;
@@ -3247,11 +3582,12 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3247
3582
 
3248
3583
  // Always set an explicit own value so a polluted
3249
3584
  // Object.prototype.insecureHTTPParser cannot enable the lenient parser
3250
- // through Node's internal options copy (GHSA-q8qp-cvcw-x6jj).
3585
+ // through Node's internal options copy
3251
3586
  options.insecureHTTPParser = Boolean(own('insecureHTTPParser'));
3252
3587
 
3253
3588
  // Create the request
3254
3589
  req = transport.request(options, function handleResponse(res) {
3590
+ clearConnectPhaseTimer();
3255
3591
  if (req.destroyed) return;
3256
3592
  const streams = [res];
3257
3593
  const responseLength = utils$1.toFiniteNumber(res.headers['content-length']);
@@ -3314,7 +3650,7 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3314
3650
  };
3315
3651
  if (responseType === 'stream') {
3316
3652
  // Enforce maxContentLength on streamed responses; previously this
3317
- // was applied only to buffered responses. See GHSA-vf2m-468p-8v99.
3653
+ // was applied only to buffered responses.
3318
3654
  if (config.maxContentLength > -1) {
3319
3655
  const limit = config.maxContentLength;
3320
3656
  const source = responseStream;
@@ -3353,13 +3689,13 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3353
3689
  if (rejected) {
3354
3690
  return;
3355
3691
  }
3356
- const err = new AxiosError('stream has been aborted', AxiosError.ERR_BAD_RESPONSE, config, lastRequest);
3692
+ const err = new AxiosError('stream has been aborted', AxiosError.ERR_BAD_RESPONSE, config, lastRequest, response);
3357
3693
  responseStream.destroy(err);
3358
3694
  reject(err);
3359
3695
  });
3360
3696
  responseStream.on('error', function handleStreamError(err) {
3361
- if (req.destroyed) return;
3362
- reject(AxiosError.from(err, null, config, lastRequest));
3697
+ if (rejected) return;
3698
+ reject(AxiosError.from(err, null, config, lastRequest, response));
3363
3699
  });
3364
3700
  responseStream.on('end', function handleStreamEnd() {
3365
3701
  try {
@@ -3398,6 +3734,15 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3398
3734
  });
3399
3735
 
3400
3736
  // set tcp keep alive to prevent drop connection by peer
3737
+ // Track every socket bound to this outer RedirectableRequest so a single
3738
+ // 'close' listener can release ownership on all of them. follow-redirects
3739
+ // re-emits the 'socket' event for each hop's native request onto the same
3740
+ // outer request, so attaching per-request listeners inside this handler
3741
+ // would accumulate across hops and trigger MaxListenersExceededWarning at
3742
+ // >= 11 redirects. Clearing only the last-bound socket would leave stale
3743
+ // kAxiosCurrentReq refs on earlier hop sockets returned to the keep-alive
3744
+ // pool, causing an idle-pool 'error' to be attributed to a closed req.
3745
+ const boundSockets = new Set();
3401
3746
  req.on('socket', function handleRequestSocket(socket) {
3402
3747
  // default interval of sending ack packet is 1 minute
3403
3748
  socket.setKeepAlive(true, 1000 * 60);
@@ -3417,11 +3762,16 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3417
3762
  socket[kAxiosSocketListener] = true;
3418
3763
  }
3419
3764
  socket[kAxiosCurrentReq] = req;
3420
- req.once('close', function clearCurrentReq() {
3765
+ boundSockets.add(socket);
3766
+ });
3767
+ req.once('close', function clearCurrentReq() {
3768
+ clearConnectPhaseTimer();
3769
+ for (const socket of boundSockets) {
3421
3770
  if (socket[kAxiosCurrentReq] === req) {
3422
3771
  socket[kAxiosCurrentReq] = null;
3423
3772
  }
3424
- });
3773
+ }
3774
+ boundSockets.clear();
3425
3775
  });
3426
3776
 
3427
3777
  // Handle request timeout
@@ -3432,21 +3782,23 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3432
3782
  abort(new AxiosError('error trying to parse `config.timeout` to int', AxiosError.ERR_BAD_OPTION_VALUE, config, req));
3433
3783
  return;
3434
3784
  }
3785
+ const handleTimeout = function handleTimeout() {
3786
+ if (isDone) return;
3787
+ abort(createTimeoutError());
3788
+ };
3789
+ if (isNativeTransport && timeout > 0) {
3790
+ // Native ClientRequest#setTimeout starts from the socket lifecycle and
3791
+ // may not fire while TCP connect is still pending. Mirror the
3792
+ // follow-redirects wall-clock timer for the maxRedirects === 0 path.
3793
+ connectPhaseTimer = setTimeout(handleTimeout, timeout);
3794
+ }
3435
3795
 
3436
3796
  // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
3437
3797
  // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
3438
3798
  // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
3439
3799
  // And then these socket which be hang up will devouring CPU little by little.
3440
3800
  // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
3441
- req.setTimeout(timeout, function handleRequestTimeout() {
3442
- if (isDone) return;
3443
- let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
3444
- const transitional = config.transitional || transitionalDefaults;
3445
- if (config.timeoutErrorMessage) {
3446
- timeoutErrorMessage = config.timeoutErrorMessage;
3447
- }
3448
- abort(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, req));
3449
- });
3801
+ req.setTimeout(timeout, handleTimeout);
3450
3802
  } else {
3451
3803
  // explicitly reset the socket timeout value for a possible `keep-alive` request
3452
3804
  req.setTimeout(0);
@@ -3471,7 +3823,7 @@ var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3471
3823
 
3472
3824
  // Enforce maxBodyLength for streamed uploads on the native http/https
3473
3825
  // transport (maxRedirects === 0); follow-redirects enforces it on the
3474
- // other path. See GHSA-5c9x-8gcm-mpgx.
3826
+ // other path.
3475
3827
  let uploadStream = data;
3476
3828
  if (config.maxBodyLength > -1 && config.maxRedirects === 0) {
3477
3829
  const limit = config.maxBodyLength;
@@ -3527,8 +3879,20 @@ var cookies = platform.hasStandardBrowserEnv ?
3527
3879
  },
3528
3880
  read(name) {
3529
3881
  if (typeof document === 'undefined') return null;
3530
- const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
3531
- return match ? decodeURIComponent(match[1]) : null;
3882
+ // Match name=value by splitting on the semicolon separator instead of building a
3883
+ // RegExp from `name` interpolating an unescaped string into a RegExp would let
3884
+ // metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
3885
+ // match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
3886
+ // "; ", so ignore optional whitespace before each cookie name.
3887
+ const cookies = document.cookie.split(';');
3888
+ for (let i = 0; i < cookies.length; i++) {
3889
+ const cookie = cookies[i].replace(/^\s+/, '');
3890
+ const eq = cookie.indexOf('=');
3891
+ if (eq !== -1 && cookie.slice(0, eq) === name) {
3892
+ return decodeURIComponent(cookie.slice(eq + 1));
3893
+ }
3894
+ }
3895
+ return null;
3532
3896
  },
3533
3897
  remove(name) {
3534
3898
  this.write(name, '', Date.now() - 86400000, '/');
@@ -3561,11 +3925,14 @@ function mergeConfig(config1, config2) {
3561
3925
  config2 = config2 || {};
3562
3926
 
3563
3927
  // Use a null-prototype object so that downstream reads such as `config.auth`
3564
- // or `config.baseURL` cannot inherit polluted values from Object.prototype
3565
- // (see GHSA-q8qp-cvcw-x6jj). `hasOwnProperty` is restored as a non-enumerable
3566
- // own slot to preserve ergonomics for user code that relies on it.
3928
+ // or `config.baseURL` cannot inherit polluted values from Object.prototype.
3929
+ // `hasOwnProperty` is restored as a non-enumerable own slot to preserve
3930
+ // ergonomics for user code that relies on it.
3567
3931
  const config = Object.create(null);
3568
3932
  Object.defineProperty(config, 'hasOwnProperty', {
3933
+ // Null-proto descriptor so a polluted Object.prototype.get cannot turn
3934
+ // this data descriptor into an accessor descriptor on the way in.
3935
+ __proto__: null,
3569
3936
  value: Object.prototype.hasOwnProperty,
3570
3937
  enumerable: false,
3571
3938
  writable: true,
@@ -3661,11 +4028,33 @@ function mergeConfig(config1, config2) {
3661
4028
  return config;
3662
4029
  }
3663
4030
 
4031
+ const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
4032
+ function setFormDataHeaders(headers, formHeaders, policy) {
4033
+ if (policy !== 'content-only') {
4034
+ headers.set(formHeaders);
4035
+ return;
4036
+ }
4037
+ Object.entries(formHeaders).forEach(([key, val]) => {
4038
+ if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
4039
+ headers.set(key, val);
4040
+ }
4041
+ });
4042
+ }
4043
+
4044
+ /**
4045
+ * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
4046
+ * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
4047
+ *
4048
+ * @param {string} str The string to encode
4049
+ *
4050
+ * @returns {string} UTF-8 bytes as a Latin-1 string
4051
+ */
4052
+ const encodeUTF8 = str => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
3664
4053
  var resolveConfig = config => {
3665
4054
  const newConfig = mergeConfig({}, config);
3666
4055
 
3667
4056
  // Read only own properties to prevent prototype pollution gadgets
3668
- // (e.g. Object.prototype.baseURL = 'https://evil.com'). See GHSA-q8qp-cvcw-x6jj.
4057
+ // (e.g. Object.prototype.baseURL = 'https://evil.com').
3669
4058
  const own = key => utils$1.hasOwnProp(newConfig, key) ? newConfig[key] : undefined;
3670
4059
  const data = own('data');
3671
4060
  let withXSRFToken = own('withXSRFToken');
@@ -3681,21 +4070,14 @@ var resolveConfig = config => {
3681
4070
 
3682
4071
  // HTTP basic authentication
3683
4072
  if (auth) {
3684
- headers.set('Authorization', 'Basic ' + btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')));
4073
+ headers.set('Authorization', 'Basic ' + btoa((auth.username || '') + ':' + (auth.password ? encodeUTF8(auth.password) : '')));
3685
4074
  }
3686
4075
  if (utils$1.isFormData(data)) {
3687
4076
  if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
3688
4077
  headers.setContentType(undefined); // browser handles it
3689
4078
  } else if (utils$1.isFunction(data.getHeaders)) {
3690
4079
  // Node.js FormData (like form-data package)
3691
- const formHeaders = data.getHeaders();
3692
- // Only set safe headers to avoid overwriting security headers
3693
- const allowedHeaders = ['content-type', 'content-length'];
3694
- Object.entries(formHeaders).forEach(([key, val]) => {
3695
- if (allowedHeaders.includes(key.toLowerCase())) {
3696
- headers.set(key, val);
3697
- }
3698
- });
4080
+ setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
3699
4081
  }
3700
4082
  }
3701
4083
 
@@ -3710,7 +4092,7 @@ var resolveConfig = config => {
3710
4092
 
3711
4093
  // Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
3712
4094
  // and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
3713
- // the XSRF token cross-origin. See GHSA-xx6v-rp6x-q39c.
4095
+ // the XSRF token cross-origin.
3714
4096
  const shouldSendXSRF = withXSRFToken === true || withXSRFToken == null && isURLSameOrigin(newConfig.url);
3715
4097
  if (shouldSendXSRF) {
3716
4098
  const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
@@ -3788,7 +4170,7 @@ var xhrAdapter = isXHRAdapterSupported && function (config) {
3788
4170
  // handled by onerror instead
3789
4171
  // With one exception: request that using file: protocol, most browsers
3790
4172
  // will return status as 0 even though it's a successful request
3791
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
4173
+ if (request.status === 0 && !(request.responseURL && request.responseURL.startsWith('file:'))) {
3792
4174
  return;
3793
4175
  }
3794
4176
  // readystate handler is calling before onerror or ontimeout handlers,
@@ -3803,6 +4185,7 @@ var xhrAdapter = isXHRAdapterSupported && function (config) {
3803
4185
  return;
3804
4186
  }
3805
4187
  reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
4188
+ done();
3806
4189
 
3807
4190
  // Clean up request
3808
4191
  request = null;
@@ -3818,6 +4201,7 @@ var xhrAdapter = isXHRAdapterSupported && function (config) {
3818
4201
  // attach the underlying event for consumers who want details
3819
4202
  err.event = event || null;
3820
4203
  reject(err);
4204
+ done();
3821
4205
  request = null;
3822
4206
  };
3823
4207
 
@@ -3829,6 +4213,7 @@ var xhrAdapter = isXHRAdapterSupported && function (config) {
3829
4213
  timeoutErrorMessage = _config.timeoutErrorMessage;
3830
4214
  }
3831
4215
  reject(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request));
4216
+ done();
3832
4217
 
3833
4218
  // Clean up request
3834
4219
  request = null;
@@ -3839,7 +4224,7 @@ var xhrAdapter = isXHRAdapterSupported && function (config) {
3839
4224
 
3840
4225
  // Add headers to the request
3841
4226
  if ('setRequestHeader' in request) {
3842
- utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
4227
+ utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
3843
4228
  request.setRequestHeader(key, val);
3844
4229
  });
3845
4230
  }
@@ -3875,6 +4260,7 @@ var xhrAdapter = isXHRAdapterSupported && function (config) {
3875
4260
  }
3876
4261
  reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
3877
4262
  request.abort();
4263
+ done();
3878
4264
  request = null;
3879
4265
  };
3880
4266
  _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
@@ -3883,7 +4269,7 @@ var xhrAdapter = isXHRAdapterSupported && function (config) {
3883
4269
  }
3884
4270
  }
3885
4271
  const protocol = parseProtocol(_config.url);
3886
- if (protocol && platform.protocols.indexOf(protocol) === -1) {
4272
+ if (protocol && !platform.protocols.includes(protocol)) {
3887
4273
  reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
3888
4274
  return;
3889
4275
  }
@@ -3894,41 +4280,41 @@ var xhrAdapter = isXHRAdapterSupported && function (config) {
3894
4280
  };
3895
4281
 
3896
4282
  const composeSignals = (signals, timeout) => {
3897
- const {
3898
- length
3899
- } = signals = signals ? signals.filter(Boolean) : [];
3900
- if (timeout || length) {
3901
- let controller = new AbortController();
3902
- let aborted;
3903
- const onabort = function (reason) {
3904
- if (!aborted) {
3905
- aborted = true;
3906
- unsubscribe();
3907
- const err = reason instanceof Error ? reason : this.reason;
3908
- controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
3909
- }
3910
- };
3911
- let timer = timeout && setTimeout(() => {
3912
- timer = null;
3913
- onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
3914
- }, timeout);
3915
- const unsubscribe = () => {
3916
- if (signals) {
3917
- timer && clearTimeout(timer);
3918
- timer = null;
3919
- signals.forEach(signal => {
3920
- signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
3921
- });
3922
- signals = null;
3923
- }
3924
- };
3925
- signals.forEach(signal => signal.addEventListener('abort', onabort));
3926
- const {
3927
- signal
3928
- } = controller;
3929
- signal.unsubscribe = () => utils$1.asap(unsubscribe);
3930
- return signal;
4283
+ signals = signals ? signals.filter(Boolean) : [];
4284
+ if (!timeout && !signals.length) {
4285
+ return;
3931
4286
  }
4287
+ const controller = new AbortController();
4288
+ let aborted = false;
4289
+ const onabort = function (reason) {
4290
+ if (!aborted) {
4291
+ aborted = true;
4292
+ unsubscribe();
4293
+ const err = reason instanceof Error ? reason : this.reason;
4294
+ controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
4295
+ }
4296
+ };
4297
+ let timer = timeout && setTimeout(() => {
4298
+ timer = null;
4299
+ onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
4300
+ }, timeout);
4301
+ const unsubscribe = () => {
4302
+ if (!signals) {
4303
+ return;
4304
+ }
4305
+ timer && clearTimeout(timer);
4306
+ timer = null;
4307
+ signals.forEach(signal => {
4308
+ signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
4309
+ });
4310
+ signals = null;
4311
+ };
4312
+ signals.forEach(signal => signal.addEventListener('abort', onabort));
4313
+ const {
4314
+ signal
4315
+ } = controller;
4316
+ signal.unsubscribe = () => utils$1.asap(unsubscribe);
4317
+ return signal;
3932
4318
  };
3933
4319
 
3934
4320
  const streamChunk = function* (chunk, chunkSize) {
@@ -4017,17 +4403,6 @@ const DEFAULT_CHUNK_SIZE = 64 * 1024;
4017
4403
  const {
4018
4404
  isFunction
4019
4405
  } = utils$1;
4020
- const globalFetchAPI = (({
4021
- Request,
4022
- Response
4023
- }) => ({
4024
- Request,
4025
- Response
4026
- }))(utils$1.global);
4027
- const {
4028
- ReadableStream: ReadableStream$1,
4029
- TextEncoder: TextEncoder$1
4030
- } = utils$1.global;
4031
4406
  const test = (fn, ...args) => {
4032
4407
  try {
4033
4408
  return !!fn(...args);
@@ -4036,9 +4411,17 @@ const test = (fn, ...args) => {
4036
4411
  }
4037
4412
  };
4038
4413
  const factory = env => {
4414
+ const globalObject = utils$1.global !== undefined && utils$1.global !== null ? utils$1.global : globalThis;
4415
+ const {
4416
+ ReadableStream,
4417
+ TextEncoder
4418
+ } = globalObject;
4039
4419
  env = utils$1.merge.call({
4040
4420
  skipUndefined: true
4041
- }, globalFetchAPI, env);
4421
+ }, {
4422
+ Request: globalObject.Request,
4423
+ Response: globalObject.Response
4424
+ }, env);
4042
4425
  const {
4043
4426
  fetch: envFetch,
4044
4427
  Request,
@@ -4050,12 +4433,12 @@ const factory = env => {
4050
4433
  if (!isFetchSupported) {
4051
4434
  return false;
4052
4435
  }
4053
- const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
4054
- const encodeText = isFetchSupported && (typeof TextEncoder$1 === 'function' ? (encoder => str => encoder.encode(str))(new TextEncoder$1()) : async str => new Uint8Array(await new Request(str).arrayBuffer()));
4436
+ const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
4437
+ const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? (encoder => str => encoder.encode(str))(new TextEncoder()) : async str => new Uint8Array(await new Request(str).arrayBuffer()));
4055
4438
  const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
4056
4439
  let duplexAccessed = false;
4057
4440
  const request = new Request(platform.origin, {
4058
- body: new ReadableStream$1(),
4441
+ body: new ReadableStream(),
4059
4442
  method: 'POST',
4060
4443
  get duplex() {
4061
4444
  duplexAccessed = true;
@@ -4124,8 +4507,12 @@ const factory = env => {
4124
4507
  responseType,
4125
4508
  headers,
4126
4509
  withCredentials = 'same-origin',
4127
- fetchOptions
4510
+ fetchOptions,
4511
+ maxContentLength,
4512
+ maxBodyLength
4128
4513
  } = resolveConfig(config);
4514
+ const hasMaxContentLength = utils$1.isNumber(maxContentLength) && maxContentLength > -1;
4515
+ const hasMaxBodyLength = utils$1.isNumber(maxBodyLength) && maxBodyLength > -1;
4129
4516
  let _fetch = envFetch || fetch;
4130
4517
  responseType = responseType ? (responseType + '').toLowerCase() : 'text';
4131
4518
  let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
@@ -4135,6 +4522,26 @@ const factory = env => {
4135
4522
  });
4136
4523
  let requestContentLength;
4137
4524
  try {
4525
+ // Enforce maxContentLength for data: URLs up-front so we never materialize
4526
+ // an oversized payload. The HTTP adapter applies the same check (see http.js
4527
+ // "if (protocol === 'data:')" branch).
4528
+ if (hasMaxContentLength && typeof url === 'string' && url.startsWith('data:')) {
4529
+ const estimated = estimateDataURLDecodedBytes(url);
4530
+ if (estimated > maxContentLength) {
4531
+ throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
4532
+ }
4533
+ }
4534
+
4535
+ // Enforce maxBodyLength against the outbound request body before dispatch.
4536
+ // Mirrors http.js behavior (ERR_BAD_REQUEST / 'Request body larger than
4537
+ // maxBodyLength limit'). Skip when the body length cannot be determined
4538
+ // (e.g. a live ReadableStream supplied by the caller).
4539
+ if (hasMaxBodyLength && method !== 'get' && method !== 'head') {
4540
+ const outboundLength = await resolveBodyLength(headers, data);
4541
+ if (typeof outboundLength === 'number' && isFinite(outboundLength) && outboundLength > maxBodyLength) {
4542
+ throw new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config, request);
4543
+ }
4544
+ }
4138
4545
  if (onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
4139
4546
  let _request = new Request(url, {
4140
4547
  method: 'POST',
@@ -4166,32 +4573,73 @@ const factory = env => {
4166
4573
  headers.delete('content-type');
4167
4574
  }
4168
4575
  }
4576
+
4577
+ // Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
4578
+ headers.set('User-Agent', 'axios/' + VERSION, false);
4169
4579
  const resolvedOptions = {
4170
4580
  ...fetchOptions,
4171
4581
  signal: composedSignal,
4172
4582
  method: method.toUpperCase(),
4173
- headers: headers.normalize().toJSON(),
4583
+ headers: toByteStringHeaderObject(headers.normalize()),
4174
4584
  body: data,
4175
4585
  duplex: 'half',
4176
4586
  credentials: isCredentialsSupported ? withCredentials : undefined
4177
4587
  };
4178
4588
  request = isRequestSupported && new Request(url, resolvedOptions);
4179
4589
  let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
4590
+
4591
+ // Cheap pre-check: if the server honestly declares a content-length that
4592
+ // already exceeds the cap, reject before we start streaming.
4593
+ if (hasMaxContentLength) {
4594
+ const declaredLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
4595
+ if (declaredLength != null && declaredLength > maxContentLength) {
4596
+ throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
4597
+ }
4598
+ }
4180
4599
  const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
4181
- if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
4600
+ if (supportsResponseStream && response.body && (onDownloadProgress || hasMaxContentLength || isStreamResponse && unsubscribe)) {
4182
4601
  const options = {};
4183
4602
  ['status', 'statusText', 'headers'].forEach(prop => {
4184
4603
  options[prop] = response[prop];
4185
4604
  });
4186
4605
  const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
4187
4606
  const [onProgress, flush] = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [];
4188
- response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
4607
+ let bytesRead = 0;
4608
+ const onChunkProgress = loadedBytes => {
4609
+ if (hasMaxContentLength) {
4610
+ bytesRead = loadedBytes;
4611
+ if (bytesRead > maxContentLength) {
4612
+ throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
4613
+ }
4614
+ }
4615
+ onProgress && onProgress(loadedBytes);
4616
+ };
4617
+ response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
4189
4618
  flush && flush();
4190
4619
  unsubscribe && unsubscribe();
4191
4620
  }), options);
4192
4621
  }
4193
4622
  responseType = responseType || 'text';
4194
4623
  let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
4624
+
4625
+ // Fallback enforcement for environments without ReadableStream support
4626
+ // (legacy runtimes). Detect materialized size from typed output; skip
4627
+ // streams/Response passthrough since the user will read those themselves.
4628
+ if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
4629
+ let materializedSize;
4630
+ if (responseData != null) {
4631
+ if (typeof responseData.byteLength === 'number') {
4632
+ materializedSize = responseData.byteLength;
4633
+ } else if (typeof responseData.size === 'number') {
4634
+ materializedSize = responseData.size;
4635
+ } else if (typeof responseData === 'string') {
4636
+ materializedSize = typeof TextEncoder === 'function' ? new TextEncoder().encode(responseData).byteLength : responseData.length;
4637
+ }
4638
+ }
4639
+ if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {
4640
+ throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
4641
+ }
4642
+ }
4195
4643
  !isStreamResponse && unsubscribe && unsubscribe();
4196
4644
  return await new Promise((resolve, reject) => {
4197
4645
  settle(resolve, reject, {
@@ -4205,6 +4653,17 @@ const factory = env => {
4205
4653
  });
4206
4654
  } catch (err) {
4207
4655
  unsubscribe && unsubscribe();
4656
+
4657
+ // Safari can surface fetch aborts as a DOMException-like object whose
4658
+ // branded getters throw. Prefer our composed signal reason before reading
4659
+ // the caught error, preserving timeout vs cancellation semantics.
4660
+ if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) {
4661
+ const canceledError = composedSignal.reason;
4662
+ canceledError.config = config;
4663
+ request && (canceledError.request = request);
4664
+ err !== canceledError && (canceledError.cause = err);
4665
+ throw canceledError;
4666
+ }
4208
4667
  if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
4209
4668
  throw Object.assign(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, err && err.response), {
4210
4669
  cause: err.cause || err
@@ -4259,13 +4718,17 @@ const knownAdapters = {
4259
4718
  utils$1.forEach(knownAdapters, (fn, value) => {
4260
4719
  if (fn) {
4261
4720
  try {
4721
+ // Null-proto descriptors so a polluted Object.prototype.get cannot turn
4722
+ // these data descriptors into accessor descriptors on the way in.
4262
4723
  Object.defineProperty(fn, 'name', {
4724
+ __proto__: null,
4263
4725
  value
4264
4726
  });
4265
4727
  } catch (e) {
4266
4728
  // eslint-disable-next-line no-empty
4267
4729
  }
4268
4730
  Object.defineProperty(fn, 'adapterName', {
4731
+ __proto__: null,
4269
4732
  value
4270
4733
  });
4271
4734
  }
@@ -4380,8 +4843,15 @@ function dispatchRequest(config) {
4380
4843
  return adapter(config).then(function onAdapterResolution(response) {
4381
4844
  throwIfCancellationRequested(config);
4382
4845
 
4383
- // Transform response data
4384
- response.data = transformData.call(config, config.transformResponse, response);
4846
+ // Expose the current response on config so that transformResponse can
4847
+ // attach it to any AxiosError it throws (e.g. on JSON parse failure).
4848
+ // We clean it up afterwards to avoid polluting the config object.
4849
+ config.response = response;
4850
+ try {
4851
+ response.data = transformData.call(config, config.transformResponse, response);
4852
+ } finally {
4853
+ delete config.response;
4854
+ }
4385
4855
  response.headers = AxiosHeaders.from(response.headers);
4386
4856
  return response;
4387
4857
  }, function onAdapterRejection(reason) {
@@ -4390,7 +4860,12 @@ function dispatchRequest(config) {
4390
4860
 
4391
4861
  // Transform response data
4392
4862
  if (reason && reason.response) {
4393
- reason.response.data = transformData.call(config, config.transformResponse, reason.response);
4863
+ config.response = reason.response;
4864
+ try {
4865
+ reason.response.data = transformData.call(config, config.transformResponse, reason.response);
4866
+ } finally {
4867
+ delete config.response;
4868
+ }
4394
4869
  reason.response.headers = AxiosHeaders.from(reason.response.headers);
4395
4870
  }
4396
4871
  }
@@ -4462,7 +4937,7 @@ function assertOptions(options, schema, allowUnknown) {
4462
4937
  while (i-- > 0) {
4463
4938
  const opt = keys[i];
4464
4939
  // Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply
4465
- // a non-function validator and cause a TypeError. See GHSA-q8qp-cvcw-x6jj.
4940
+ // a non-function validator and cause a TypeError.
4466
4941
  const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;
4467
4942
  if (validator) {
4468
4943
  const value = options[opt];
@@ -4595,7 +5070,7 @@ class Axios {
4595
5070
 
4596
5071
  // Flatten headers
4597
5072
  let contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]);
4598
- headers && utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], method => {
5073
+ headers && utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], method => {
4599
5074
  delete headers[method];
4600
5075
  });
4601
5076
  config.headers = AxiosHeaders.concat(contextHeaders, headers);
@@ -4676,7 +5151,7 @@ utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoDa
4676
5151
  }));
4677
5152
  };
4678
5153
  });
4679
- utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
5154
+ utils$1.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
4680
5155
  function generateHTTPMethod(isForm) {
4681
5156
  return function httpMethod(url, data, config) {
4682
5157
  return this.request(mergeConfig(config || {}, {
@@ -4690,7 +5165,12 @@ utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method)
4690
5165
  };
4691
5166
  }
4692
5167
  Axios.prototype[method] = generateHTTPMethod();
4693
- Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
5168
+
5169
+ // QUERY is a safe/idempotent read method; multipart form bodies don't fit
5170
+ // its semantics, so no queryForm shorthand is generated.
5171
+ if (method !== 'query') {
5172
+ Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
5173
+ }
4694
5174
  });
4695
5175
 
4696
5176
  /**