utils.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. 'use strict';
  2. import bind from './helpers/bind.js';
  3. // utils is a library of generic helper functions non-specific to axios
  4. const { toString } = Object.prototype;
  5. const { getPrototypeOf } = Object;
  6. const { iterator, toStringTag } = Symbol;
  7. /* Creating a function that will check if an object has a property. */
  8. const hasOwnProperty = (
  9. ({ hasOwnProperty }) =>
  10. (obj, prop) =>
  11. hasOwnProperty.call(obj, prop)
  12. )(Object.prototype);
  13. const isUnsafeObjectKey = (prop) =>
  14. typeof prop === 'string' &&
  15. (prop === '__proto__' || prop === 'constructor' || prop === 'prototype');
  16. /**
  17. * Determine whether an inherited object must be treated as a shared-prototype
  18. * boundary. Cross-realm Object.prototype objects cannot be distinguished
  19. * reliably from application-created null-prototype objects because their
  20. * properties are mutable, so all inherited terminal prototypes are excluded
  21. * as a fail-closed boundary. A null-prototype source still keeps its own
  22. * properties, as produced by mergeConfig and other safe materialization paths.
  23. *
  24. * @param {*} obj The object to inspect
  25. * @param {*} prototype The object's prototype
  26. * @param {boolean} source Whether obj is the original traversal source
  27. *
  28. * @returns {boolean} True when obj is a safe prototype traversal boundary
  29. */
  30. const isPrototypeBoundary = (obj, prototype, source) =>
  31. obj === Object.prototype || (!source && prototype === null);
  32. /**
  33. * Determine whether an object can retain its identity through code paths that
  34. * add, replace, and remove config properties without bypassing unsafe-key
  35. * filtering. Immutable objects, unsafe-key-bearing objects, and objects with
  36. * accessor or restricted data properties must be materialized instead.
  37. *
  38. * @param {*} obj The object to inspect
  39. *
  40. * @returns {boolean} True when every own property is safe and fully mutable
  41. */
  42. const isSafeAndFullyMutable = (obj) => {
  43. if (!Object.isExtensible(obj)) {
  44. return false;
  45. }
  46. const props = Object.getOwnPropertyNames(obj);
  47. if (Object.getOwnPropertySymbols) {
  48. props.push(...Object.getOwnPropertySymbols(obj));
  49. }
  50. return props.every((prop) => {
  51. if (isUnsafeObjectKey(prop)) {
  52. return false;
  53. }
  54. const descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  55. return !!descriptor && descriptor.configurable && descriptor.writable === true;
  56. });
  57. };
  58. /**
  59. * Walk the prototype chain (excluding the source realm's Object.prototype)
  60. * looking for an own `prop`. This distinguishes genuine own/inherited members
  61. * — including class accessors and template prototypes — from members injected
  62. * via Object.prototype pollution (e.g. `Object.prototype.username = '...'`),
  63. * which live on Object.prototype itself and are therefore never matched.
  64. *
  65. * @param {*} thing The value whose chain to inspect
  66. * @param {string|symbol} prop The property key to look for
  67. *
  68. * @returns {boolean} True when `prop` is owned below Object.prototype
  69. */
  70. const hasOwnInPrototypeChain = (thing, prop) => {
  71. let obj = thing;
  72. const seen = [];
  73. while (obj != null) {
  74. if (seen.indexOf(obj) !== -1) {
  75. return false;
  76. }
  77. seen.push(obj);
  78. const prototype = getPrototypeOf(obj);
  79. if (isPrototypeBoundary(obj, prototype, obj === thing)) {
  80. return false;
  81. }
  82. if (hasOwnProperty(obj, prop)) {
  83. return true;
  84. }
  85. obj = prototype;
  86. }
  87. return false;
  88. };
  89. /**
  90. * Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
  91. * properties and members inherited from a non-Object.prototype source (a class
  92. * instance or template object) are honored; a value reachable only through a
  93. * polluted Object.prototype is ignored and `undefined` is returned.
  94. *
  95. * @param {*} obj The source object
  96. * @param {string|symbol} prop The property key to read
  97. *
  98. * @returns {*} The resolved value, or undefined when unsafe/absent
  99. */
  100. const getSafeProp = (obj, prop) =>
  101. obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;
  102. /**
  103. * Flatten an object and its application-defined prototype chain into a
  104. * null-prototype object. Members inherited only from the source realm's
  105. * Object.prototype are deliberately excluded, while class/template members
  106. * below that boundary are preserved.
  107. *
  108. * @param {*} thing The value to flatten
  109. *
  110. * @returns {*} A null-prototype copy, or the original value when it is already
  111. * structurally safe or is not an object
  112. */
  113. const toSafeFlatObject = (thing) => {
  114. if (thing == null || (typeof thing !== 'object' && typeof thing !== 'function')) {
  115. return thing;
  116. }
  117. const sourcePrototype = getPrototypeOf(thing);
  118. if (sourcePrototype === null && isSafeAndFullyMutable(thing)) {
  119. return thing;
  120. }
  121. const result = Object.create(null);
  122. const merged = Object.create(null);
  123. const seen = [];
  124. let current = thing;
  125. while (current != null) {
  126. if (seen.indexOf(current) !== -1) {
  127. break;
  128. }
  129. seen.push(current);
  130. const prototype = current === thing ? sourcePrototype : getPrototypeOf(current);
  131. if (isPrototypeBoundary(current, prototype, current === thing)) {
  132. break;
  133. }
  134. const props = Object.getOwnPropertyNames(current);
  135. if (Object.getOwnPropertySymbols) {
  136. props.push(...Object.getOwnPropertySymbols(current));
  137. }
  138. for (const prop of props) {
  139. if (isUnsafeObjectKey(prop)) {
  140. continue;
  141. }
  142. if (!hasOwnProperty(merged, prop)) {
  143. result[prop] = thing[prop];
  144. merged[prop] = true;
  145. }
  146. }
  147. current = prototype;
  148. }
  149. return result;
  150. };
  151. const kindOf = ((cache) => (thing) => {
  152. const str = toString.call(thing);
  153. return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
  154. })(Object.create(null));
  155. const kindOfTest = (type) => {
  156. type = type.toLowerCase();
  157. return (thing) => kindOf(thing) === type;
  158. };
  159. const typeOfTest = (type) => (thing) => typeof thing === type;
  160. /**
  161. * Determine if a value is a non-null object
  162. *
  163. * @param {Object} val The value to test
  164. *
  165. * @returns {boolean} True if value is an Array, otherwise false
  166. */
  167. const { isArray } = Array;
  168. /**
  169. * Determine if a value is undefined
  170. *
  171. * @param {*} val The value to test
  172. *
  173. * @returns {boolean} True if the value is undefined, otherwise false
  174. */
  175. const isUndefined = typeOfTest('undefined');
  176. /**
  177. * Determine if a value is a Buffer
  178. *
  179. * @param {*} val The value to test
  180. *
  181. * @returns {boolean} True if value is a Buffer, otherwise false
  182. */
  183. function isBuffer(val) {
  184. return (
  185. val !== null &&
  186. !isUndefined(val) &&
  187. val.constructor !== null &&
  188. !isUndefined(val.constructor) &&
  189. isFunction(val.constructor.isBuffer) &&
  190. val.constructor.isBuffer(val)
  191. );
  192. }
  193. /**
  194. * Determine if a value is an ArrayBuffer
  195. *
  196. * @param {*} val The value to test
  197. *
  198. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  199. */
  200. const isArrayBuffer = kindOfTest('ArrayBuffer');
  201. /**
  202. * Determine if a value is a view on an ArrayBuffer
  203. *
  204. * @param {*} val The value to test
  205. *
  206. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  207. */
  208. function isArrayBufferView(val) {
  209. let result;
  210. if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
  211. result = ArrayBuffer.isView(val);
  212. } else {
  213. result = val && val.buffer && isArrayBuffer(val.buffer);
  214. }
  215. return result;
  216. }
  217. /**
  218. * Determine if a value is a String
  219. *
  220. * @param {*} val The value to test
  221. *
  222. * @returns {boolean} True if value is a String, otherwise false
  223. */
  224. const isString = typeOfTest('string');
  225. /**
  226. * Determine if a value is a Function
  227. *
  228. * @param {*} val The value to test
  229. * @returns {boolean} True if value is a Function, otherwise false
  230. */
  231. const isFunction = typeOfTest('function');
  232. /**
  233. * Determine if a value is a Number
  234. *
  235. * @param {*} val The value to test
  236. *
  237. * @returns {boolean} True if value is a Number, otherwise false
  238. */
  239. const isNumber = typeOfTest('number');
  240. /**
  241. * Determine if a value is an Object
  242. *
  243. * @param {*} thing The value to test
  244. *
  245. * @returns {boolean} True if value is an Object, otherwise false
  246. */
  247. const isObject = (thing) => thing !== null && typeof thing === 'object';
  248. /**
  249. * Determine if a value is a Boolean
  250. *
  251. * @param {*} thing The value to test
  252. * @returns {boolean} True if value is a Boolean, otherwise false
  253. */
  254. const isBoolean = (thing) => thing === true || thing === false;
  255. /**
  256. * Determine if a value is a plain Object
  257. *
  258. * @param {*} val The value to test
  259. *
  260. * @returns {boolean} True if value is a plain Object, otherwise false
  261. */
  262. const isPlainObject = (val) => {
  263. if (!isObject(val)) {
  264. return false;
  265. }
  266. const prototype = getPrototypeOf(val);
  267. return (
  268. (prototype === null || prototype === Object.prototype || getPrototypeOf(prototype) === null) &&
  269. // Treat own Symbol.toStringTag or Symbol.iterator members as evidence the
  270. // value is tagged/iterable, ignoring members reachable only through shared
  271. // or terminal prototype boundaries. This is exactly what
  272. // hasOwnInPrototypeChain(val, prop) computes here: every prototype admitted
  273. // above (null, Object.prototype, or a terminal null-prototype template) is
  274. // a boundary, so the walk never inspects anything but `val`'s own members,
  275. // and stops before even those when `val` is itself the boundary
  276. // Object.prototype. Checking that inline avoids allocating the walker's
  277. // `seen` list twice per call on the mergeConfig / merge hot path.
  278. (isPrototypeBoundary(val, prototype, true) ||
  279. (!hasOwnProperty(val, toStringTag) && !hasOwnProperty(val, iterator)))
  280. );
  281. };
  282. /**
  283. * Determine if a value is an empty object (safely handles Buffers)
  284. *
  285. * @param {*} val The value to test
  286. *
  287. * @returns {boolean} True if value is an empty object, otherwise false
  288. */
  289. const isEmptyObject = (val) => {
  290. // Early return for non-objects or Buffers to prevent RangeError
  291. if (!isObject(val) || isBuffer(val)) {
  292. return false;
  293. }
  294. try {
  295. return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
  296. } catch (e) {
  297. // Fallback for any other objects that might cause RangeError with Object.keys()
  298. return false;
  299. }
  300. };
  301. /**
  302. * Determine if a value is a Date
  303. *
  304. * @param {*} val The value to test
  305. *
  306. * @returns {boolean} True if value is a Date, otherwise false
  307. */
  308. const isDate = kindOfTest('Date');
  309. /**
  310. * Determine if a value is a File
  311. *
  312. * @param {*} val The value to test
  313. *
  314. * @returns {boolean} True if value is a File, otherwise false
  315. */
  316. const isFile = kindOfTest('File');
  317. /**
  318. * Determine if a value is a React Native Blob
  319. * React Native "blob": an object with a `uri` attribute. Optionally, it can
  320. * also have a `name` and `type` attribute to specify filename and content type
  321. *
  322. * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
  323. *
  324. * @param {*} value The value to test
  325. *
  326. * @returns {boolean} True if value is a React Native Blob, otherwise false
  327. */
  328. const isReactNativeBlob = (value) => {
  329. return !!(value && typeof value.uri !== 'undefined');
  330. };
  331. /**
  332. * Determine if environment is React Native
  333. * ReactNative `FormData` has a non-standard `getParts()` method
  334. *
  335. * @param {*} formData The formData to test
  336. *
  337. * @returns {boolean} True if environment is React Native, otherwise false
  338. */
  339. const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined';
  340. /**
  341. * Determine if a value is a Blob
  342. *
  343. * @param {*} val The value to test
  344. *
  345. * @returns {boolean} True if value is a Blob, otherwise false
  346. */
  347. const isBlob = kindOfTest('Blob');
  348. /**
  349. * Determine if a value is a FileList
  350. *
  351. * @param {*} val The value to test
  352. *
  353. * @returns {boolean} True if value is a FileList, otherwise false
  354. */
  355. const isFileList = kindOfTest('FileList');
  356. const isSet = kindOfTest('Set');
  357. /**
  358. * Determine if a value is a Stream
  359. *
  360. * @param {*} val The value to test
  361. *
  362. * @returns {boolean} True if value is a Stream, otherwise false
  363. */
  364. const isStream = (val) => isObject(val) && isFunction(val.pipe);
  365. /**
  366. * Determine if a value is a FormData
  367. *
  368. * @param {*} thing The value to test
  369. *
  370. * @returns {boolean} True if value is an FormData, otherwise false
  371. */
  372. function getGlobal() {
  373. if (typeof globalThis !== 'undefined') return globalThis;
  374. if (typeof self !== 'undefined') return self;
  375. if (typeof window !== 'undefined') return window;
  376. if (typeof global !== 'undefined') return global;
  377. return {};
  378. }
  379. const G = getGlobal();
  380. const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
  381. const isFormData = (thing) => {
  382. if (!thing) return false;
  383. if (FormDataCtor && thing instanceof FormDataCtor) return true;
  384. // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
  385. const proto = getPrototypeOf(thing);
  386. if (!proto || proto === Object.prototype) return false;
  387. if (!isFunction(thing.append)) return false;
  388. const kind = kindOf(thing);
  389. return (
  390. kind === 'formdata' ||
  391. // detect form-data instance
  392. (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
  393. );
  394. };
  395. /**
  396. * Determine if a value is a URLSearchParams object
  397. *
  398. * @param {*} val The value to test
  399. *
  400. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  401. */
  402. const isURLSearchParams = kindOfTest('URLSearchParams');
  403. const [isReadableStream, isRequest, isResponse, isHeaders] = [
  404. 'ReadableStream',
  405. 'Request',
  406. 'Response',
  407. 'Headers',
  408. ].map(kindOfTest);
  409. /**
  410. * Trim excess whitespace off the beginning and end of a string
  411. *
  412. * @param {String} str The String to trim
  413. *
  414. * @returns {String} The String freed of excess whitespace
  415. */
  416. const trim = (str) => {
  417. return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  418. };
  419. /**
  420. * Iterate over an Array or an Object invoking a function for each item.
  421. *
  422. * If `obj` is an Array callback will be called passing
  423. * the value, index, and complete array for each item.
  424. *
  425. * If 'obj' is an Object callback will be called passing
  426. * the value, key, and complete object for each property.
  427. *
  428. * @param {Object|Array<unknown>} obj The object to iterate
  429. * @param {Function} fn The callback to invoke for each item
  430. *
  431. * @param {Object} [options]
  432. * @param {Boolean} [options.allOwnKeys = false]
  433. * @returns {any}
  434. */
  435. function forEach(obj, fn, { allOwnKeys = false } = {}) {
  436. // Don't bother if no value provided
  437. if (obj === null || typeof obj === 'undefined') {
  438. return;
  439. }
  440. let i;
  441. let l;
  442. // Force an array if not already something iterable
  443. if (typeof obj !== 'object') {
  444. /*eslint no-param-reassign:0*/
  445. obj = [obj];
  446. }
  447. if (isArray(obj)) {
  448. // Iterate over array values
  449. for (i = 0, l = obj.length; i < l; i++) {
  450. fn.call(null, obj[i], i, obj);
  451. }
  452. } else {
  453. // Buffer check
  454. if (isBuffer(obj)) {
  455. return;
  456. }
  457. // Iterate over object keys
  458. const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
  459. const len = keys.length;
  460. let key;
  461. for (i = 0; i < len; i++) {
  462. key = keys[i];
  463. fn.call(null, obj[key], key, obj);
  464. }
  465. }
  466. }
  467. /**
  468. * Finds a key in an object, case-insensitive, returning the actual key name.
  469. * Returns null if the object is a Buffer or if no match is found.
  470. *
  471. * @param {Object} obj - The object to search.
  472. * @param {string} key - The key to find (case-insensitive).
  473. * @returns {?string} The actual key name if found, otherwise null.
  474. */
  475. function findKey(obj, key) {
  476. if (isBuffer(obj)) {
  477. return null;
  478. }
  479. key = key.toLowerCase();
  480. const keys = Object.keys(obj);
  481. let i = keys.length;
  482. let _key;
  483. while (i-- > 0) {
  484. _key = keys[i];
  485. if (key === _key.toLowerCase()) {
  486. return _key;
  487. }
  488. }
  489. return null;
  490. }
  491. const _global = (() => {
  492. /*eslint no-undef:0*/
  493. if (typeof globalThis !== 'undefined') return globalThis;
  494. return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
  495. })();
  496. const isContextDefined = (context) => !isUndefined(context) && context !== _global;
  497. /**
  498. * Accepts varargs expecting each argument to be an object, then
  499. * immutably merges the properties of each object and returns result.
  500. *
  501. * When multiple objects contain the same key the later object in
  502. * the arguments list will take precedence.
  503. *
  504. * Example:
  505. *
  506. * ```js
  507. * const result = merge({foo: 123}, {foo: 456});
  508. * console.log(result.foo); // outputs 456
  509. * ```
  510. *
  511. * @param {Object} obj1 Object to merge
  512. *
  513. * @returns {Object} Result of all merge properties
  514. */
  515. function merge(...objs) {
  516. const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};
  517. const result = {};
  518. // Caseless lookup only applies to string keys — symbol keys are
  519. // identity-matched. Every string key that reaches `result` passes through
  520. // this index first, so it can never hold two case variants of one key and a
  521. // lowercase -> key map is exactly what findKey(result, key) would rescan
  522. // Object.keys(result) for on each assignment.
  523. const lowerCaseKeys = caseless ? Object.create(null) : null;
  524. const assignValue = (val, key) => {
  525. // Skip dangerous property names to prevent prototype pollution
  526. if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  527. return;
  528. }
  529. let targetKey = key;
  530. if (lowerCaseKeys && typeof key === 'string') {
  531. const lowerKey = key.toLowerCase();
  532. const knownKey = lowerCaseKeys[lowerKey];
  533. // A key recorded but absent from `result` was skipped by skipUndefined;
  534. // the later spelling wins then, as it does for findKey.
  535. if (knownKey !== undefined && hasOwnProperty(result, knownKey)) {
  536. targetKey = knownKey;
  537. } else {
  538. lowerCaseKeys[lowerKey] = key;
  539. }
  540. }
  541. // Read via own-prop only — a bare `result[targetKey]` walks the prototype
  542. // chain, so a polluted Object.prototype value could surface here and get
  543. // copied into the merged result.
  544. const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
  545. if (isPlainObject(existing) && isPlainObject(val)) {
  546. result[targetKey] = merge(existing, val);
  547. } else if (isPlainObject(val)) {
  548. result[targetKey] = merge({}, val);
  549. } else if (isArray(val)) {
  550. result[targetKey] = val.slice();
  551. } else if (!skipUndefined || !isUndefined(val)) {
  552. result[targetKey] = val;
  553. }
  554. };
  555. for (let i = 0, l = objs.length; i < l; i++) {
  556. const source = objs[i];
  557. if (!source || isBuffer(source)) {
  558. continue;
  559. }
  560. forEach(source, assignValue);
  561. if (typeof source !== 'object' || isArray(source) || !Object.getOwnPropertySymbols) {
  562. continue;
  563. }
  564. const symbols = Object.getOwnPropertySymbols(source);
  565. for (let j = 0; j < symbols.length; j++) {
  566. const symbol = symbols[j];
  567. if (propertyIsEnumerable.call(source, symbol)) {
  568. assignValue(source[symbol], symbol);
  569. }
  570. }
  571. }
  572. return result;
  573. }
  574. /**
  575. * Extends object a by mutably adding to it the properties of object b.
  576. *
  577. * @param {Object} a The object to be extended
  578. * @param {Object} b The object to copy properties from
  579. * @param {Object} thisArg The object to bind function to
  580. *
  581. * @param {Object} [options]
  582. * @param {Boolean} [options.allOwnKeys]
  583. * @returns {Object} The resulting value of object a
  584. */
  585. const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
  586. forEach(
  587. b,
  588. (val, key) => {
  589. if (thisArg && isFunction(val)) {
  590. Object.defineProperty(a, key, {
  591. // Null-proto descriptor so a polluted Object.prototype.get cannot
  592. // hijack defineProperty's accessor-vs-data resolution.
  593. __proto__: null,
  594. value: bind(val, thisArg),
  595. writable: true,
  596. enumerable: true,
  597. configurable: true,
  598. });
  599. } else {
  600. Object.defineProperty(a, key, {
  601. __proto__: null,
  602. value: val,
  603. writable: true,
  604. enumerable: true,
  605. configurable: true,
  606. });
  607. }
  608. },
  609. { allOwnKeys }
  610. );
  611. return a;
  612. };
  613. /**
  614. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  615. *
  616. * @param {string} content with BOM
  617. *
  618. * @returns {string} content value without BOM
  619. */
  620. const stripBOM = (content) => {
  621. if (content.charCodeAt(0) === 0xfeff) {
  622. content = content.slice(1);
  623. }
  624. return content;
  625. };
  626. /**
  627. * Inherit the prototype methods from one constructor into another
  628. * @param {function} constructor
  629. * @param {function} superConstructor
  630. * @param {object} [props]
  631. * @param {object} [descriptors]
  632. *
  633. * @returns {void}
  634. */
  635. const inherits = (constructor, superConstructor, props, descriptors) => {
  636. constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  637. Object.defineProperty(constructor.prototype, 'constructor', {
  638. __proto__: null,
  639. value: constructor,
  640. writable: true,
  641. enumerable: false,
  642. configurable: true,
  643. });
  644. Object.defineProperty(constructor, 'super', {
  645. __proto__: null,
  646. value: superConstructor.prototype,
  647. });
  648. props && Object.assign(constructor.prototype, props);
  649. };
  650. /**
  651. * Resolve object with deep prototype chain to a flat object
  652. * @param {Object} sourceObj source object
  653. * @param {Object} [destObj]
  654. * @param {Function|Boolean} [filter]
  655. * @param {Function} [propFilter]
  656. *
  657. * @returns {Object}
  658. */
  659. const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
  660. let props;
  661. let i;
  662. let prop;
  663. const merged = {};
  664. destObj = destObj || {};
  665. // eslint-disable-next-line no-eq-null,eqeqeq
  666. if (sourceObj == null) return destObj;
  667. do {
  668. props = Object.getOwnPropertyNames(sourceObj);
  669. i = props.length;
  670. while (i-- > 0) {
  671. prop = props[i];
  672. if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
  673. destObj[prop] = sourceObj[prop];
  674. merged[prop] = true;
  675. }
  676. }
  677. sourceObj = filter !== false && getPrototypeOf(sourceObj);
  678. } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
  679. return destObj;
  680. };
  681. /**
  682. * Determines whether a string ends with the characters of a specified string
  683. *
  684. * @param {String} str
  685. * @param {String} searchString
  686. * @param {Number} [position= 0]
  687. *
  688. * @returns {boolean}
  689. */
  690. const endsWith = (str, searchString, position) => {
  691. str = String(str);
  692. if (position === undefined || position > str.length) {
  693. position = str.length;
  694. }
  695. position -= searchString.length;
  696. const lastIndex = str.indexOf(searchString, position);
  697. return lastIndex !== -1 && lastIndex === position;
  698. };
  699. /**
  700. * Returns new array from array like object or null if failed
  701. *
  702. * @param {*} [thing]
  703. *
  704. * @returns {?Array}
  705. */
  706. const toArray = (thing) => {
  707. if (!thing) return null;
  708. if (isArray(thing)) return thing;
  709. let i = thing.length;
  710. if (!Number.isSafeInteger(i) || i < 0 || i > 0xffffffff) return null;
  711. // Bound the copy by actual indexed properties, including hidden and inherited
  712. // members of array-like collections, rather than by the declared length alone.
  713. const indexes = new Set();
  714. const seen = new Set();
  715. let source = thing;
  716. while (source != null && indexes.size < i) {
  717. if (seen.has(source)) return null;
  718. seen.add(source);
  719. const prototype = getPrototypeOf(source);
  720. if (isPrototypeBoundary(source, prototype, source === thing)) break;
  721. Object.getOwnPropertyNames(source).forEach((key) => {
  722. const index = +key;
  723. if (
  724. Number.isInteger(index) &&
  725. index >= 0 &&
  726. index < i &&
  727. String(index) === key &&
  728. hasOwnProperty(source, key)
  729. ) {
  730. indexes.add(index);
  731. }
  732. });
  733. source = prototype;
  734. }
  735. if (indexes.size !== i) return null;
  736. const arr = new Array(i);
  737. while (i-- > 0) {
  738. arr[i] = thing[i];
  739. }
  740. return arr;
  741. };
  742. /**
  743. * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
  744. * thing passed in is an instance of Uint8Array
  745. *
  746. * @param {TypedArray}
  747. *
  748. * @returns {Array}
  749. */
  750. // eslint-disable-next-line func-names
  751. const isTypedArray = ((TypedArray) => {
  752. // eslint-disable-next-line func-names
  753. return (thing) => {
  754. return TypedArray && thing instanceof TypedArray;
  755. };
  756. })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
  757. /**
  758. * For each entry in the object, call the function with the key and value.
  759. *
  760. * @param {Object<any, any>} obj - The object to iterate over.
  761. * @param {Function} fn - The function to call for each entry.
  762. *
  763. * @returns {void}
  764. */
  765. const forEachEntry = (obj, fn) => {
  766. const generator = obj && obj[iterator];
  767. const _iterator = generator.call(obj);
  768. let result;
  769. while ((result = _iterator.next()) && !result.done) {
  770. const pair = result.value;
  771. fn.call(obj, pair[0], pair[1]);
  772. }
  773. };
  774. /**
  775. * It takes a regular expression and a string, and returns an array of all the matches
  776. *
  777. * @param {string} regExp - The regular expression to match against.
  778. * @param {string} str - The string to search.
  779. *
  780. * @returns {Array<boolean>}
  781. */
  782. const matchAll = (regExp, str) => {
  783. let matches;
  784. const arr = [];
  785. while ((matches = regExp.exec(str)) !== null) {
  786. arr.push(matches);
  787. }
  788. return arr;
  789. };
  790. /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
  791. const isHTMLForm = kindOfTest('HTMLFormElement');
  792. const toCamelCase = (str) => {
  793. return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
  794. return p1.toUpperCase() + p2;
  795. });
  796. };
  797. const { propertyIsEnumerable } = Object.prototype;
  798. /**
  799. * Determine if a value is a RegExp object
  800. *
  801. * @param {*} val The value to test
  802. *
  803. * @returns {boolean} True if value is a RegExp object, otherwise false
  804. */
  805. const isRegExp = kindOfTest('RegExp');
  806. const reduceDescriptors = (obj, reducer) => {
  807. const descriptors = Object.getOwnPropertyDescriptors(obj);
  808. const reducedDescriptors = {};
  809. forEach(descriptors, (descriptor, name) => {
  810. let ret;
  811. if ((ret = reducer(descriptor, name, obj)) !== false) {
  812. reducedDescriptors[name] = ret || descriptor;
  813. }
  814. });
  815. Object.defineProperties(obj, reducedDescriptors);
  816. };
  817. /**
  818. * Makes all methods read-only
  819. * @param {Object} obj
  820. */
  821. const freezeMethods = (obj) => {
  822. reduceDescriptors(obj, (descriptor, name) => {
  823. // skip restricted props in strict mode
  824. if (isFunction(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
  825. return false;
  826. }
  827. const value = obj[name];
  828. if (!isFunction(value)) return;
  829. descriptor.enumerable = false;
  830. if ('writable' in descriptor) {
  831. descriptor.writable = false;
  832. return;
  833. }
  834. if (!descriptor.set) {
  835. descriptor.set = () => {
  836. throw Error("Can not rewrite read-only method '" + name + "'");
  837. };
  838. }
  839. });
  840. };
  841. /**
  842. * Converts an array or a delimited string into an object set with values as keys and true as values.
  843. * Useful for fast membership checks.
  844. *
  845. * @param {Array|string} arrayOrString - The array or string to convert.
  846. * @param {string} delimiter - The delimiter to use if input is a string.
  847. * @returns {Object} An object with keys from the array or string, values set to true.
  848. */
  849. const toObjectSet = (arrayOrString, delimiter) => {
  850. const obj = {};
  851. const define = (arr) => {
  852. arr.forEach((value) => {
  853. obj[value] = true;
  854. });
  855. };
  856. isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
  857. return obj;
  858. };
  859. const noop = () => {};
  860. const toFiniteNumber = (value, defaultValue) => {
  861. return value != null && Number.isFinite((value = +value)) ? value : defaultValue;
  862. };
  863. /**
  864. * If the thing is a FormData object, return true, otherwise return false.
  865. *
  866. * @param {unknown} thing - The thing to check.
  867. *
  868. * @returns {boolean}
  869. */
  870. function isSpecCompliantForm(thing) {
  871. return !!(
  872. thing &&
  873. isFunction(thing.append) &&
  874. thing[toStringTag] === 'FormData' &&
  875. thing[iterator]
  876. );
  877. }
  878. /**
  879. * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
  880. *
  881. * @param {Object} obj - The object to convert.
  882. * @returns {Object} The JSON-compatible object.
  883. */
  884. const toJSONObject = (obj) => {
  885. const visited = new WeakSet();
  886. const visit = (source) => {
  887. if (isObject(source)) {
  888. if (visited.has(source)) {
  889. return;
  890. }
  891. //Buffer check
  892. if (isBuffer(source)) {
  893. return source;
  894. }
  895. if (!('toJSON' in source)) {
  896. // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
  897. visited.add(source);
  898. let target;
  899. if (isSet(source)) {
  900. target = [];
  901. for (const value of source) {
  902. const reducedValue = visit(value);
  903. !isUndefined(reducedValue) && target.push(reducedValue);
  904. }
  905. } else {
  906. target = isArray(source) ? [] : {};
  907. forEach(source, (value, key) => {
  908. const reducedValue = visit(value);
  909. !isUndefined(reducedValue) && (target[key] = reducedValue);
  910. });
  911. }
  912. visited.delete(source);
  913. return target;
  914. }
  915. }
  916. return source;
  917. };
  918. return visit(obj);
  919. };
  920. /**
  921. * Determines if a value is an async function.
  922. *
  923. * @param {*} thing - The value to test.
  924. * @returns {boolean} True if value is an async function, otherwise false.
  925. */
  926. const isAsyncFn = kindOfTest('AsyncFunction');
  927. /**
  928. * Determines if a value is thenable (has then and catch methods).
  929. *
  930. * @param {*} thing - The value to test.
  931. * @returns {boolean} True if value is thenable, otherwise false.
  932. */
  933. const isThenable = (thing) =>
  934. thing &&
  935. (isObject(thing) || isFunction(thing)) &&
  936. isFunction(thing.then) &&
  937. isFunction(thing.catch);
  938. // original code
  939. // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
  940. /**
  941. * Provides a cross-platform setImmediate implementation.
  942. * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
  943. *
  944. * @param {boolean} setImmediateSupported - Whether setImmediate is supported.
  945. * @param {boolean} postMessageSupported - Whether postMessage is supported.
  946. * @returns {Function} A function to schedule a callback asynchronously.
  947. */
  948. const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
  949. if (setImmediateSupported) {
  950. return setImmediate;
  951. }
  952. return postMessageSupported
  953. ? ((token, callbacks) => {
  954. _global.addEventListener(
  955. 'message',
  956. ({ source, data }) => {
  957. if (source === _global && data === token) {
  958. callbacks.length && callbacks.shift()();
  959. }
  960. },
  961. false
  962. );
  963. return (cb) => {
  964. callbacks.push(cb);
  965. _global.postMessage(token, '*');
  966. };
  967. })(`axios@${Math.random()}`, [])
  968. : (cb) => setTimeout(cb);
  969. })(typeof setImmediate === 'function', isFunction(_global.postMessage));
  970. /**
  971. * Schedules a microtask or asynchronous callback as soon as possible.
  972. * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
  973. *
  974. * @type {Function}
  975. */
  976. const asap =
  977. typeof queueMicrotask !== 'undefined'
  978. ? queueMicrotask.bind(_global)
  979. : (typeof process !== 'undefined' && process.nextTick) || _setImmediate;
  980. // *********************
  981. const isIterable = (thing) => thing != null && isFunction(thing[iterator]);
  982. /**
  983. * Determine if a value is iterable via an iterator that is NOT sourced solely
  984. * from a polluted Object.prototype. Use this instead of `isIterable` whenever
  985. * the iterable comes from untrusted input (e.g. user-supplied header sources),
  986. * so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
  987. * into an attacker-controlled entries iterator.
  988. *
  989. * @param {*} thing The value to test
  990. *
  991. * @returns {boolean} True if value has a non-polluted iterator
  992. */
  993. const isSafeIterable = (thing) =>
  994. thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
  995. export default {
  996. isArray,
  997. isArrayBuffer,
  998. isBuffer,
  999. isFormData,
  1000. isArrayBufferView,
  1001. isString,
  1002. isNumber,
  1003. isBoolean,
  1004. isObject,
  1005. isPlainObject,
  1006. isEmptyObject,
  1007. isReadableStream,
  1008. isRequest,
  1009. isResponse,
  1010. isHeaders,
  1011. isUndefined,
  1012. isDate,
  1013. isFile,
  1014. isReactNativeBlob,
  1015. isReactNative,
  1016. isBlob,
  1017. isRegExp,
  1018. isFunction,
  1019. isStream,
  1020. isURLSearchParams,
  1021. isTypedArray,
  1022. isFileList,
  1023. forEach,
  1024. merge,
  1025. extend,
  1026. trim,
  1027. stripBOM,
  1028. inherits,
  1029. toFlatObject,
  1030. kindOf,
  1031. kindOfTest,
  1032. endsWith,
  1033. toArray,
  1034. forEachEntry,
  1035. matchAll,
  1036. isHTMLForm,
  1037. hasOwnProperty,
  1038. hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
  1039. hasOwnInPrototypeChain,
  1040. getSafeProp,
  1041. toSafeFlatObject,
  1042. reduceDescriptors,
  1043. freezeMethods,
  1044. toObjectSet,
  1045. toCamelCase,
  1046. noop,
  1047. toFiniteNumber,
  1048. findKey,
  1049. global: _global,
  1050. isContextDefined,
  1051. isSpecCompliantForm,
  1052. toJSONObject,
  1053. isAsyncFn,
  1054. isThenable,
  1055. setImmediate: _setImmediate,
  1056. asap,
  1057. isIterable,
  1058. isSafeIterable,
  1059. };