axios.js 124 KB

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