axios.cjs 123 KB

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