axios.js 101 KB

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