智慧水务管理系统 - 精河县供水工程综合管理平台

utils.js 27KB

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