axios.cjs 147 KB

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