axios.js 96 KB

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