| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201 |
- 'use strict';
- import bind from './helpers/bind.js';
- // utils is a library of generic helper functions non-specific to axios
- const { toString } = Object.prototype;
- const { getPrototypeOf } = Object;
- const { iterator, toStringTag } = Symbol;
- /* Creating a function that will check if an object has a property. */
- const hasOwnProperty = (
- ({ hasOwnProperty }) =>
- (obj, prop) =>
- hasOwnProperty.call(obj, prop)
- )(Object.prototype);
- const isUnsafeObjectKey = (prop) =>
- typeof prop === 'string' &&
- (prop === '__proto__' || prop === 'constructor' || prop === 'prototype');
- /**
- * Determine whether an inherited object must be treated as a shared-prototype
- * boundary. Cross-realm Object.prototype objects cannot be distinguished
- * reliably from application-created null-prototype objects because their
- * properties are mutable, so all inherited terminal prototypes are excluded
- * as a fail-closed boundary. A null-prototype source still keeps its own
- * properties, as produced by mergeConfig and other safe materialization paths.
- *
- * @param {*} obj The object to inspect
- * @param {*} prototype The object's prototype
- * @param {boolean} source Whether obj is the original traversal source
- *
- * @returns {boolean} True when obj is a safe prototype traversal boundary
- */
- const isPrototypeBoundary = (obj, prototype, source) =>
- obj === Object.prototype || (!source && prototype === null);
- /**
- * Determine whether an object can retain its identity through code paths that
- * add, replace, and remove config properties without bypassing unsafe-key
- * filtering. Immutable objects, unsafe-key-bearing objects, and objects with
- * accessor or restricted data properties must be materialized instead.
- *
- * @param {*} obj The object to inspect
- *
- * @returns {boolean} True when every own property is safe and fully mutable
- */
- const isSafeAndFullyMutable = (obj) => {
- if (!Object.isExtensible(obj)) {
- return false;
- }
- const props = Object.getOwnPropertyNames(obj);
- if (Object.getOwnPropertySymbols) {
- props.push(...Object.getOwnPropertySymbols(obj));
- }
- return props.every((prop) => {
- if (isUnsafeObjectKey(prop)) {
- return false;
- }
- const descriptor = Object.getOwnPropertyDescriptor(obj, prop);
- return !!descriptor && descriptor.configurable && descriptor.writable === true;
- });
- };
- /**
- * Walk the prototype chain (excluding the source realm's Object.prototype)
- * looking for an own `prop`. This distinguishes genuine own/inherited members
- * — including class accessors and template prototypes — from members injected
- * via Object.prototype pollution (e.g. `Object.prototype.username = '...'`),
- * which live on Object.prototype itself and are therefore never matched.
- *
- * @param {*} thing The value whose chain to inspect
- * @param {string|symbol} prop The property key to look for
- *
- * @returns {boolean} True when `prop` is owned below Object.prototype
- */
- const hasOwnInPrototypeChain = (thing, prop) => {
- let obj = thing;
- const seen = [];
- while (obj != null) {
- if (seen.indexOf(obj) !== -1) {
- return false;
- }
- seen.push(obj);
- const prototype = getPrototypeOf(obj);
- if (isPrototypeBoundary(obj, prototype, obj === thing)) {
- return false;
- }
- if (hasOwnProperty(obj, prop)) {
- return true;
- }
- obj = prototype;
- }
- return false;
- };
- /**
- * Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
- * properties and members inherited from a non-Object.prototype source (a class
- * instance or template object) are honored; a value reachable only through a
- * polluted Object.prototype is ignored and `undefined` is returned.
- *
- * @param {*} obj The source object
- * @param {string|symbol} prop The property key to read
- *
- * @returns {*} The resolved value, or undefined when unsafe/absent
- */
- const getSafeProp = (obj, prop) =>
- obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;
- /**
- * Flatten an object and its application-defined prototype chain into a
- * null-prototype object. Members inherited only from the source realm's
- * Object.prototype are deliberately excluded, while class/template members
- * below that boundary are preserved.
- *
- * @param {*} thing The value to flatten
- *
- * @returns {*} A null-prototype copy, or the original value when it is already
- * structurally safe or is not an object
- */
- const toSafeFlatObject = (thing) => {
- if (thing == null || (typeof thing !== 'object' && typeof thing !== 'function')) {
- return thing;
- }
- const sourcePrototype = getPrototypeOf(thing);
- if (sourcePrototype === null && isSafeAndFullyMutable(thing)) {
- return thing;
- }
- const result = Object.create(null);
- const merged = Object.create(null);
- const seen = [];
- let current = thing;
- while (current != null) {
- if (seen.indexOf(current) !== -1) {
- break;
- }
- seen.push(current);
- const prototype = current === thing ? sourcePrototype : getPrototypeOf(current);
- if (isPrototypeBoundary(current, prototype, current === thing)) {
- break;
- }
- const props = Object.getOwnPropertyNames(current);
- if (Object.getOwnPropertySymbols) {
- props.push(...Object.getOwnPropertySymbols(current));
- }
- for (const prop of props) {
- if (isUnsafeObjectKey(prop)) {
- continue;
- }
- if (!hasOwnProperty(merged, prop)) {
- result[prop] = thing[prop];
- merged[prop] = true;
- }
- }
- current = prototype;
- }
- return result;
- };
- const kindOf = ((cache) => (thing) => {
- const str = toString.call(thing);
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
- })(Object.create(null));
- const kindOfTest = (type) => {
- type = type.toLowerCase();
- return (thing) => kindOf(thing) === type;
- };
- const typeOfTest = (type) => (thing) => typeof thing === type;
- /**
- * Determine if a value is a non-null object
- *
- * @param {Object} val The value to test
- *
- * @returns {boolean} True if value is an Array, otherwise false
- */
- const { isArray } = Array;
- /**
- * Determine if a value is undefined
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if the value is undefined, otherwise false
- */
- const isUndefined = typeOfTest('undefined');
- /**
- * Determine if a value is a Buffer
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a Buffer, otherwise false
- */
- function isBuffer(val) {
- return (
- val !== null &&
- !isUndefined(val) &&
- val.constructor !== null &&
- !isUndefined(val.constructor) &&
- isFunction(val.constructor.isBuffer) &&
- val.constructor.isBuffer(val)
- );
- }
- /**
- * Determine if a value is an ArrayBuffer
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
- */
- const isArrayBuffer = kindOfTest('ArrayBuffer');
- /**
- * Determine if a value is a view on an ArrayBuffer
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
- */
- function isArrayBufferView(val) {
- let result;
- if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
- result = ArrayBuffer.isView(val);
- } else {
- result = val && val.buffer && isArrayBuffer(val.buffer);
- }
- return result;
- }
- /**
- * Determine if a value is a String
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a String, otherwise false
- */
- const isString = typeOfTest('string');
- /**
- * Determine if a value is a Function
- *
- * @param {*} val The value to test
- * @returns {boolean} True if value is a Function, otherwise false
- */
- const isFunction = typeOfTest('function');
- /**
- * Determine if a value is a Number
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a Number, otherwise false
- */
- const isNumber = typeOfTest('number');
- /**
- * Determine if a value is an Object
- *
- * @param {*} thing The value to test
- *
- * @returns {boolean} True if value is an Object, otherwise false
- */
- const isObject = (thing) => thing !== null && typeof thing === 'object';
- /**
- * Determine if a value is a Boolean
- *
- * @param {*} thing The value to test
- * @returns {boolean} True if value is a Boolean, otherwise false
- */
- const isBoolean = (thing) => thing === true || thing === false;
- /**
- * Determine if a value is a plain Object
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a plain Object, otherwise false
- */
- const isPlainObject = (val) => {
- if (!isObject(val)) {
- return false;
- }
- const prototype = getPrototypeOf(val);
- return (
- (prototype === null || prototype === Object.prototype || getPrototypeOf(prototype) === null) &&
- // Treat own Symbol.toStringTag or Symbol.iterator members as evidence the
- // value is tagged/iterable, ignoring members reachable only through shared
- // or terminal prototype boundaries. This is exactly what
- // hasOwnInPrototypeChain(val, prop) computes here: every prototype admitted
- // above (null, Object.prototype, or a terminal null-prototype template) is
- // a boundary, so the walk never inspects anything but `val`'s own members,
- // and stops before even those when `val` is itself the boundary
- // Object.prototype. Checking that inline avoids allocating the walker's
- // `seen` list twice per call on the mergeConfig / merge hot path.
- (isPrototypeBoundary(val, prototype, true) ||
- (!hasOwnProperty(val, toStringTag) && !hasOwnProperty(val, iterator)))
- );
- };
- /**
- * Determine if a value is an empty object (safely handles Buffers)
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is an empty object, otherwise false
- */
- const isEmptyObject = (val) => {
- // Early return for non-objects or Buffers to prevent RangeError
- if (!isObject(val) || isBuffer(val)) {
- return false;
- }
- try {
- return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
- } catch (e) {
- // Fallback for any other objects that might cause RangeError with Object.keys()
- return false;
- }
- };
- /**
- * Determine if a value is a Date
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a Date, otherwise false
- */
- const isDate = kindOfTest('Date');
- /**
- * Determine if a value is a File
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a File, otherwise false
- */
- const isFile = kindOfTest('File');
- /**
- * Determine if a value is a React Native Blob
- * React Native "blob": an object with a `uri` attribute. Optionally, it can
- * also have a `name` and `type` attribute to specify filename and content type
- *
- * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
- *
- * @param {*} value The value to test
- *
- * @returns {boolean} True if value is a React Native Blob, otherwise false
- */
- const isReactNativeBlob = (value) => {
- return !!(value && typeof value.uri !== 'undefined');
- };
- /**
- * Determine if environment is React Native
- * ReactNative `FormData` has a non-standard `getParts()` method
- *
- * @param {*} formData The formData to test
- *
- * @returns {boolean} True if environment is React Native, otherwise false
- */
- const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined';
- /**
- * Determine if a value is a Blob
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a Blob, otherwise false
- */
- const isBlob = kindOfTest('Blob');
- /**
- * Determine if a value is a FileList
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a FileList, otherwise false
- */
- const isFileList = kindOfTest('FileList');
- const isSet = kindOfTest('Set');
- /**
- * Determine if a value is a Stream
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a Stream, otherwise false
- */
- const isStream = (val) => isObject(val) && isFunction(val.pipe);
- /**
- * Determine if a value is a FormData
- *
- * @param {*} thing The value to test
- *
- * @returns {boolean} True if value is an FormData, otherwise false
- */
- function getGlobal() {
- if (typeof globalThis !== 'undefined') return globalThis;
- if (typeof self !== 'undefined') return self;
- if (typeof window !== 'undefined') return window;
- if (typeof global !== 'undefined') return global;
- return {};
- }
- const G = getGlobal();
- const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
- const isFormData = (thing) => {
- if (!thing) return false;
- if (FormDataCtor && thing instanceof FormDataCtor) return true;
- // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
- const proto = getPrototypeOf(thing);
- if (!proto || proto === Object.prototype) return false;
- if (!isFunction(thing.append)) return false;
- const kind = kindOf(thing);
- return (
- kind === 'formdata' ||
- // detect form-data instance
- (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
- );
- };
- /**
- * Determine if a value is a URLSearchParams object
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
- */
- const isURLSearchParams = kindOfTest('URLSearchParams');
- const [isReadableStream, isRequest, isResponse, isHeaders] = [
- 'ReadableStream',
- 'Request',
- 'Response',
- 'Headers',
- ].map(kindOfTest);
- /**
- * Trim excess whitespace off the beginning and end of a string
- *
- * @param {String} str The String to trim
- *
- * @returns {String} The String freed of excess whitespace
- */
- const trim = (str) => {
- return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
- };
- /**
- * Iterate over an Array or an Object invoking a function for each item.
- *
- * If `obj` is an Array callback will be called passing
- * the value, index, and complete array for each item.
- *
- * If 'obj' is an Object callback will be called passing
- * the value, key, and complete object for each property.
- *
- * @param {Object|Array<unknown>} obj The object to iterate
- * @param {Function} fn The callback to invoke for each item
- *
- * @param {Object} [options]
- * @param {Boolean} [options.allOwnKeys = false]
- * @returns {any}
- */
- function forEach(obj, fn, { allOwnKeys = false } = {}) {
- // Don't bother if no value provided
- if (obj === null || typeof obj === 'undefined') {
- return;
- }
- let i;
- let l;
- // Force an array if not already something iterable
- if (typeof obj !== 'object') {
- /*eslint no-param-reassign:0*/
- obj = [obj];
- }
- if (isArray(obj)) {
- // Iterate over array values
- for (i = 0, l = obj.length; i < l; i++) {
- fn.call(null, obj[i], i, obj);
- }
- } else {
- // Buffer check
- if (isBuffer(obj)) {
- return;
- }
- // Iterate over object keys
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
- const len = keys.length;
- let key;
- for (i = 0; i < len; i++) {
- key = keys[i];
- fn.call(null, obj[key], key, obj);
- }
- }
- }
- /**
- * Finds a key in an object, case-insensitive, returning the actual key name.
- * Returns null if the object is a Buffer or if no match is found.
- *
- * @param {Object} obj - The object to search.
- * @param {string} key - The key to find (case-insensitive).
- * @returns {?string} The actual key name if found, otherwise null.
- */
- function findKey(obj, key) {
- if (isBuffer(obj)) {
- return null;
- }
- key = key.toLowerCase();
- const keys = Object.keys(obj);
- let i = keys.length;
- let _key;
- while (i-- > 0) {
- _key = keys[i];
- if (key === _key.toLowerCase()) {
- return _key;
- }
- }
- return null;
- }
- const _global = (() => {
- /*eslint no-undef:0*/
- if (typeof globalThis !== 'undefined') return globalThis;
- return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
- })();
- const isContextDefined = (context) => !isUndefined(context) && context !== _global;
- /**
- * Accepts varargs expecting each argument to be an object, then
- * immutably merges the properties of each object and returns result.
- *
- * When multiple objects contain the same key the later object in
- * the arguments list will take precedence.
- *
- * Example:
- *
- * ```js
- * const result = merge({foo: 123}, {foo: 456});
- * console.log(result.foo); // outputs 456
- * ```
- *
- * @param {Object} obj1 Object to merge
- *
- * @returns {Object} Result of all merge properties
- */
- function merge(...objs) {
- const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};
- const result = {};
- // Caseless lookup only applies to string keys — symbol keys are
- // identity-matched. Every string key that reaches `result` passes through
- // this index first, so it can never hold two case variants of one key and a
- // lowercase -> key map is exactly what findKey(result, key) would rescan
- // Object.keys(result) for on each assignment.
- const lowerCaseKeys = caseless ? Object.create(null) : null;
- const assignValue = (val, key) => {
- // Skip dangerous property names to prevent prototype pollution
- if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
- return;
- }
- let targetKey = key;
- if (lowerCaseKeys && typeof key === 'string') {
- const lowerKey = key.toLowerCase();
- const knownKey = lowerCaseKeys[lowerKey];
- // A key recorded but absent from `result` was skipped by skipUndefined;
- // the later spelling wins then, as it does for findKey.
- if (knownKey !== undefined && hasOwnProperty(result, knownKey)) {
- targetKey = knownKey;
- } else {
- lowerCaseKeys[lowerKey] = key;
- }
- }
- // Read via own-prop only — a bare `result[targetKey]` walks the prototype
- // chain, so a polluted Object.prototype value could surface here and get
- // copied into the merged result.
- const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
- if (isPlainObject(existing) && isPlainObject(val)) {
- result[targetKey] = merge(existing, val);
- } else if (isPlainObject(val)) {
- result[targetKey] = merge({}, val);
- } else if (isArray(val)) {
- result[targetKey] = val.slice();
- } else if (!skipUndefined || !isUndefined(val)) {
- result[targetKey] = val;
- }
- };
- for (let i = 0, l = objs.length; i < l; i++) {
- const source = objs[i];
- if (!source || isBuffer(source)) {
- continue;
- }
- forEach(source, assignValue);
- if (typeof source !== 'object' || isArray(source) || !Object.getOwnPropertySymbols) {
- continue;
- }
- const symbols = Object.getOwnPropertySymbols(source);
- for (let j = 0; j < symbols.length; j++) {
- const symbol = symbols[j];
- if (propertyIsEnumerable.call(source, symbol)) {
- assignValue(source[symbol], symbol);
- }
- }
- }
- return result;
- }
- /**
- * Extends object a by mutably adding to it the properties of object b.
- *
- * @param {Object} a The object to be extended
- * @param {Object} b The object to copy properties from
- * @param {Object} thisArg The object to bind function to
- *
- * @param {Object} [options]
- * @param {Boolean} [options.allOwnKeys]
- * @returns {Object} The resulting value of object a
- */
- const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
- forEach(
- b,
- (val, key) => {
- if (thisArg && isFunction(val)) {
- Object.defineProperty(a, key, {
- // Null-proto descriptor so a polluted Object.prototype.get cannot
- // hijack defineProperty's accessor-vs-data resolution.
- __proto__: null,
- value: bind(val, thisArg),
- writable: true,
- enumerable: true,
- configurable: true,
- });
- } else {
- Object.defineProperty(a, key, {
- __proto__: null,
- value: val,
- writable: true,
- enumerable: true,
- configurable: true,
- });
- }
- },
- { allOwnKeys }
- );
- return a;
- };
- /**
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
- *
- * @param {string} content with BOM
- *
- * @returns {string} content value without BOM
- */
- const stripBOM = (content) => {
- if (content.charCodeAt(0) === 0xfeff) {
- content = content.slice(1);
- }
- return content;
- };
- /**
- * Inherit the prototype methods from one constructor into another
- * @param {function} constructor
- * @param {function} superConstructor
- * @param {object} [props]
- * @param {object} [descriptors]
- *
- * @returns {void}
- */
- const inherits = (constructor, superConstructor, props, descriptors) => {
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
- Object.defineProperty(constructor.prototype, 'constructor', {
- __proto__: null,
- value: constructor,
- writable: true,
- enumerable: false,
- configurable: true,
- });
- Object.defineProperty(constructor, 'super', {
- __proto__: null,
- value: superConstructor.prototype,
- });
- props && Object.assign(constructor.prototype, props);
- };
- /**
- * Resolve object with deep prototype chain to a flat object
- * @param {Object} sourceObj source object
- * @param {Object} [destObj]
- * @param {Function|Boolean} [filter]
- * @param {Function} [propFilter]
- *
- * @returns {Object}
- */
- const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
- let props;
- let i;
- let prop;
- const merged = {};
- destObj = destObj || {};
- // eslint-disable-next-line no-eq-null,eqeqeq
- if (sourceObj == null) return destObj;
- do {
- props = Object.getOwnPropertyNames(sourceObj);
- i = props.length;
- while (i-- > 0) {
- prop = props[i];
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
- destObj[prop] = sourceObj[prop];
- merged[prop] = true;
- }
- }
- sourceObj = filter !== false && getPrototypeOf(sourceObj);
- } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
- return destObj;
- };
- /**
- * Determines whether a string ends with the characters of a specified string
- *
- * @param {String} str
- * @param {String} searchString
- * @param {Number} [position= 0]
- *
- * @returns {boolean}
- */
- const endsWith = (str, searchString, position) => {
- str = String(str);
- if (position === undefined || position > str.length) {
- position = str.length;
- }
- position -= searchString.length;
- const lastIndex = str.indexOf(searchString, position);
- return lastIndex !== -1 && lastIndex === position;
- };
- /**
- * Returns new array from array like object or null if failed
- *
- * @param {*} [thing]
- *
- * @returns {?Array}
- */
- const toArray = (thing) => {
- if (!thing) return null;
- if (isArray(thing)) return thing;
- let i = thing.length;
- if (!Number.isSafeInteger(i) || i < 0 || i > 0xffffffff) return null;
- // Bound the copy by actual indexed properties, including hidden and inherited
- // members of array-like collections, rather than by the declared length alone.
- const indexes = new Set();
- const seen = new Set();
- let source = thing;
- while (source != null && indexes.size < i) {
- if (seen.has(source)) return null;
- seen.add(source);
- const prototype = getPrototypeOf(source);
- if (isPrototypeBoundary(source, prototype, source === thing)) break;
- Object.getOwnPropertyNames(source).forEach((key) => {
- const index = +key;
- if (
- Number.isInteger(index) &&
- index >= 0 &&
- index < i &&
- String(index) === key &&
- hasOwnProperty(source, key)
- ) {
- indexes.add(index);
- }
- });
- source = prototype;
- }
- if (indexes.size !== i) return null;
- const arr = new Array(i);
- while (i-- > 0) {
- arr[i] = thing[i];
- }
- return arr;
- };
- /**
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
- * thing passed in is an instance of Uint8Array
- *
- * @param {TypedArray}
- *
- * @returns {Array}
- */
- // eslint-disable-next-line func-names
- const isTypedArray = ((TypedArray) => {
- // eslint-disable-next-line func-names
- return (thing) => {
- return TypedArray && thing instanceof TypedArray;
- };
- })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
- /**
- * For each entry in the object, call the function with the key and value.
- *
- * @param {Object<any, any>} obj - The object to iterate over.
- * @param {Function} fn - The function to call for each entry.
- *
- * @returns {void}
- */
- const forEachEntry = (obj, fn) => {
- const generator = obj && obj[iterator];
- const _iterator = generator.call(obj);
- let result;
- while ((result = _iterator.next()) && !result.done) {
- const pair = result.value;
- fn.call(obj, pair[0], pair[1]);
- }
- };
- /**
- * It takes a regular expression and a string, and returns an array of all the matches
- *
- * @param {string} regExp - The regular expression to match against.
- * @param {string} str - The string to search.
- *
- * @returns {Array<boolean>}
- */
- const matchAll = (regExp, str) => {
- let matches;
- const arr = [];
- while ((matches = regExp.exec(str)) !== null) {
- arr.push(matches);
- }
- return arr;
- };
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
- const isHTMLForm = kindOfTest('HTMLFormElement');
- const toCamelCase = (str) => {
- return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
- return p1.toUpperCase() + p2;
- });
- };
- const { propertyIsEnumerable } = Object.prototype;
- /**
- * Determine if a value is a RegExp object
- *
- * @param {*} val The value to test
- *
- * @returns {boolean} True if value is a RegExp object, otherwise false
- */
- const isRegExp = kindOfTest('RegExp');
- const reduceDescriptors = (obj, reducer) => {
- const descriptors = Object.getOwnPropertyDescriptors(obj);
- const reducedDescriptors = {};
- forEach(descriptors, (descriptor, name) => {
- let ret;
- if ((ret = reducer(descriptor, name, obj)) !== false) {
- reducedDescriptors[name] = ret || descriptor;
- }
- });
- Object.defineProperties(obj, reducedDescriptors);
- };
- /**
- * Makes all methods read-only
- * @param {Object} obj
- */
- const freezeMethods = (obj) => {
- reduceDescriptors(obj, (descriptor, name) => {
- // skip restricted props in strict mode
- if (isFunction(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
- return false;
- }
- const value = obj[name];
- if (!isFunction(value)) return;
- descriptor.enumerable = false;
- if ('writable' in descriptor) {
- descriptor.writable = false;
- return;
- }
- if (!descriptor.set) {
- descriptor.set = () => {
- throw Error("Can not rewrite read-only method '" + name + "'");
- };
- }
- });
- };
- /**
- * Converts an array or a delimited string into an object set with values as keys and true as values.
- * Useful for fast membership checks.
- *
- * @param {Array|string} arrayOrString - The array or string to convert.
- * @param {string} delimiter - The delimiter to use if input is a string.
- * @returns {Object} An object with keys from the array or string, values set to true.
- */
- const toObjectSet = (arrayOrString, delimiter) => {
- const obj = {};
- const define = (arr) => {
- arr.forEach((value) => {
- obj[value] = true;
- });
- };
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
- return obj;
- };
- const noop = () => {};
- const toFiniteNumber = (value, defaultValue) => {
- return value != null && Number.isFinite((value = +value)) ? value : defaultValue;
- };
- /**
- * If the thing is a FormData object, return true, otherwise return false.
- *
- * @param {unknown} thing - The thing to check.
- *
- * @returns {boolean}
- */
- function isSpecCompliantForm(thing) {
- return !!(
- thing &&
- isFunction(thing.append) &&
- thing[toStringTag] === 'FormData' &&
- thing[iterator]
- );
- }
- /**
- * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
- *
- * @param {Object} obj - The object to convert.
- * @returns {Object} The JSON-compatible object.
- */
- const toJSONObject = (obj) => {
- const visited = new WeakSet();
- const visit = (source) => {
- if (isObject(source)) {
- if (visited.has(source)) {
- return;
- }
- //Buffer check
- if (isBuffer(source)) {
- return source;
- }
- if (!('toJSON' in source)) {
- // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
- visited.add(source);
- let target;
- if (isSet(source)) {
- target = [];
- for (const value of source) {
- const reducedValue = visit(value);
- !isUndefined(reducedValue) && target.push(reducedValue);
- }
- } else {
- target = isArray(source) ? [] : {};
- forEach(source, (value, key) => {
- const reducedValue = visit(value);
- !isUndefined(reducedValue) && (target[key] = reducedValue);
- });
- }
- visited.delete(source);
- return target;
- }
- }
- return source;
- };
- return visit(obj);
- };
- /**
- * Determines if a value is an async function.
- *
- * @param {*} thing - The value to test.
- * @returns {boolean} True if value is an async function, otherwise false.
- */
- const isAsyncFn = kindOfTest('AsyncFunction');
- /**
- * Determines if a value is thenable (has then and catch methods).
- *
- * @param {*} thing - The value to test.
- * @returns {boolean} True if value is thenable, otherwise false.
- */
- const isThenable = (thing) =>
- thing &&
- (isObject(thing) || isFunction(thing)) &&
- isFunction(thing.then) &&
- isFunction(thing.catch);
- // original code
- // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
- /**
- * Provides a cross-platform setImmediate implementation.
- * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
- *
- * @param {boolean} setImmediateSupported - Whether setImmediate is supported.
- * @param {boolean} postMessageSupported - Whether postMessage is supported.
- * @returns {Function} A function to schedule a callback asynchronously.
- */
- const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
- if (setImmediateSupported) {
- return setImmediate;
- }
- return postMessageSupported
- ? ((token, callbacks) => {
- _global.addEventListener(
- 'message',
- ({ source, data }) => {
- if (source === _global && data === token) {
- callbacks.length && callbacks.shift()();
- }
- },
- false
- );
- return (cb) => {
- callbacks.push(cb);
- _global.postMessage(token, '*');
- };
- })(`axios@${Math.random()}`, [])
- : (cb) => setTimeout(cb);
- })(typeof setImmediate === 'function', isFunction(_global.postMessage));
- /**
- * Schedules a microtask or asynchronous callback as soon as possible.
- * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
- *
- * @type {Function}
- */
- const asap =
- typeof queueMicrotask !== 'undefined'
- ? queueMicrotask.bind(_global)
- : (typeof process !== 'undefined' && process.nextTick) || _setImmediate;
- // *********************
- const isIterable = (thing) => thing != null && isFunction(thing[iterator]);
- /**
- * Determine if a value is iterable via an iterator that is NOT sourced solely
- * from a polluted Object.prototype. Use this instead of `isIterable` whenever
- * the iterable comes from untrusted input (e.g. user-supplied header sources),
- * so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
- * into an attacker-controlled entries iterator.
- *
- * @param {*} thing The value to test
- *
- * @returns {boolean} True if value has a non-polluted iterator
- */
- const isSafeIterable = (thing) =>
- thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
- export default {
- isArray,
- isArrayBuffer,
- isBuffer,
- isFormData,
- isArrayBufferView,
- isString,
- isNumber,
- isBoolean,
- isObject,
- isPlainObject,
- isEmptyObject,
- isReadableStream,
- isRequest,
- isResponse,
- isHeaders,
- isUndefined,
- isDate,
- isFile,
- isReactNativeBlob,
- isReactNative,
- isBlob,
- isRegExp,
- isFunction,
- isStream,
- isURLSearchParams,
- isTypedArray,
- isFileList,
- forEach,
- merge,
- extend,
- trim,
- stripBOM,
- inherits,
- toFlatObject,
- kindOf,
- kindOfTest,
- endsWith,
- toArray,
- forEachEntry,
- matchAll,
- isHTMLForm,
- hasOwnProperty,
- hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
- hasOwnInPrototypeChain,
- getSafeProp,
- toSafeFlatObject,
- reduceDescriptors,
- freezeMethods,
- toObjectSet,
- toCamelCase,
- noop,
- toFiniteNumber,
- findKey,
- global: _global,
- isContextDefined,
- isSpecCompliantForm,
- toJSONObject,
- isAsyncFn,
- isThenable,
- setImmediate: _setImmediate,
- asap,
- isIterable,
- isSafeIterable,
- };
|