axios.cjs 211 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356
  1. /*! Axios v1.19.0 Copyright (c) 2026 Matt Zabriskie and contributors */
  2. 'use strict';
  3. var FormData$1 = require('form-data');
  4. var crypto = require('crypto');
  5. var url = require('url');
  6. var HttpsProxyAgent = require('https-proxy-agent');
  7. var http = require('http');
  8. var https = require('https');
  9. var http2 = require('http2');
  10. var util = require('util');
  11. var path = require('path');
  12. var followRedirects = require('follow-redirects');
  13. var zlib = require('zlib');
  14. var stream = require('stream');
  15. var events = require('events');
  16. /**
  17. * Create a bound version of a function with a specified `this` context
  18. *
  19. * @param {Function} fn - The function to bind
  20. * @param {*} thisArg - The value to be passed as the `this` parameter
  21. * @returns {Function} A new function that will call the original function with the specified `this` context
  22. */
  23. function bind(fn, thisArg) {
  24. return function wrap() {
  25. return fn.apply(thisArg, arguments);
  26. };
  27. }
  28. // utils is a library of generic helper functions non-specific to axios
  29. const {
  30. toString
  31. } = Object.prototype;
  32. const {
  33. getPrototypeOf
  34. } = Object;
  35. const {
  36. iterator,
  37. toStringTag
  38. } = Symbol;
  39. /* Creating a function that will check if an object has a property. */
  40. const hasOwnProperty = (({
  41. hasOwnProperty
  42. }) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
  43. /**
  44. * Walk the prototype chain (excluding the shared Object.prototype) looking for
  45. * an own `prop`. This distinguishes genuine own/inherited members — including
  46. * class accessors and template prototypes — from members injected via
  47. * Object.prototype pollution (e.g. `Object.prototype.username = '...'`), which
  48. * live on Object.prototype itself and are therefore never matched.
  49. *
  50. * @param {*} thing The value whose chain to inspect
  51. * @param {string|symbol} prop The property key to look for
  52. *
  53. * @returns {boolean} True when `prop` is owned below Object.prototype
  54. */
  55. const hasOwnInPrototypeChain = (thing, prop) => {
  56. let obj = thing;
  57. const seen = [];
  58. while (obj != null && obj !== Object.prototype) {
  59. if (seen.indexOf(obj) !== -1) {
  60. return false;
  61. }
  62. seen.push(obj);
  63. if (hasOwnProperty(obj, prop)) {
  64. return true;
  65. }
  66. obj = getPrototypeOf(obj);
  67. }
  68. return false;
  69. };
  70. /**
  71. * Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
  72. * properties and members inherited from a non-Object.prototype source (a class
  73. * instance or template object) are honored; a value reachable only through a
  74. * polluted Object.prototype is ignored and `undefined` is returned.
  75. *
  76. * @param {*} obj The source object
  77. * @param {string|symbol} prop The property key to read
  78. *
  79. * @returns {*} The resolved value, or undefined when unsafe/absent
  80. */
  81. const getSafeProp = (obj, prop) => obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;
  82. const kindOf = (cache => thing => {
  83. const str = toString.call(thing);
  84. return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
  85. })(Object.create(null));
  86. const kindOfTest = type => {
  87. type = type.toLowerCase();
  88. return thing => kindOf(thing) === type;
  89. };
  90. const typeOfTest = type => thing => typeof thing === type;
  91. /**
  92. * Determine if a value is a non-null object
  93. *
  94. * @param {Object} val The value to test
  95. *
  96. * @returns {boolean} True if value is an Array, otherwise false
  97. */
  98. const {
  99. isArray
  100. } = Array;
  101. /**
  102. * Determine if a value is undefined
  103. *
  104. * @param {*} val The value to test
  105. *
  106. * @returns {boolean} True if the value is undefined, otherwise false
  107. */
  108. const isUndefined = typeOfTest('undefined');
  109. /**
  110. * Determine if a value is a Buffer
  111. *
  112. * @param {*} val The value to test
  113. *
  114. * @returns {boolean} True if value is a Buffer, otherwise false
  115. */
  116. function isBuffer(val) {
  117. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
  118. }
  119. /**
  120. * Determine if a value is an ArrayBuffer
  121. *
  122. * @param {*} val The value to test
  123. *
  124. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  125. */
  126. const isArrayBuffer = kindOfTest('ArrayBuffer');
  127. /**
  128. * Determine if a value is a view on an ArrayBuffer
  129. *
  130. * @param {*} val The value to test
  131. *
  132. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  133. */
  134. function isArrayBufferView(val) {
  135. let result;
  136. if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
  137. result = ArrayBuffer.isView(val);
  138. } else {
  139. result = val && val.buffer && isArrayBuffer(val.buffer);
  140. }
  141. return result;
  142. }
  143. /**
  144. * Determine if a value is a String
  145. *
  146. * @param {*} val The value to test
  147. *
  148. * @returns {boolean} True if value is a String, otherwise false
  149. */
  150. const isString = typeOfTest('string');
  151. /**
  152. * Determine if a value is a Function
  153. *
  154. * @param {*} val The value to test
  155. * @returns {boolean} True if value is a Function, otherwise false
  156. */
  157. const isFunction$1 = typeOfTest('function');
  158. /**
  159. * Determine if a value is a Number
  160. *
  161. * @param {*} val The value to test
  162. *
  163. * @returns {boolean} True if value is a Number, otherwise false
  164. */
  165. const isNumber = typeOfTest('number');
  166. /**
  167. * Determine if a value is an Object
  168. *
  169. * @param {*} thing The value to test
  170. *
  171. * @returns {boolean} True if value is an Object, otherwise false
  172. */
  173. const isObject = thing => thing !== null && typeof thing === 'object';
  174. /**
  175. * Determine if a value is a Boolean
  176. *
  177. * @param {*} thing The value to test
  178. * @returns {boolean} True if value is a Boolean, otherwise false
  179. */
  180. const isBoolean = thing => thing === true || thing === false;
  181. /**
  182. * Determine if a value is a plain Object
  183. *
  184. * @param {*} val The value to test
  185. *
  186. * @returns {boolean} True if value is a plain Object, otherwise false
  187. */
  188. const isPlainObject = val => {
  189. if (!isObject(val)) {
  190. return false;
  191. }
  192. const prototype = getPrototypeOf(val);
  193. return (prototype === null || prototype === Object.prototype || getPrototypeOf(prototype) === null) &&
  194. // Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or
  195. // Symbol.iterator as evidence the value is a tagged/iterable type rather
  196. // than a plain object, while ignoring keys injected onto Object.prototype.
  197. !hasOwnInPrototypeChain(val, toStringTag) && !hasOwnInPrototypeChain(val, iterator);
  198. };
  199. /**
  200. * Determine if a value is an empty object (safely handles Buffers)
  201. *
  202. * @param {*} val The value to test
  203. *
  204. * @returns {boolean} True if value is an empty object, otherwise false
  205. */
  206. const isEmptyObject = val => {
  207. // Early return for non-objects or Buffers to prevent RangeError
  208. if (!isObject(val) || isBuffer(val)) {
  209. return false;
  210. }
  211. try {
  212. return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
  213. } catch (e) {
  214. // Fallback for any other objects that might cause RangeError with Object.keys()
  215. return false;
  216. }
  217. };
  218. /**
  219. * Determine if a value is a Date
  220. *
  221. * @param {*} val The value to test
  222. *
  223. * @returns {boolean} True if value is a Date, otherwise false
  224. */
  225. const isDate = kindOfTest('Date');
  226. /**
  227. * Determine if a value is a File
  228. *
  229. * @param {*} val The value to test
  230. *
  231. * @returns {boolean} True if value is a File, otherwise false
  232. */
  233. const isFile = kindOfTest('File');
  234. /**
  235. * Determine if a value is a React Native Blob
  236. * React Native "blob": an object with a `uri` attribute. Optionally, it can
  237. * also have a `name` and `type` attribute to specify filename and content type
  238. *
  239. * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
  240. *
  241. * @param {*} value The value to test
  242. *
  243. * @returns {boolean} True if value is a React Native Blob, otherwise false
  244. */
  245. const isReactNativeBlob = value => {
  246. return !!(value && typeof value.uri !== 'undefined');
  247. };
  248. /**
  249. * Determine if environment is React Native
  250. * ReactNative `FormData` has a non-standard `getParts()` method
  251. *
  252. * @param {*} formData The formData to test
  253. *
  254. * @returns {boolean} True if environment is React Native, otherwise false
  255. */
  256. const isReactNative = formData => formData && typeof formData.getParts !== 'undefined';
  257. /**
  258. * Determine if a value is a Blob
  259. *
  260. * @param {*} val The value to test
  261. *
  262. * @returns {boolean} True if value is a Blob, otherwise false
  263. */
  264. const isBlob = kindOfTest('Blob');
  265. /**
  266. * Determine if a value is a FileList
  267. *
  268. * @param {*} val The value to test
  269. *
  270. * @returns {boolean} True if value is a FileList, otherwise false
  271. */
  272. const isFileList = kindOfTest('FileList');
  273. const isSet = kindOfTest('Set');
  274. /**
  275. * Determine if a value is a Stream
  276. *
  277. * @param {*} val The value to test
  278. *
  279. * @returns {boolean} True if value is a Stream, otherwise false
  280. */
  281. const isStream = val => isObject(val) && isFunction$1(val.pipe);
  282. /**
  283. * Determine if a value is a FormData
  284. *
  285. * @param {*} thing The value to test
  286. *
  287. * @returns {boolean} True if value is an FormData, otherwise false
  288. */
  289. function getGlobal() {
  290. if (typeof globalThis !== 'undefined') return globalThis;
  291. if (typeof self !== 'undefined') return self;
  292. if (typeof window !== 'undefined') return window;
  293. if (typeof global !== 'undefined') return global;
  294. return {};
  295. }
  296. const G = getGlobal();
  297. const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
  298. const isFormData = thing => {
  299. if (!thing) return false;
  300. if (FormDataCtor && thing instanceof FormDataCtor) return true;
  301. // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
  302. const proto = getPrototypeOf(thing);
  303. if (!proto || proto === Object.prototype) return false;
  304. if (!isFunction$1(thing.append)) return false;
  305. const kind = kindOf(thing);
  306. return kind === 'formdata' ||
  307. // detect form-data instance
  308. kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]';
  309. };
  310. /**
  311. * Determine if a value is a URLSearchParams object
  312. *
  313. * @param {*} val The value to test
  314. *
  315. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  316. */
  317. const isURLSearchParams = kindOfTest('URLSearchParams');
  318. const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].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, {
  346. allOwnKeys = false
  347. } = {}) {
  348. // Don't bother if no value provided
  349. if (obj === null || typeof obj === 'undefined') {
  350. return;
  351. }
  352. let i;
  353. let l;
  354. // Force an array if not already something iterable
  355. if (typeof obj !== 'object') {
  356. /*eslint no-param-reassign:0*/
  357. obj = [obj];
  358. }
  359. if (isArray(obj)) {
  360. // Iterate over array values
  361. for (i = 0, l = obj.length; i < l; i++) {
  362. fn.call(null, obj[i], i, obj);
  363. }
  364. } else {
  365. // Buffer check
  366. if (isBuffer(obj)) {
  367. return;
  368. }
  369. // Iterate over object keys
  370. const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
  371. const len = keys.length;
  372. let key;
  373. for (i = 0; i < len; i++) {
  374. key = keys[i];
  375. fn.call(null, obj[key], key, obj);
  376. }
  377. }
  378. }
  379. /**
  380. * Finds a key in an object, case-insensitive, returning the actual key name.
  381. * Returns null if the object is a Buffer or if no match is found.
  382. *
  383. * @param {Object} obj - The object to search.
  384. * @param {string} key - The key to find (case-insensitive).
  385. * @returns {?string} The actual key name if found, otherwise null.
  386. */
  387. function findKey(obj, key) {
  388. if (isBuffer(obj)) {
  389. return null;
  390. }
  391. key = key.toLowerCase();
  392. const keys = Object.keys(obj);
  393. let i = keys.length;
  394. let _key;
  395. while (i-- > 0) {
  396. _key = keys[i];
  397. if (key === _key.toLowerCase()) {
  398. return _key;
  399. }
  400. }
  401. return null;
  402. }
  403. const _global = (() => {
  404. /*eslint no-undef:0*/
  405. if (typeof globalThis !== 'undefined') return globalThis;
  406. return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
  407. })();
  408. const isContextDefined = context => !isUndefined(context) && context !== _global;
  409. /**
  410. * Accepts varargs expecting each argument to be an object, then
  411. * immutably merges the properties of each object and returns result.
  412. *
  413. * When multiple objects contain the same key the later object in
  414. * the arguments list will take precedence.
  415. *
  416. * Example:
  417. *
  418. * ```js
  419. * const result = merge({foo: 123}, {foo: 456});
  420. * console.log(result.foo); // outputs 456
  421. * ```
  422. *
  423. * @param {Object} obj1 Object to merge
  424. *
  425. * @returns {Object} Result of all merge properties
  426. */
  427. function merge(...objs) {
  428. const {
  429. caseless,
  430. skipUndefined
  431. } = isContextDefined(this) && this || {};
  432. const result = {};
  433. const assignValue = (val, key) => {
  434. // Skip dangerous property names to prevent prototype pollution
  435. if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  436. return;
  437. }
  438. // findKey lowercases the key, so caseless lookup only applies to strings —
  439. // symbol keys are identity-matched.
  440. const targetKey = caseless && typeof key === 'string' && findKey(result, key) || key;
  441. // Read via own-prop only — a bare `result[targetKey]` walks the prototype
  442. // chain, so a polluted Object.prototype value could surface here and get
  443. // copied into the merged result.
  444. const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
  445. if (isPlainObject(existing) && isPlainObject(val)) {
  446. result[targetKey] = merge(existing, val);
  447. } else if (isPlainObject(val)) {
  448. result[targetKey] = merge({}, val);
  449. } else if (isArray(val)) {
  450. result[targetKey] = val.slice();
  451. } else if (!skipUndefined || !isUndefined(val)) {
  452. result[targetKey] = val;
  453. }
  454. };
  455. for (let i = 0, l = objs.length; i < l; i++) {
  456. const source = objs[i];
  457. if (!source || isBuffer(source)) {
  458. continue;
  459. }
  460. forEach(source, assignValue);
  461. if (typeof source !== 'object' || isArray(source)) {
  462. continue;
  463. }
  464. const symbols = Object.getOwnPropertySymbols(source);
  465. for (let j = 0; j < symbols.length; j++) {
  466. const symbol = symbols[j];
  467. if (propertyIsEnumerable.call(source, symbol)) {
  468. assignValue(source[symbol], symbol);
  469. }
  470. }
  471. }
  472. return result;
  473. }
  474. /**
  475. * Extends object a by mutably adding to it the properties of object b.
  476. *
  477. * @param {Object} a The object to be extended
  478. * @param {Object} b The object to copy properties from
  479. * @param {Object} thisArg The object to bind function to
  480. *
  481. * @param {Object} [options]
  482. * @param {Boolean} [options.allOwnKeys]
  483. * @returns {Object} The resulting value of object a
  484. */
  485. const extend = (a, b, thisArg, {
  486. allOwnKeys
  487. } = {}) => {
  488. forEach(b, (val, key) => {
  489. if (thisArg && isFunction$1(val)) {
  490. Object.defineProperty(a, key, {
  491. // Null-proto descriptor so a polluted Object.prototype.get cannot
  492. // hijack defineProperty's accessor-vs-data resolution.
  493. __proto__: null,
  494. value: bind(val, thisArg),
  495. writable: true,
  496. enumerable: true,
  497. configurable: true
  498. });
  499. } else {
  500. Object.defineProperty(a, key, {
  501. __proto__: null,
  502. value: val,
  503. writable: true,
  504. enumerable: true,
  505. configurable: true
  506. });
  507. }
  508. }, {
  509. allOwnKeys
  510. });
  511. return a;
  512. };
  513. /**
  514. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  515. *
  516. * @param {string} content with BOM
  517. *
  518. * @returns {string} content value without BOM
  519. */
  520. const stripBOM = content => {
  521. if (content.charCodeAt(0) === 0xfeff) {
  522. content = content.slice(1);
  523. }
  524. return content;
  525. };
  526. /**
  527. * Inherit the prototype methods from one constructor into another
  528. * @param {function} constructor
  529. * @param {function} superConstructor
  530. * @param {object} [props]
  531. * @param {object} [descriptors]
  532. *
  533. * @returns {void}
  534. */
  535. const inherits = (constructor, superConstructor, props, descriptors) => {
  536. constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  537. Object.defineProperty(constructor.prototype, 'constructor', {
  538. __proto__: null,
  539. value: constructor,
  540. writable: true,
  541. enumerable: false,
  542. configurable: true
  543. });
  544. Object.defineProperty(constructor, 'super', {
  545. __proto__: null,
  546. value: superConstructor.prototype
  547. });
  548. props && Object.assign(constructor.prototype, props);
  549. };
  550. /**
  551. * Resolve object with deep prototype chain to a flat object
  552. * @param {Object} sourceObj source object
  553. * @param {Object} [destObj]
  554. * @param {Function|Boolean} [filter]
  555. * @param {Function} [propFilter]
  556. *
  557. * @returns {Object}
  558. */
  559. const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
  560. let props;
  561. let i;
  562. let prop;
  563. const merged = {};
  564. destObj = destObj || {};
  565. // eslint-disable-next-line no-eq-null,eqeqeq
  566. if (sourceObj == null) return destObj;
  567. do {
  568. props = Object.getOwnPropertyNames(sourceObj);
  569. i = props.length;
  570. while (i-- > 0) {
  571. prop = props[i];
  572. if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
  573. destObj[prop] = sourceObj[prop];
  574. merged[prop] = true;
  575. }
  576. }
  577. sourceObj = filter !== false && getPrototypeOf(sourceObj);
  578. } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
  579. return destObj;
  580. };
  581. /**
  582. * Determines whether a string ends with the characters of a specified string
  583. *
  584. * @param {String} str
  585. * @param {String} searchString
  586. * @param {Number} [position= 0]
  587. *
  588. * @returns {boolean}
  589. */
  590. const endsWith = (str, searchString, position) => {
  591. str = String(str);
  592. if (position === undefined || position > str.length) {
  593. position = str.length;
  594. }
  595. position -= searchString.length;
  596. const lastIndex = str.indexOf(searchString, position);
  597. return lastIndex !== -1 && lastIndex === position;
  598. };
  599. /**
  600. * Returns new array from array like object or null if failed
  601. *
  602. * @param {*} [thing]
  603. *
  604. * @returns {?Array}
  605. */
  606. const toArray = thing => {
  607. if (!thing) return null;
  608. if (isArray(thing)) return thing;
  609. let i = thing.length;
  610. if (!isNumber(i)) return null;
  611. const arr = new Array(i);
  612. while (i-- > 0) {
  613. arr[i] = thing[i];
  614. }
  615. return arr;
  616. };
  617. /**
  618. * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
  619. * thing passed in is an instance of Uint8Array
  620. *
  621. * @param {TypedArray}
  622. *
  623. * @returns {Array}
  624. */
  625. // eslint-disable-next-line func-names
  626. const isTypedArray = (TypedArray => {
  627. // eslint-disable-next-line func-names
  628. return thing => {
  629. return TypedArray && thing instanceof TypedArray;
  630. };
  631. })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
  632. /**
  633. * For each entry in the object, call the function with the key and value.
  634. *
  635. * @param {Object<any, any>} obj - The object to iterate over.
  636. * @param {Function} fn - The function to call for each entry.
  637. *
  638. * @returns {void}
  639. */
  640. const forEachEntry = (obj, fn) => {
  641. const generator = obj && obj[iterator];
  642. const _iterator = generator.call(obj);
  643. let result;
  644. while ((result = _iterator.next()) && !result.done) {
  645. const pair = result.value;
  646. fn.call(obj, pair[0], pair[1]);
  647. }
  648. };
  649. /**
  650. * It takes a regular expression and a string, and returns an array of all the matches
  651. *
  652. * @param {string} regExp - The regular expression to match against.
  653. * @param {string} str - The string to search.
  654. *
  655. * @returns {Array<boolean>}
  656. */
  657. const matchAll = (regExp, str) => {
  658. let matches;
  659. const arr = [];
  660. while ((matches = regExp.exec(str)) !== null) {
  661. arr.push(matches);
  662. }
  663. return arr;
  664. };
  665. /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
  666. const isHTMLForm = kindOfTest('HTMLFormElement');
  667. const toCamelCase = str => {
  668. return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
  669. return p1.toUpperCase() + p2;
  670. });
  671. };
  672. const {
  673. propertyIsEnumerable
  674. } = Object.prototype;
  675. /**
  676. * Determine if a value is a RegExp object
  677. *
  678. * @param {*} val The value to test
  679. *
  680. * @returns {boolean} True if value is a RegExp object, otherwise false
  681. */
  682. const isRegExp = kindOfTest('RegExp');
  683. const reduceDescriptors = (obj, reducer) => {
  684. const descriptors = Object.getOwnPropertyDescriptors(obj);
  685. const reducedDescriptors = {};
  686. forEach(descriptors, (descriptor, name) => {
  687. let ret;
  688. if ((ret = reducer(descriptor, name, obj)) !== false) {
  689. reducedDescriptors[name] = ret || descriptor;
  690. }
  691. });
  692. Object.defineProperties(obj, reducedDescriptors);
  693. };
  694. /**
  695. * Makes all methods read-only
  696. * @param {Object} obj
  697. */
  698. const freezeMethods = obj => {
  699. reduceDescriptors(obj, (descriptor, name) => {
  700. // skip restricted props in strict mode
  701. if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
  702. return false;
  703. }
  704. const value = obj[name];
  705. if (!isFunction$1(value)) return;
  706. descriptor.enumerable = false;
  707. if ('writable' in descriptor) {
  708. descriptor.writable = false;
  709. return;
  710. }
  711. if (!descriptor.set) {
  712. descriptor.set = () => {
  713. throw Error("Can not rewrite read-only method '" + name + "'");
  714. };
  715. }
  716. });
  717. };
  718. /**
  719. * Converts an array or a delimited string into an object set with values as keys and true as values.
  720. * Useful for fast membership checks.
  721. *
  722. * @param {Array|string} arrayOrString - The array or string to convert.
  723. * @param {string} delimiter - The delimiter to use if input is a string.
  724. * @returns {Object} An object with keys from the array or string, values set to true.
  725. */
  726. const toObjectSet = (arrayOrString, delimiter) => {
  727. const obj = {};
  728. const define = arr => {
  729. arr.forEach(value => {
  730. obj[value] = true;
  731. });
  732. };
  733. isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
  734. return obj;
  735. };
  736. const noop = () => {};
  737. const toFiniteNumber = (value, defaultValue) => {
  738. return value != null && Number.isFinite(value = +value) ? value : defaultValue;
  739. };
  740. /**
  741. * If the thing is a FormData object, return true, otherwise return false.
  742. *
  743. * @param {unknown} thing - The thing to check.
  744. *
  745. * @returns {boolean}
  746. */
  747. function isSpecCompliantForm(thing) {
  748. return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
  749. }
  750. /**
  751. * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
  752. *
  753. * @param {Object} obj - The object to convert.
  754. * @returns {Object} The JSON-compatible object.
  755. */
  756. const toJSONObject = obj => {
  757. const visited = new WeakSet();
  758. const visit = source => {
  759. if (isObject(source)) {
  760. if (visited.has(source)) {
  761. return;
  762. }
  763. //Buffer check
  764. if (isBuffer(source)) {
  765. return source;
  766. }
  767. if (!('toJSON' in source)) {
  768. // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
  769. visited.add(source);
  770. let target;
  771. if (isSet(source)) {
  772. target = [];
  773. for (const value of source) {
  774. const reducedValue = visit(value);
  775. !isUndefined(reducedValue) && target.push(reducedValue);
  776. }
  777. } else {
  778. target = isArray(source) ? [] : {};
  779. forEach(source, (value, key) => {
  780. const reducedValue = visit(value);
  781. !isUndefined(reducedValue) && (target[key] = reducedValue);
  782. });
  783. }
  784. visited.delete(source);
  785. return target;
  786. }
  787. }
  788. return source;
  789. };
  790. return visit(obj);
  791. };
  792. /**
  793. * Determines if a value is an async function.
  794. *
  795. * @param {*} thing - The value to test.
  796. * @returns {boolean} True if value is an async function, otherwise false.
  797. */
  798. const isAsyncFn = kindOfTest('AsyncFunction');
  799. /**
  800. * Determines if a value is thenable (has then and catch methods).
  801. *
  802. * @param {*} thing - The value to test.
  803. * @returns {boolean} True if value is thenable, otherwise false.
  804. */
  805. const isThenable = thing => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
  806. // original code
  807. // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
  808. /**
  809. * Provides a cross-platform setImmediate implementation.
  810. * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
  811. *
  812. * @param {boolean} setImmediateSupported - Whether setImmediate is supported.
  813. * @param {boolean} postMessageSupported - Whether postMessage is supported.
  814. * @returns {Function} A function to schedule a callback asynchronously.
  815. */
  816. const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
  817. if (setImmediateSupported) {
  818. return setImmediate;
  819. }
  820. return postMessageSupported ? ((token, callbacks) => {
  821. _global.addEventListener('message', ({
  822. source,
  823. data
  824. }) => {
  825. if (source === _global && data === token) {
  826. callbacks.length && callbacks.shift()();
  827. }
  828. }, false);
  829. return cb => {
  830. callbacks.push(cb);
  831. _global.postMessage(token, '*');
  832. };
  833. })(`axios@${Math.random()}`, []) : cb => setTimeout(cb);
  834. })(typeof setImmediate === 'function', isFunction$1(_global.postMessage));
  835. /**
  836. * Schedules a microtask or asynchronous callback as soon as possible.
  837. * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
  838. *
  839. * @type {Function}
  840. */
  841. const asap = typeof queueMicrotask !== 'undefined' ? queueMicrotask.bind(_global) : typeof process !== 'undefined' && process.nextTick || _setImmediate;
  842. // *********************
  843. const isIterable = thing => thing != null && isFunction$1(thing[iterator]);
  844. /**
  845. * Determine if a value is iterable via an iterator that is NOT sourced solely
  846. * from a polluted Object.prototype. Use this instead of `isIterable` whenever
  847. * the iterable comes from untrusted input (e.g. user-supplied header sources),
  848. * so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
  849. * into an attacker-controlled entries iterator.
  850. *
  851. * @param {*} thing The value to test
  852. *
  853. * @returns {boolean} True if value has a non-polluted iterator
  854. */
  855. const isSafeIterable = thing => thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
  856. var utils$1 = {
  857. isArray,
  858. isArrayBuffer,
  859. isBuffer,
  860. isFormData,
  861. isArrayBufferView,
  862. isString,
  863. isNumber,
  864. isBoolean,
  865. isObject,
  866. isPlainObject,
  867. isEmptyObject,
  868. isReadableStream,
  869. isRequest,
  870. isResponse,
  871. isHeaders,
  872. isUndefined,
  873. isDate,
  874. isFile,
  875. isReactNativeBlob,
  876. isReactNative,
  877. isBlob,
  878. isRegExp,
  879. isFunction: isFunction$1,
  880. isStream,
  881. isURLSearchParams,
  882. isTypedArray,
  883. isFileList,
  884. forEach,
  885. merge,
  886. extend,
  887. trim,
  888. stripBOM,
  889. inherits,
  890. toFlatObject,
  891. kindOf,
  892. kindOfTest,
  893. endsWith,
  894. toArray,
  895. forEachEntry,
  896. matchAll,
  897. isHTMLForm,
  898. hasOwnProperty,
  899. hasOwnProp: hasOwnProperty,
  900. // an alias to avoid ESLint no-prototype-builtins detection
  901. hasOwnInPrototypeChain,
  902. getSafeProp,
  903. reduceDescriptors,
  904. freezeMethods,
  905. toObjectSet,
  906. toCamelCase,
  907. noop,
  908. toFiniteNumber,
  909. findKey,
  910. global: _global,
  911. isContextDefined,
  912. isSpecCompliantForm,
  913. toJSONObject,
  914. isAsyncFn,
  915. isThenable,
  916. setImmediate: _setImmediate,
  917. asap,
  918. isIterable,
  919. isSafeIterable
  920. };
  921. // RawAxiosHeaders whose duplicates are ignored by node
  922. // c.f. https://nodejs.org/api/http.html#http_message_headers
  923. const ignoreDuplicateOf = utils$1.toObjectSet(['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']);
  924. /**
  925. * Parse headers into an object
  926. *
  927. * ```
  928. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  929. * Content-Type: application/json
  930. * Connection: keep-alive
  931. * Transfer-Encoding: chunked
  932. * ```
  933. *
  934. * @param {String} rawHeaders Headers needing to be parsed
  935. *
  936. * @returns {Object} Headers parsed into an object
  937. */
  938. var parseHeaders = rawHeaders => {
  939. const parsed = {};
  940. let key;
  941. let val;
  942. let i;
  943. rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
  944. i = line.indexOf(':');
  945. key = line.substring(0, i).trim().toLowerCase();
  946. val = line.substring(i + 1).trim();
  947. const hasKey = utils$1.hasOwnProp(parsed, key);
  948. if (!key || hasKey && utils$1.hasOwnProp(ignoreDuplicateOf, key)) {
  949. return;
  950. }
  951. if (key === 'set-cookie') {
  952. if (hasKey) {
  953. parsed[key].push(val);
  954. } else {
  955. parsed[key] = [val];
  956. }
  957. } else {
  958. parsed[key] = hasKey ? parsed[key] + ', ' + val : val;
  959. }
  960. });
  961. return parsed;
  962. };
  963. function trimSPorHTAB(str) {
  964. let start = 0;
  965. let end = str.length;
  966. while (start < end) {
  967. const code = str.charCodeAt(start);
  968. if (code !== 0x09 && code !== 0x20) {
  969. break;
  970. }
  971. start += 1;
  972. }
  973. while (end > start) {
  974. const code = str.charCodeAt(end - 1);
  975. if (code !== 0x09 && code !== 0x20) {
  976. break;
  977. }
  978. end -= 1;
  979. }
  980. return start === 0 && end === str.length ? str : str.slice(start, end);
  981. }
  982. // The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
  983. // eslint-disable-next-line no-control-regex
  984. const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g');
  985. // eslint-disable-next-line no-control-regex
  986. const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g');
  987. function sanitizeValue(value, invalidChars) {
  988. if (utils$1.isArray(value)) {
  989. return value.map(item => sanitizeValue(item, invalidChars));
  990. }
  991. return trimSPorHTAB(String(value).replace(invalidChars, ''));
  992. }
  993. const sanitizeHeaderValue = value => sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
  994. const sanitizeByteStringHeaderValue = value => sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
  995. function toByteStringHeaderObject(headers) {
  996. const byteStringHeaders = Object.create(null);
  997. utils$1.forEach(headers.toJSON(), (value, header) => {
  998. byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
  999. });
  1000. return byteStringHeaders;
  1001. }
  1002. const $internals = Symbol('internals');
  1003. function normalizeHeader(header) {
  1004. return header && String(header).trim().toLowerCase();
  1005. }
  1006. function normalizeValue(value) {
  1007. if (value === false || value == null) {
  1008. return value;
  1009. }
  1010. return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
  1011. }
  1012. function parseTokens(str) {
  1013. const tokens = Object.create(null);
  1014. const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  1015. let match;
  1016. while (match = tokensRE.exec(str)) {
  1017. tokens[match[1]] = match[2];
  1018. }
  1019. return tokens;
  1020. }
  1021. const parameterNameRE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  1022. function trimOWS(value) {
  1023. let start = 0;
  1024. let end = value.length;
  1025. while (start < end) {
  1026. const code = value.charCodeAt(start);
  1027. if (code !== 0x09 && code !== 0x20) {
  1028. break;
  1029. }
  1030. start += 1;
  1031. }
  1032. while (end > start) {
  1033. const code = value.charCodeAt(end - 1);
  1034. if (code !== 0x09 && code !== 0x20) {
  1035. break;
  1036. }
  1037. end -= 1;
  1038. }
  1039. return start === 0 && end === value.length ? value : value.slice(start, end);
  1040. }
  1041. function decodeQuotedString(value) {
  1042. const last = value.length - 1;
  1043. if (last < 1 || value.charCodeAt(0) !== 0x22 || value.charCodeAt(last) !== 0x22) {
  1044. return value;
  1045. }
  1046. let decoded = '';
  1047. for (let i = 1; i < last; i++) {
  1048. const code = value.charCodeAt(i);
  1049. if (code === 0x22) {
  1050. return value;
  1051. }
  1052. if (code === 0x5c) {
  1053. i += 1;
  1054. if (i >= last) {
  1055. return value;
  1056. }
  1057. }
  1058. decoded += value[i];
  1059. }
  1060. return decoded;
  1061. }
  1062. function parseParameters(value) {
  1063. const parameters = Object.create(null);
  1064. const str = String(value);
  1065. let start = 0;
  1066. let quoted = false;
  1067. let escaped = false;
  1068. function parseParameter(end) {
  1069. const part = trimOWS(str.slice(start, end));
  1070. const equals = part.indexOf('=');
  1071. if (equals < 1) {
  1072. return;
  1073. }
  1074. const name = trimOWS(part.slice(0, equals));
  1075. if (!parameterNameRE.test(name)) {
  1076. return;
  1077. }
  1078. const normalizedName = name.toLowerCase();
  1079. if (normalizedName === '__proto__' || normalizedName === 'constructor' || normalizedName === 'prototype') {
  1080. return;
  1081. }
  1082. const parameterValue = trimOWS(part.slice(equals + 1));
  1083. parameters[normalizedName] = decodeQuotedString(parameterValue);
  1084. }
  1085. for (let i = 0; i < str.length; i++) {
  1086. const code = str.charCodeAt(i);
  1087. if (quoted) {
  1088. if (escaped) {
  1089. escaped = false;
  1090. } else if (code === 0x5c) {
  1091. escaped = true;
  1092. } else if (code === 0x22) {
  1093. quoted = false;
  1094. }
  1095. } else if (code === 0x22) {
  1096. quoted = true;
  1097. } else if (code === 0x2c || code === 0x3b) {
  1098. parseParameter(i);
  1099. start = i + 1;
  1100. }
  1101. }
  1102. parseParameter(str.length);
  1103. return parameters;
  1104. }
  1105. const isValidHeaderName = str => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
  1106. function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
  1107. if (utils$1.isFunction(filter)) {
  1108. return filter.call(this, value, header);
  1109. }
  1110. if (isHeaderNameFilter) {
  1111. value = header;
  1112. }
  1113. if (!utils$1.isString(value)) return;
  1114. if (utils$1.isString(filter)) {
  1115. return value.indexOf(filter) !== -1;
  1116. }
  1117. if (utils$1.isRegExp(filter)) {
  1118. return filter.test(value);
  1119. }
  1120. }
  1121. function formatHeader(header) {
  1122. return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
  1123. return char.toUpperCase() + str;
  1124. });
  1125. }
  1126. function buildAccessors(obj, header) {
  1127. const accessorName = utils$1.toCamelCase(' ' + header);
  1128. ['get', 'set', 'has'].forEach(methodName => {
  1129. Object.defineProperty(obj, methodName + accessorName, {
  1130. // Null-proto descriptor so a polluted Object.prototype.get cannot turn
  1131. // this data descriptor into an accessor descriptor on the way in.
  1132. __proto__: null,
  1133. value: function (arg1, arg2, arg3) {
  1134. return this[methodName].call(this, header, arg1, arg2, arg3);
  1135. },
  1136. configurable: true
  1137. });
  1138. });
  1139. }
  1140. class AxiosHeaders {
  1141. constructor(headers) {
  1142. headers && this.set(headers);
  1143. }
  1144. set(header, valueOrRewrite, rewrite) {
  1145. const self = this;
  1146. function setHeader(_value, _header, _rewrite) {
  1147. const lHeader = normalizeHeader(_header);
  1148. if (!lHeader) {
  1149. return;
  1150. }
  1151. const key = utils$1.findKey(self, lHeader);
  1152. if (!key || self[key] === undefined || _rewrite === true || _rewrite === undefined && self[key] !== false) {
  1153. self[key || _header] = normalizeValue(_value);
  1154. }
  1155. }
  1156. const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
  1157. if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
  1158. setHeaders(header, valueOrRewrite);
  1159. } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
  1160. setHeaders(parseHeaders(header), valueOrRewrite);
  1161. } else if (utils$1.isObject(header) && utils$1.isSafeIterable(header)) {
  1162. let obj = Object.create(null),
  1163. dest,
  1164. key;
  1165. for (const entry of header) {
  1166. if (!utils$1.isArray(entry)) {
  1167. throw new TypeError('Object iterator must return a key-value pair');
  1168. }
  1169. key = entry[0];
  1170. if (utils$1.hasOwnProp(obj, key)) {
  1171. dest = obj[key];
  1172. obj[key] = utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]];
  1173. } else {
  1174. obj[key] = entry[1];
  1175. }
  1176. }
  1177. setHeaders(obj, valueOrRewrite);
  1178. } else {
  1179. header != null && setHeader(valueOrRewrite, header, rewrite);
  1180. }
  1181. return this;
  1182. }
  1183. get(header, parser) {
  1184. header = normalizeHeader(header);
  1185. if (header) {
  1186. const key = utils$1.findKey(this, header);
  1187. if (key) {
  1188. const value = this[key];
  1189. if (!parser) {
  1190. return value;
  1191. }
  1192. if (parser === true) {
  1193. return parseTokens(value);
  1194. }
  1195. if (utils$1.isFunction(parser)) {
  1196. return parser.call(this, value, key);
  1197. }
  1198. if (utils$1.isRegExp(parser)) {
  1199. return parser.exec(value);
  1200. }
  1201. throw new TypeError('parser must be boolean|regexp|function');
  1202. }
  1203. }
  1204. }
  1205. has(header, matcher) {
  1206. header = normalizeHeader(header);
  1207. if (header) {
  1208. const key = utils$1.findKey(this, header);
  1209. return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
  1210. }
  1211. return false;
  1212. }
  1213. delete(header, matcher) {
  1214. const self = this;
  1215. let deleted = false;
  1216. function deleteHeader(_header) {
  1217. _header = normalizeHeader(_header);
  1218. if (_header) {
  1219. const key = utils$1.findKey(self, _header);
  1220. if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
  1221. delete self[key];
  1222. deleted = true;
  1223. }
  1224. }
  1225. }
  1226. if (utils$1.isArray(header)) {
  1227. header.forEach(deleteHeader);
  1228. } else {
  1229. deleteHeader(header);
  1230. }
  1231. return deleted;
  1232. }
  1233. clear(matcher) {
  1234. const keys = Object.keys(this);
  1235. let i = keys.length;
  1236. let deleted = false;
  1237. while (i--) {
  1238. const key = keys[i];
  1239. if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
  1240. delete this[key];
  1241. deleted = true;
  1242. }
  1243. }
  1244. return deleted;
  1245. }
  1246. normalize(format) {
  1247. const self = this;
  1248. const headers = {};
  1249. utils$1.forEach(this, (value, header) => {
  1250. const key = utils$1.findKey(headers, header);
  1251. if (key) {
  1252. self[key] = normalizeValue(value);
  1253. delete self[header];
  1254. return;
  1255. }
  1256. const normalized = format ? formatHeader(header) : String(header).trim();
  1257. if (normalized !== header) {
  1258. delete self[header];
  1259. }
  1260. self[normalized] = normalizeValue(value);
  1261. headers[normalized] = true;
  1262. });
  1263. return this;
  1264. }
  1265. concat(...targets) {
  1266. return this.constructor.concat(this, ...targets);
  1267. }
  1268. toJSON(asStrings) {
  1269. const obj = Object.create(null);
  1270. utils$1.forEach(this, (value, header) => {
  1271. value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
  1272. });
  1273. return obj;
  1274. }
  1275. [Symbol.iterator]() {
  1276. return Object.entries(this.toJSON())[Symbol.iterator]();
  1277. }
  1278. toString() {
  1279. return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
  1280. }
  1281. getSetCookie() {
  1282. const value = this.get('set-cookie');
  1283. return utils$1.isArray(value) ? value : value == null || value === false ? [] : [value];
  1284. }
  1285. get [Symbol.toStringTag]() {
  1286. return 'AxiosHeaders';
  1287. }
  1288. static from(thing) {
  1289. return thing instanceof this ? thing : new this(thing);
  1290. }
  1291. static parseParameters(value) {
  1292. return parseParameters(value);
  1293. }
  1294. static concat(first, ...targets) {
  1295. const computed = new this(first);
  1296. targets.forEach(target => computed.set(target));
  1297. return computed;
  1298. }
  1299. static accessor(header) {
  1300. const internals = this[$internals] = this[$internals] = {
  1301. accessors: {}
  1302. };
  1303. const accessors = internals.accessors;
  1304. const prototype = this.prototype;
  1305. function defineAccessor(_header) {
  1306. const lHeader = normalizeHeader(_header);
  1307. if (!accessors[lHeader]) {
  1308. buildAccessors(prototype, _header);
  1309. accessors[lHeader] = true;
  1310. }
  1311. }
  1312. utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
  1313. return this;
  1314. }
  1315. }
  1316. AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
  1317. // reserved names hotfix
  1318. utils$1.reduceDescriptors(AxiosHeaders.prototype, ({
  1319. value
  1320. }, key) => {
  1321. let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
  1322. return {
  1323. get: () => value,
  1324. set(headerValue) {
  1325. this[mapped] = headerValue;
  1326. }
  1327. };
  1328. });
  1329. utils$1.freezeMethods(AxiosHeaders);
  1330. const REDACTED = '[REDACTED ****]';
  1331. function hasOwnOrPrototypeToJSON(source) {
  1332. if (utils$1.hasOwnProp(source, 'toJSON')) {
  1333. return true;
  1334. }
  1335. let prototype = Object.getPrototypeOf(source);
  1336. while (prototype && prototype !== Object.prototype) {
  1337. if (utils$1.hasOwnProp(prototype, 'toJSON')) {
  1338. return true;
  1339. }
  1340. prototype = Object.getPrototypeOf(prototype);
  1341. }
  1342. return false;
  1343. }
  1344. // Build a plain-object snapshot of `config` and replace the value of any key
  1345. // (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays
  1346. // and AxiosHeaders, and short-circuits on circular references.
  1347. function redactConfig(config, redactKeys) {
  1348. const lowerKeys = new Set(redactKeys.map(k => String(k).toLowerCase()));
  1349. const seen = [];
  1350. const visit = source => {
  1351. if (source === null || typeof source !== 'object') return source;
  1352. if (utils$1.isBuffer(source)) return source;
  1353. if (seen.indexOf(source) !== -1) return undefined;
  1354. if (source instanceof AxiosHeaders) {
  1355. source = source.toJSON();
  1356. }
  1357. seen.push(source);
  1358. let result;
  1359. if (utils$1.isArray(source)) {
  1360. result = [];
  1361. source.forEach((v, i) => {
  1362. const reducedValue = visit(v);
  1363. if (!utils$1.isUndefined(reducedValue)) {
  1364. result[i] = reducedValue;
  1365. }
  1366. });
  1367. } else {
  1368. if (!utils$1.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
  1369. seen.pop();
  1370. return source;
  1371. }
  1372. result = Object.create(null);
  1373. for (const [key, value] of Object.entries(source)) {
  1374. const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
  1375. if (!utils$1.isUndefined(reducedValue)) {
  1376. result[key] = reducedValue;
  1377. }
  1378. }
  1379. }
  1380. seen.pop();
  1381. return result;
  1382. };
  1383. return visit(config);
  1384. }
  1385. function stringifySafely$1(value) {
  1386. try {
  1387. return String(value);
  1388. } catch (err) {
  1389. return '';
  1390. }
  1391. }
  1392. function aggregateErrorMessage(error) {
  1393. const message = error.errors.map(entry => {
  1394. try {
  1395. return entry && entry.message ? stringifySafely$1(entry.message) : stringifySafely$1(entry);
  1396. } catch (err) {
  1397. return '';
  1398. }
  1399. }).filter(Boolean).join('; ');
  1400. return message || error.name || 'AggregateError';
  1401. }
  1402. class AxiosError extends Error {
  1403. static from(error, code, config, request, response, customProps) {
  1404. // `AggregateError` (thrown by Node on dual-stack/Happy-Eyeballs connection
  1405. // failures) has an empty `message`; its detail lives in `errors[]`. Without
  1406. // this, the wrapped error surfaces with a blank message (see #6721).
  1407. let message = error.message;
  1408. if (!message && utils$1.isArray(error.errors) && error.errors.length) {
  1409. message = aggregateErrorMessage(error);
  1410. }
  1411. const axiosError = new AxiosError(message, code || error.code, config, request, response);
  1412. // Match native `Error` `cause` semantics: non-enumerable. The wrapped
  1413. // error often carries circular internals (sockets, requests, agents), so
  1414. // an enumerable `cause` makes structured loggers (pino/winston) and any
  1415. // own-property walk throw "Converting circular structure to JSON".
  1416. // Regression from #6982; see #7205. `__proto__: null` mirrors the
  1417. // `message` descriptor below (prototype-pollution-safe descriptor).
  1418. Object.defineProperty(axiosError, 'cause', {
  1419. __proto__: null,
  1420. value: error,
  1421. writable: true,
  1422. enumerable: false,
  1423. configurable: true
  1424. });
  1425. axiosError.name = error.name;
  1426. // Preserve status from the original error if not already set from response
  1427. if (error.status != null && axiosError.status == null) {
  1428. axiosError.status = error.status;
  1429. }
  1430. customProps && Object.assign(axiosError, customProps);
  1431. return axiosError;
  1432. }
  1433. /**
  1434. * Create an Error with the specified message, config, error code, request and response.
  1435. *
  1436. * @param {string} message The error message.
  1437. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  1438. * @param {Object} [config] The config.
  1439. * @param {Object} [request] The request.
  1440. * @param {Object} [response] The response.
  1441. *
  1442. * @returns {Error} The created error.
  1443. */
  1444. constructor(message, code, config, request, response) {
  1445. super(message);
  1446. // Make message enumerable to maintain backward compatibility
  1447. // The native Error constructor sets message as non-enumerable,
  1448. // but axios < v1.13.3 had it as enumerable
  1449. Object.defineProperty(this, 'message', {
  1450. // Null-proto descriptor so a polluted Object.prototype.get cannot turn
  1451. // this data descriptor into an accessor descriptor on the way in.
  1452. __proto__: null,
  1453. value: message,
  1454. enumerable: true,
  1455. writable: true,
  1456. configurable: true
  1457. });
  1458. this.name = 'AxiosError';
  1459. this.isAxiosError = true;
  1460. code && (this.code = code);
  1461. config && (this.config = config);
  1462. request && (this.request = request);
  1463. if (response) {
  1464. this.response = response;
  1465. this.status = response.status;
  1466. }
  1467. }
  1468. toJSON() {
  1469. // Opt-in redaction: when the request config carries a `redact` array, the
  1470. // value of any matching key (case-insensitive, at any depth) is replaced
  1471. // with REDACTED in the serialized snapshot. Undefined or empty leaves the
  1472. // existing serialization behavior unchanged.
  1473. const config = this.config;
  1474. const redactKeys = config && utils$1.hasOwnProp(config, 'redact') ? config.redact : undefined;
  1475. const serializedConfig = utils$1.isArray(redactKeys) && redactKeys.length > 0 ? redactConfig(config, redactKeys) : utils$1.toJSONObject(config);
  1476. return {
  1477. // Standard
  1478. message: this.message,
  1479. name: this.name,
  1480. // Microsoft
  1481. description: this.description,
  1482. number: this.number,
  1483. // Mozilla
  1484. fileName: this.fileName,
  1485. lineNumber: this.lineNumber,
  1486. columnNumber: this.columnNumber,
  1487. stack: this.stack,
  1488. // Axios
  1489. config: serializedConfig,
  1490. code: this.code,
  1491. status: this.status
  1492. };
  1493. }
  1494. }
  1495. // This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
  1496. AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
  1497. AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
  1498. AxiosError.ECONNABORTED = 'ECONNABORTED';
  1499. AxiosError.ETIMEDOUT = 'ETIMEDOUT';
  1500. AxiosError.ECONNREFUSED = 'ECONNREFUSED';
  1501. AxiosError.ERR_NETWORK = 'ERR_NETWORK';
  1502. AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
  1503. AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';
  1504. AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
  1505. AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
  1506. AxiosError.ERR_CANCELED = 'ERR_CANCELED';
  1507. AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
  1508. AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
  1509. AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
  1510. var PlatformBuffer = {
  1511. isBufferAvailable() {
  1512. return typeof Buffer !== 'undefined';
  1513. },
  1514. from(value) {
  1515. return Buffer.from(value);
  1516. }
  1517. };
  1518. // Default nesting limit shared with the inverse transform (formDataToJSON) so
  1519. // the FormData <-> JSON round-trip stays symmetric.
  1520. const DEFAULT_FORM_DATA_MAX_DEPTH = 100;
  1521. /**
  1522. * Determines if the given thing is a array or js object.
  1523. *
  1524. * @param {string} thing - The object or array to be visited.
  1525. *
  1526. * @returns {boolean}
  1527. */
  1528. function isVisitable(thing) {
  1529. return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
  1530. }
  1531. /**
  1532. * It removes the brackets from the end of a string
  1533. *
  1534. * @param {string} key - The key of the parameter.
  1535. *
  1536. * @returns {string} the key without the brackets.
  1537. */
  1538. function removeBrackets(key) {
  1539. return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
  1540. }
  1541. /**
  1542. * It takes a path, a key, and a boolean, and returns a string
  1543. *
  1544. * @param {string} path - The path to the current key.
  1545. * @param {string} key - The key of the current object being iterated over.
  1546. * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
  1547. *
  1548. * @returns {string} The path to the current key.
  1549. */
  1550. function renderKey(path, key, dots) {
  1551. if (!path) return key;
  1552. return path.concat(key).map(function each(token, i) {
  1553. // eslint-disable-next-line no-param-reassign
  1554. token = removeBrackets(token);
  1555. return !dots && i ? '[' + token + ']' : token;
  1556. }).join(dots ? '.' : '');
  1557. }
  1558. /**
  1559. * If the array is an array and none of its elements are visitable, then it's a flat array.
  1560. *
  1561. * @param {Array<any>} arr - The array to check
  1562. *
  1563. * @returns {boolean}
  1564. */
  1565. function isFlatArray(arr) {
  1566. return utils$1.isArray(arr) && !arr.some(isVisitable);
  1567. }
  1568. const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
  1569. return /^is[A-Z]/.test(prop);
  1570. });
  1571. /**
  1572. * Convert a data object to FormData
  1573. *
  1574. * @param {Object} obj
  1575. * @param {?Object} [formData]
  1576. * @param {?Object} [options]
  1577. * @param {Function} [options.visitor]
  1578. * @param {Boolean} [options.metaTokens = true]
  1579. * @param {Boolean} [options.dots = false]
  1580. * @param {?Boolean} [options.indexes = false]
  1581. *
  1582. * @returns {Object}
  1583. **/
  1584. /**
  1585. * It converts an object into a FormData object
  1586. *
  1587. * @param {Object<any, any>} obj - The object to convert to form data.
  1588. * @param {string} formData - The FormData object to append to.
  1589. * @param {Object<string, any>} options
  1590. *
  1591. * @returns
  1592. */
  1593. function toFormData(obj, formData, options) {
  1594. if (!utils$1.isObject(obj)) {
  1595. throw new TypeError('target must be an object');
  1596. }
  1597. // eslint-disable-next-line no-param-reassign
  1598. formData = formData || new (FormData$1 || FormData)();
  1599. // eslint-disable-next-line no-param-reassign
  1600. options = utils$1.toFlatObject(options, {
  1601. metaTokens: true,
  1602. dots: false,
  1603. indexes: false
  1604. }, false, function defined(option, source) {
  1605. // eslint-disable-next-line no-eq-null,eqeqeq
  1606. return !utils$1.isUndefined(source[option]);
  1607. });
  1608. const metaTokens = options.metaTokens;
  1609. // eslint-disable-next-line no-use-before-define
  1610. const visitor = options.visitor || defaultVisitor;
  1611. const dots = options.dots;
  1612. const indexes = options.indexes;
  1613. const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
  1614. const maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
  1615. const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
  1616. const stack = [];
  1617. if (!utils$1.isFunction(visitor)) {
  1618. throw new TypeError('visitor must be a function');
  1619. }
  1620. function convertValue(value) {
  1621. if (value === null) return '';
  1622. if (utils$1.isDate(value)) {
  1623. return value.toISOString();
  1624. }
  1625. if (utils$1.isBoolean(value)) {
  1626. return value.toString();
  1627. }
  1628. if (!useBlob && utils$1.isBlob(value)) {
  1629. throw new AxiosError('Blob is not supported. Use a Buffer instead.');
  1630. }
  1631. if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
  1632. if (useBlob && typeof _Blob === 'function') {
  1633. return new _Blob([value]);
  1634. }
  1635. if (PlatformBuffer && PlatformBuffer.isBufferAvailable()) {
  1636. return PlatformBuffer.from(value);
  1637. }
  1638. throw new AxiosError('Blob is not supported. Use a Buffer instead.', AxiosError.ERR_NOT_SUPPORT);
  1639. }
  1640. return value;
  1641. }
  1642. function throwIfMaxDepthExceeded(depth) {
  1643. if (depth > maxDepth) {
  1644. throw new AxiosError('Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
  1645. }
  1646. }
  1647. function stringifyWithDepthLimit(value, depth) {
  1648. if (maxDepth === Infinity) {
  1649. return JSON.stringify(value);
  1650. }
  1651. const ancestors = [];
  1652. return JSON.stringify(value, function limitDepth(_key, currentValue) {
  1653. if (!utils$1.isObject(currentValue)) {
  1654. return currentValue;
  1655. }
  1656. while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
  1657. ancestors.pop();
  1658. }
  1659. ancestors.push(currentValue);
  1660. throwIfMaxDepthExceeded(depth + ancestors.length - 1);
  1661. return currentValue;
  1662. });
  1663. }
  1664. /**
  1665. * Default visitor.
  1666. *
  1667. * @param {*} value
  1668. * @param {String|Number} key
  1669. * @param {Array<String|Number>} path
  1670. * @this {FormData}
  1671. *
  1672. * @returns {boolean} return true to visit the each prop of the value recursively
  1673. */
  1674. function defaultVisitor(value, key, path) {
  1675. let arr = value;
  1676. if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
  1677. formData.append(renderKey(path, key, dots), convertValue(value));
  1678. return false;
  1679. }
  1680. if (value && !path && typeof value === 'object') {
  1681. if (utils$1.endsWith(key, '{}')) {
  1682. // eslint-disable-next-line no-param-reassign
  1683. key = metaTokens ? key : key.slice(0, -2);
  1684. // eslint-disable-next-line no-param-reassign
  1685. value = stringifyWithDepthLimit(value, 1);
  1686. } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))) {
  1687. // eslint-disable-next-line no-param-reassign
  1688. key = removeBrackets(key);
  1689. arr.forEach(function each(el, index) {
  1690. !(utils$1.isUndefined(el) || el === null) && formData.append(
  1691. // eslint-disable-next-line no-nested-ternary
  1692. indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + '[]', convertValue(el));
  1693. });
  1694. return false;
  1695. }
  1696. }
  1697. if (isVisitable(value)) {
  1698. return true;
  1699. }
  1700. formData.append(renderKey(path, key, dots), convertValue(value));
  1701. return false;
  1702. }
  1703. const exposedHelpers = Object.assign(predicates, {
  1704. defaultVisitor,
  1705. convertValue,
  1706. isVisitable
  1707. });
  1708. function build(value, path, depth = 0) {
  1709. if (utils$1.isUndefined(value)) return;
  1710. throwIfMaxDepthExceeded(depth);
  1711. if (stack.indexOf(value) !== -1) {
  1712. throw new Error('Circular reference detected in ' + path.join('.'));
  1713. }
  1714. stack.push(value);
  1715. utils$1.forEach(value, function each(el, key) {
  1716. const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
  1717. if (result === true) {
  1718. build(el, path ? path.concat(key) : [key], depth + 1);
  1719. }
  1720. });
  1721. stack.pop();
  1722. }
  1723. if (!utils$1.isObject(obj)) {
  1724. throw new TypeError('data must be an object');
  1725. }
  1726. build(obj);
  1727. return formData;
  1728. }
  1729. /**
  1730. * It encodes a string by replacing all characters that are not in the unreserved set with
  1731. * their percent-encoded equivalents
  1732. *
  1733. * @param {string} str - The string to encode.
  1734. *
  1735. * @returns {string} The encoded string.
  1736. */
  1737. function encode$1(str) {
  1738. const charMap = {
  1739. '!': '%21',
  1740. "'": '%27',
  1741. '(': '%28',
  1742. ')': '%29',
  1743. '~': '%7E',
  1744. '%20': '+'
  1745. };
  1746. return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
  1747. return charMap[match];
  1748. });
  1749. }
  1750. /**
  1751. * It takes a params object and converts it to a FormData object
  1752. *
  1753. * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
  1754. * @param {Object<string, any>} options - The options object passed to the Axios constructor.
  1755. *
  1756. * @returns {void}
  1757. */
  1758. function AxiosURLSearchParams(params, options) {
  1759. this._pairs = [];
  1760. params && toFormData(params, this, options);
  1761. }
  1762. const prototype = AxiosURLSearchParams.prototype;
  1763. prototype.append = function append(name, value) {
  1764. this._pairs.push([name, value]);
  1765. };
  1766. prototype.toString = function toString(encoder) {
  1767. const _encode = encoder ? value => encoder.call(this, value, encode$1) : encode$1;
  1768. return this._pairs.map(function each(pair) {
  1769. return _encode(pair[0]) + '=' + _encode(pair[1]);
  1770. }, '').join('&');
  1771. };
  1772. /**
  1773. * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
  1774. * their plain counterparts (`:`, `$`, `,`, `+`).
  1775. *
  1776. * @param {string} val The value to be encoded.
  1777. *
  1778. * @returns {string} The encoded value.
  1779. */
  1780. function encode(val) {
  1781. return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+');
  1782. }
  1783. /**
  1784. * Build a URL by appending params to the end
  1785. *
  1786. * @param {string} url The base of the url (e.g., http://www.google.com)
  1787. * @param {object} [params] The params to be appended
  1788. * @param {?(object|Function)} options
  1789. *
  1790. * @returns {string} The formatted url
  1791. */
  1792. function buildURL(url, params, options) {
  1793. if (!params) {
  1794. return url;
  1795. }
  1796. url = url || '';
  1797. const _options = utils$1.isFunction(options) ? {
  1798. serialize: options
  1799. } : options;
  1800. // Read serializer options pollution-safely: own properties and methods on a
  1801. // class/template prototype are honored, but values injected onto a polluted
  1802. // Object.prototype are ignored.
  1803. const _encode = utils$1.getSafeProp(_options, 'encode') || encode;
  1804. const serializeFn = utils$1.getSafeProp(_options, 'serialize');
  1805. let serializedParams;
  1806. if (serializeFn) {
  1807. serializedParams = serializeFn(params, _options);
  1808. } else {
  1809. serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode);
  1810. }
  1811. if (serializedParams) {
  1812. const hashmarkIndex = url.indexOf('#');
  1813. if (hashmarkIndex !== -1) {
  1814. url = url.slice(0, hashmarkIndex);
  1815. }
  1816. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  1817. }
  1818. return url;
  1819. }
  1820. class InterceptorManager {
  1821. constructor() {
  1822. this.handlers = [];
  1823. }
  1824. /**
  1825. * Add a new interceptor to the stack
  1826. *
  1827. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  1828. * @param {Function} rejected The function to handle `reject` for a `Promise`
  1829. * @param {Object} options The options for the interceptor, synchronous and runWhen
  1830. *
  1831. * @return {Number} An ID used to remove interceptor later
  1832. */
  1833. use(fulfilled, rejected, options) {
  1834. this.handlers.push({
  1835. fulfilled,
  1836. rejected,
  1837. synchronous: options ? options.synchronous : false,
  1838. runWhen: options ? options.runWhen : null
  1839. });
  1840. return this.handlers.length - 1;
  1841. }
  1842. /**
  1843. * Remove an interceptor from the stack
  1844. *
  1845. * @param {Number} id The ID that was returned by `use`
  1846. *
  1847. * @returns {void}
  1848. */
  1849. eject(id) {
  1850. if (this.handlers[id]) {
  1851. this.handlers[id] = null;
  1852. }
  1853. }
  1854. /**
  1855. * Clear all interceptors from the stack
  1856. *
  1857. * @returns {void}
  1858. */
  1859. clear() {
  1860. if (this.handlers) {
  1861. this.handlers = [];
  1862. }
  1863. }
  1864. /**
  1865. * Iterate over all the registered interceptors
  1866. *
  1867. * This method is particularly useful for skipping over any
  1868. * interceptors that may have become `null` calling `eject`.
  1869. *
  1870. * @param {Function} fn The function to call for each interceptor
  1871. *
  1872. * @returns {void}
  1873. */
  1874. forEach(fn) {
  1875. utils$1.forEach(this.handlers, function forEachHandler(h) {
  1876. if (h !== null) {
  1877. fn(h);
  1878. }
  1879. });
  1880. }
  1881. }
  1882. var transitionalDefaults = {
  1883. silentJSONParsing: true,
  1884. forcedJSONParsing: true,
  1885. clarifyTimeoutError: false,
  1886. legacyInterceptorReqResOrdering: true,
  1887. advertiseZstdAcceptEncoding: false,
  1888. validateStatusUndefinedResolves: true
  1889. };
  1890. var URLSearchParams = url.URLSearchParams;
  1891. const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
  1892. const DIGIT = '0123456789';
  1893. const ALPHABET = {
  1894. DIGIT,
  1895. ALPHA,
  1896. ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
  1897. };
  1898. const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
  1899. let str = '';
  1900. const {
  1901. length
  1902. } = alphabet;
  1903. const randomValues = new Uint32Array(size);
  1904. crypto.randomFillSync(randomValues);
  1905. for (let i = 0; i < size; i++) {
  1906. str += alphabet[randomValues[i] % length];
  1907. }
  1908. return str;
  1909. };
  1910. var platform$1 = {
  1911. isNode: true,
  1912. classes: {
  1913. URLSearchParams,
  1914. FormData: FormData$1,
  1915. Blob: typeof Blob !== 'undefined' && Blob || null
  1916. },
  1917. ALPHABET,
  1918. generateString,
  1919. protocols: ['http', 'https', 'file', 'data']
  1920. };
  1921. const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
  1922. const _navigator = typeof navigator === 'object' && navigator || undefined;
  1923. /**
  1924. * Determine if we're running in a standard browser environment
  1925. *
  1926. * This allows axios to run in a web worker, and react-native.
  1927. * Both environments support XMLHttpRequest, but not fully standard globals.
  1928. *
  1929. * web workers:
  1930. * typeof window -> undefined
  1931. * typeof document -> undefined
  1932. *
  1933. * react-native:
  1934. * navigator.product -> 'ReactNative'
  1935. * nativescript
  1936. * navigator.product -> 'NativeScript' or 'NS'
  1937. *
  1938. * @returns {boolean}
  1939. */
  1940. const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
  1941. /**
  1942. * Determine if we're running in a standard browser webWorker environment
  1943. *
  1944. * Although the `isStandardBrowserEnv` method indicates that
  1945. * `allows axios to run in a web worker`, the WebWorker will still be
  1946. * filtered out due to its judgment standard
  1947. * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
  1948. * This leads to a problem when axios post `FormData` in webWorker
  1949. */
  1950. const hasStandardBrowserWebWorkerEnv = (() => {
  1951. return typeof WorkerGlobalScope !== 'undefined' &&
  1952. // eslint-disable-next-line no-undef
  1953. self instanceof WorkerGlobalScope && typeof self.importScripts === 'function';
  1954. })();
  1955. const origin = hasBrowserEnv && window.location.href || 'http://localhost';
  1956. var utils = /*#__PURE__*/Object.freeze({
  1957. __proto__: null,
  1958. hasBrowserEnv: hasBrowserEnv,
  1959. hasStandardBrowserEnv: hasStandardBrowserEnv,
  1960. hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
  1961. navigator: _navigator,
  1962. origin: origin
  1963. });
  1964. var platform = {
  1965. ...utils,
  1966. ...platform$1
  1967. };
  1968. function toURLEncodedForm(data, options) {
  1969. return toFormData(data, new platform.classes.URLSearchParams(), {
  1970. visitor: function (value, key, path, helpers) {
  1971. if (platform.isNode && utils$1.isBuffer(value)) {
  1972. this.append(key, value.toString('base64'));
  1973. return false;
  1974. }
  1975. return helpers.defaultVisitor.apply(this, arguments);
  1976. },
  1977. ...options
  1978. });
  1979. }
  1980. const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
  1981. function throwIfDepthExceeded(index) {
  1982. if (index > MAX_DEPTH) {
  1983. throw new AxiosError('FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
  1984. }
  1985. }
  1986. /**
  1987. * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
  1988. *
  1989. * @param {string} name - The name of the property to get.
  1990. *
  1991. * @returns An array of strings.
  1992. */
  1993. function parsePropPath(name) {
  1994. // foo[x][y][z] -> ['foo', 'x', 'y', 'z']
  1995. // foo.x.y.z -> ['foo', 'x', 'y', 'z']
  1996. // A path is split on `.` and on `[...]` groups. A segment — whether written
  1997. // in dot notation or captured inside brackets — may contain any character
  1998. // except `.`, `[` and `]`, so a key like `user-name` or `user name` is kept
  1999. // literal instead of being split (#5402). `.`, `[` and `]` keep their existing
  2000. // meaning, e.g. `foo[bar.baz]` -> ['foo', 'bar', 'baz'] and `[]` is an array push.
  2001. // Excluding `[` from the bracket group also makes the match fail fast at the
  2002. // next `[`, so a malformed name cannot rescan to the end of the string from
  2003. // every unmatched `[` — parsing stays linear in the length of the name.
  2004. const path = [];
  2005. const pattern = /[^.[\]]+|\[([^.[\]]*)]/g;
  2006. let match;
  2007. while ((match = pattern.exec(name)) !== null) {
  2008. throwIfDepthExceeded(path.length);
  2009. path.push(match[0] === '[]' ? '' : match[1] || match[0]);
  2010. }
  2011. return path;
  2012. }
  2013. /**
  2014. * Convert an array to an object.
  2015. *
  2016. * @param {Array<any>} arr - The array to convert to an object.
  2017. *
  2018. * @returns An object with the same keys and values as the array.
  2019. */
  2020. function arrayToObject(arr) {
  2021. const obj = {};
  2022. const keys = Object.keys(arr);
  2023. let i;
  2024. const len = keys.length;
  2025. let key;
  2026. for (i = 0; i < len; i++) {
  2027. key = keys[i];
  2028. obj[key] = arr[key];
  2029. }
  2030. return obj;
  2031. }
  2032. /**
  2033. * It takes a FormData object and returns a JavaScript object
  2034. *
  2035. * @param {string} formData The FormData object to convert to JSON.
  2036. *
  2037. * @returns {Object<string, any> | null} The converted object.
  2038. */
  2039. function formDataToJSON(formData) {
  2040. function buildPath(path, value, target, index) {
  2041. throwIfDepthExceeded(index);
  2042. let name = path[index++];
  2043. if (name === '__proto__') return true;
  2044. const isNumericKey = Number.isFinite(+name);
  2045. const isLast = index >= path.length;
  2046. name = !name && utils$1.isArray(target) ? target.length : name;
  2047. if (isLast) {
  2048. if (utils$1.hasOwnProp(target, name)) {
  2049. target[name] = utils$1.isArray(target[name]) ? target[name].concat(value) : [target[name], value];
  2050. } else {
  2051. target[name] = value;
  2052. }
  2053. return !isNumericKey;
  2054. }
  2055. if (!utils$1.hasOwnProp(target, name) || !utils$1.isObject(target[name])) {
  2056. target[name] = [];
  2057. }
  2058. const result = buildPath(path, value, target[name], index);
  2059. if (result && utils$1.isArray(target[name])) {
  2060. target[name] = arrayToObject(target[name]);
  2061. }
  2062. return !isNumericKey;
  2063. }
  2064. if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
  2065. const obj = {};
  2066. utils$1.forEachEntry(formData, (name, value) => {
  2067. buildPath(parsePropPath(name), value, obj, 0);
  2068. });
  2069. return obj;
  2070. }
  2071. return null;
  2072. }
  2073. const own = (obj, key) => obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : undefined;
  2074. /**
  2075. * It takes a string, tries to parse it, and if it fails, it returns the stringified version
  2076. * of the input
  2077. *
  2078. * @param {any} rawValue - The value to be stringified.
  2079. * @param {Function} parser - A function that parses a string into a JavaScript object.
  2080. * @param {Function} encoder - A function that takes a value and returns a string.
  2081. *
  2082. * @returns {string} A stringified version of the rawValue.
  2083. */
  2084. function stringifySafely(rawValue, parser, encoder) {
  2085. if (utils$1.isString(rawValue)) {
  2086. try {
  2087. (parser || JSON.parse)(rawValue);
  2088. return utils$1.trim(rawValue);
  2089. } catch (e) {
  2090. if (e.name !== 'SyntaxError') {
  2091. throw e;
  2092. }
  2093. }
  2094. }
  2095. return (encoder || JSON.stringify)(rawValue);
  2096. }
  2097. const defaults = {
  2098. transitional: transitionalDefaults,
  2099. adapter: ['xhr', 'http', 'fetch'],
  2100. transformRequest: [function transformRequest(data, headers) {
  2101. const contentType = headers.getContentType() || '';
  2102. const hasJSONContentType = contentType.indexOf('application/json') > -1;
  2103. const isObjectPayload = utils$1.isObject(data);
  2104. if (isObjectPayload && utils$1.isHTMLForm(data)) {
  2105. data = new FormData(data);
  2106. }
  2107. const isFormData = utils$1.isFormData(data);
  2108. if (isFormData) {
  2109. return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
  2110. }
  2111. if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
  2112. return data;
  2113. }
  2114. if (utils$1.isArrayBufferView(data)) {
  2115. return data.buffer;
  2116. }
  2117. if (utils$1.isURLSearchParams(data)) {
  2118. headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
  2119. return data.toString();
  2120. }
  2121. let isFileList;
  2122. if (isObjectPayload) {
  2123. const formSerializer = own(this, 'formSerializer');
  2124. if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
  2125. return toURLEncodedForm(data, formSerializer).toString();
  2126. }
  2127. if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
  2128. const env = own(this, 'env');
  2129. const _FormData = env && env.FormData;
  2130. return toFormData(isFileList ? {
  2131. 'files[]': data
  2132. } : data, _FormData && new _FormData(), formSerializer);
  2133. }
  2134. }
  2135. if (isObjectPayload || hasJSONContentType) {
  2136. headers.setContentType('application/json', false);
  2137. return stringifySafely(data);
  2138. }
  2139. return data;
  2140. }],
  2141. transformResponse: [function transformResponse(data) {
  2142. const transitional = own(this, 'transitional') || defaults.transitional;
  2143. const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
  2144. const responseType = own(this, 'responseType');
  2145. const JSONRequested = responseType === 'json';
  2146. if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
  2147. return data;
  2148. }
  2149. if (data && utils$1.isString(data) && (forcedJSONParsing && !responseType || JSONRequested)) {
  2150. const silentJSONParsing = transitional && transitional.silentJSONParsing;
  2151. const strictJSONParsing = !silentJSONParsing && JSONRequested;
  2152. try {
  2153. return JSON.parse(data, own(this, 'parseReviver'));
  2154. } catch (e) {
  2155. if (strictJSONParsing) {
  2156. if (e.name === 'SyntaxError') {
  2157. throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
  2158. }
  2159. throw e;
  2160. }
  2161. }
  2162. }
  2163. return data;
  2164. }],
  2165. /**
  2166. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  2167. * timeout is not created.
  2168. */
  2169. timeout: 0,
  2170. xsrfCookieName: 'XSRF-TOKEN',
  2171. xsrfHeaderName: 'X-XSRF-TOKEN',
  2172. maxContentLength: -1,
  2173. maxBodyLength: -1,
  2174. env: {
  2175. FormData: platform.classes.FormData,
  2176. Blob: platform.classes.Blob
  2177. },
  2178. validateStatus: function validateStatus(status) {
  2179. return status >= 200 && status < 300;
  2180. },
  2181. headers: {
  2182. common: {
  2183. Accept: 'application/json, text/plain, */*',
  2184. 'Content-Type': undefined
  2185. }
  2186. }
  2187. };
  2188. utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], method => {
  2189. defaults.headers[method] = {};
  2190. });
  2191. /**
  2192. * Transform the data for a request or a response
  2193. *
  2194. * @param {Array|Function} fns A single function or Array of functions
  2195. * @param {?Object} response The response object
  2196. *
  2197. * @returns {*} The resulting transformed data
  2198. */
  2199. function transformData(fns, response) {
  2200. const config = this || defaults;
  2201. const context = response || config;
  2202. const headers = AxiosHeaders.from(context.headers);
  2203. let data = context.data;
  2204. utils$1.forEach(fns, function transform(fn) {
  2205. data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
  2206. });
  2207. headers.normalize();
  2208. return data;
  2209. }
  2210. function isCancel(value) {
  2211. return !!(value && value.__CANCEL__);
  2212. }
  2213. class CanceledError extends AxiosError {
  2214. /**
  2215. * A `CanceledError` is an object that is thrown when an operation is canceled.
  2216. *
  2217. * @param {string=} message The message.
  2218. * @param {Object=} config The config.
  2219. * @param {Object=} request The request.
  2220. *
  2221. * @returns {CanceledError} The created error.
  2222. */
  2223. constructor(message, config, request) {
  2224. super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
  2225. this.name = 'CanceledError';
  2226. this.__CANCEL__ = true;
  2227. }
  2228. }
  2229. /**
  2230. * Resolve or reject a Promise based on response status.
  2231. *
  2232. * @param {Function} resolve A function that resolves the promise.
  2233. * @param {Function} reject A function that rejects the promise.
  2234. * @param {object} response The response.
  2235. *
  2236. * @returns {object} The response.
  2237. */
  2238. function settle(resolve, reject, response) {
  2239. const validateStatus = response.config.validateStatus;
  2240. if (!response.status || !validateStatus || validateStatus(response.status)) {
  2241. resolve(response);
  2242. } else {
  2243. reject(new AxiosError('Request failed with status code ' + response.status, response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE, response.config, response.request, response));
  2244. }
  2245. }
  2246. /**
  2247. * Determines whether the specified URL is absolute
  2248. *
  2249. * @param {string} url The URL to test
  2250. *
  2251. * @returns {boolean} True if the specified URL is absolute, otherwise false
  2252. */
  2253. function isAbsoluteURL(url) {
  2254. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  2255. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  2256. // by any combination of letters, digits, plus, period, or hyphen.
  2257. if (typeof url !== 'string') {
  2258. return false;
  2259. }
  2260. return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
  2261. }
  2262. /**
  2263. * Creates a new URL by combining the specified URLs
  2264. *
  2265. * @param {string} baseURL The base URL
  2266. * @param {string} relativeURL The relative URL
  2267. *
  2268. * @returns {string} The combined URL
  2269. */
  2270. function combineURLs(baseURL, relativeURL) {
  2271. if (!relativeURL) {
  2272. return baseURL;
  2273. }
  2274. let end = baseURL.length;
  2275. while (end > 0 && baseURL.charCodeAt(end - 1) === 47) {
  2276. end--;
  2277. }
  2278. return baseURL.slice(0, end) + '/' + relativeURL.replace(/^\/+/, '');
  2279. }
  2280. const malformedHttpProtocol = /^https?:(?!\/\/)/i;
  2281. const httpProtocolControlCharacters = /[\t\n\r]/g;
  2282. function stripLeadingC0ControlOrSpace(url) {
  2283. let i = 0;
  2284. while (i < url.length && url.charCodeAt(i) <= 0x20) {
  2285. i++;
  2286. }
  2287. return url.slice(i);
  2288. }
  2289. function normalizeURLForProtocolCheck(url) {
  2290. return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, '');
  2291. }
  2292. // Redact the parts of a URL that can carry secrets before it is embedded in an
  2293. // error message. AxiosError.toJSON() serializes `message` verbatim and errors
  2294. // are commonly logged, while the opt-in `config.redact` model only cleans
  2295. // config keys — it cannot reach the message. Redact only the genuinely
  2296. // sensitive substrings — userinfo (credentials), query parameter values and
  2297. // fragment contents — with the same REDACTED marker the config redaction uses,
  2298. // while keeping the scheme, host, path and parameter names so the offending
  2299. // request stays accurately identifiable.
  2300. function redactFragment(fragment) {
  2301. if (!fragment) {
  2302. return fragment;
  2303. }
  2304. return fragment.replace(/(^|&)([^=&]*=)?[^&]+/g, (match, separator, parameterName = '') => {
  2305. return `${separator}${parameterName}${REDACTED}`;
  2306. });
  2307. }
  2308. function redactSensitiveURLParts(url) {
  2309. const redactedURL = url.replace(/^(https?:\/{0,2})[^/?#]*@/i, `$1${REDACTED}@`);
  2310. const fragmentIndex = redactedURL.indexOf('#');
  2311. const urlWithoutFragment = fragmentIndex === -1 ? redactedURL : redactedURL.slice(0, fragmentIndex);
  2312. const redactedURLWithoutFragment = urlWithoutFragment.replace(/([?&][^=&#]*=)[^&#]*/g, `$1${REDACTED}`);
  2313. if (fragmentIndex === -1) {
  2314. return redactedURLWithoutFragment;
  2315. }
  2316. return `${redactedURLWithoutFragment}#${redactFragment(redactedURL.slice(fragmentIndex + 1))}`;
  2317. }
  2318. function assertValidHttpProtocolURL(url, config) {
  2319. if (typeof url === 'string') {
  2320. const normalizedURL = normalizeURLForProtocolCheck(url);
  2321. if (malformedHttpProtocol.test(normalizedURL)) {
  2322. throw new AxiosError(`Invalid URL ${JSON.stringify(redactSensitiveURLParts(normalizedURL))}: missing "//" after protocol`, AxiosError.ERR_INVALID_URL, config);
  2323. }
  2324. }
  2325. }
  2326. /**
  2327. * Creates a new URL by combining the baseURL with the requestedURL,
  2328. * only when the requestedURL is not already an absolute URL.
  2329. * If the requestURL is absolute, this function returns the requestedURL untouched.
  2330. *
  2331. * @param {string} baseURL The base URL
  2332. * @param {string} requestedURL Absolute or relative URL to combine
  2333. *
  2334. * @returns {string} The combined full path
  2335. */
  2336. function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) {
  2337. assertValidHttpProtocolURL(requestedURL, config);
  2338. let isRelativeUrl = !isAbsoluteURL(requestedURL);
  2339. if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
  2340. assertValidHttpProtocolURL(baseURL, config);
  2341. return combineURLs(baseURL, requestedURL);
  2342. }
  2343. return requestedURL;
  2344. }
  2345. var DEFAULT_PORTS$1 = {
  2346. ftp: 21,
  2347. gopher: 70,
  2348. http: 80,
  2349. https: 443,
  2350. ws: 80,
  2351. wss: 443
  2352. };
  2353. function parseUrl(urlString) {
  2354. try {
  2355. return new URL(urlString);
  2356. } catch {
  2357. return null;
  2358. }
  2359. }
  2360. /**
  2361. * @param {string|object|URL} url - The URL as a string or URL instance, or a
  2362. * compatible object (such as the result from legacy url.parse).
  2363. * @return {string} The URL of the proxy that should handle the request to the
  2364. * given URL. If no proxy is set, this will be an empty string.
  2365. */
  2366. function getProxyForUrl(url) {
  2367. var parsedUrl = (typeof url === 'string' ? parseUrl(url) : url) || {};
  2368. var proto = parsedUrl.protocol;
  2369. var hostname = parsedUrl.host;
  2370. var port = parsedUrl.port;
  2371. if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') {
  2372. return ''; // Don't proxy URLs without a valid scheme or host.
  2373. }
  2374. proto = proto.split(':', 1)[0];
  2375. // Stripping ports in this way instead of using parsedUrl.hostname to make
  2376. // sure that the brackets around IPv6 addresses are kept.
  2377. hostname = hostname.replace(/:\d*$/, '');
  2378. port = parseInt(port) || DEFAULT_PORTS$1[proto] || 0;
  2379. if (!shouldProxy(hostname, port)) {
  2380. return ''; // Don't proxy URLs that match NO_PROXY.
  2381. }
  2382. var proxy = getEnv(proto + '_proxy') || getEnv('all_proxy');
  2383. if (proxy && proxy.indexOf('://') === -1) {
  2384. // Missing scheme in proxy, default to the requested URL's scheme.
  2385. proxy = proto + '://' + proxy;
  2386. }
  2387. return proxy;
  2388. }
  2389. /**
  2390. * Determines whether a given URL should be proxied.
  2391. *
  2392. * @param {string} hostname - The host name of the URL.
  2393. * @param {number} port - The effective port of the URL.
  2394. * @returns {boolean} Whether the given URL should be proxied.
  2395. * @private
  2396. */
  2397. function shouldProxy(hostname, port) {
  2398. var NO_PROXY = getEnv('no_proxy').toLowerCase();
  2399. if (!NO_PROXY) {
  2400. return true; // Always proxy if NO_PROXY is not set.
  2401. }
  2402. if (NO_PROXY === '*') {
  2403. return false; // Never proxy if wildcard is set.
  2404. }
  2405. return NO_PROXY.split(/[,\s]/).every(function (proxy) {
  2406. if (!proxy) {
  2407. return true; // Skip zero-length hosts.
  2408. }
  2409. var parsedProxy = proxy.match(/^(.+):(\d+)$/);
  2410. var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
  2411. var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
  2412. if (parsedProxyPort && parsedProxyPort !== port) {
  2413. return true; // Skip if ports don't match.
  2414. }
  2415. if (!/^[.*]/.test(parsedProxyHostname)) {
  2416. // No wildcards, so stop proxying if there is an exact match.
  2417. return hostname !== parsedProxyHostname;
  2418. }
  2419. if (parsedProxyHostname.charAt(0) === '*') {
  2420. // Remove leading wildcard.
  2421. parsedProxyHostname = parsedProxyHostname.slice(1);
  2422. }
  2423. // Stop proxying if the hostname ends with the no_proxy host.
  2424. return !hostname.endsWith(parsedProxyHostname);
  2425. });
  2426. }
  2427. /**
  2428. * Get the value for an environment variable.
  2429. *
  2430. * @param {string} key - The name of the environment variable.
  2431. * @return {string} The value of the environment variable.
  2432. * @private
  2433. */
  2434. function getEnv(key) {
  2435. return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
  2436. }
  2437. const VERSION = "1.19.0";
  2438. function parseProtocol(url) {
  2439. const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
  2440. return match && match[1] || '';
  2441. }
  2442. // RFC 2397: data:[<mediatype>][;base64],<data>
  2443. // mediatype = type/subtype followed by optional ;name=value parameters
  2444. const DATA_URL_PATTERN = /^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;
  2445. /**
  2446. * Parse data uri to a Buffer or Blob
  2447. *
  2448. * @param {String} uri
  2449. * @param {?Boolean} asBlob
  2450. * @param {?Object} options
  2451. * @param {?Function} options.Blob
  2452. *
  2453. * @returns {Buffer|Blob}
  2454. */
  2455. function fromDataURI(uri, asBlob, options) {
  2456. const _Blob = options && options.Blob || platform.classes.Blob;
  2457. const protocol = parseProtocol(uri);
  2458. if (asBlob === undefined && _Blob) {
  2459. asBlob = true;
  2460. }
  2461. if (protocol === 'data') {
  2462. uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
  2463. const match = DATA_URL_PATTERN.exec(uri);
  2464. if (!match) {
  2465. throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
  2466. }
  2467. const type = match[1];
  2468. const params = match[2];
  2469. const encoding = match[3] ? 'base64' : 'utf8';
  2470. const body = match[4];
  2471. // RFC 2397 section 3: default mediatype is text/plain;charset=US-ASCII
  2472. // Bare `data:,` leaves mime undefined; Blob normalises that to "" per spec.
  2473. let mime = '';
  2474. if (type) {
  2475. mime = params ? type + params : type;
  2476. } else if (params) {
  2477. mime = 'text/plain' + params;
  2478. }
  2479. const buffer = encoding === 'base64' ? Buffer.from(body, 'base64') : Buffer.from(decodeURIComponent(body), encoding);
  2480. if (asBlob) {
  2481. if (!_Blob) {
  2482. throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
  2483. }
  2484. return new _Blob([buffer], {
  2485. type: mime
  2486. });
  2487. }
  2488. return buffer;
  2489. }
  2490. throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
  2491. }
  2492. const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
  2493. /**
  2494. * Apply the headers generated by a FormData implementation to the request headers,
  2495. * honoring the `formDataHeaderPolicy` option: with 'content-only', copy only the
  2496. * content-* headers; otherwise merge all of them.
  2497. *
  2498. * @param {AxiosHeaders} headers - the request headers to mutate
  2499. * @param {Object | null | undefined} formHeaders - headers produced by the FormData implementation
  2500. * @param {String} [policy] - the resolved `formDataHeaderPolicy` config value
  2501. *
  2502. * @returns {void}
  2503. */
  2504. function setFormDataHeaders(headers, formHeaders, policy) {
  2505. if (policy !== 'content-only') {
  2506. headers.set(formHeaders);
  2507. return;
  2508. }
  2509. Object.entries(formHeaders || {}).forEach(([key, val]) => {
  2510. if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
  2511. headers.set(key, val);
  2512. }
  2513. });
  2514. }
  2515. const kInternals = Symbol('internals');
  2516. class AxiosTransformStream extends stream.Transform {
  2517. constructor(options) {
  2518. options = utils$1.toFlatObject(options, {
  2519. maxRate: 0,
  2520. chunkSize: 64 * 1024,
  2521. minChunkSize: 100,
  2522. timeWindow: 500,
  2523. ticksRate: 2,
  2524. samplesCount: 15
  2525. }, null, (prop, source) => {
  2526. return !utils$1.isUndefined(source[prop]);
  2527. });
  2528. super({
  2529. readableHighWaterMark: options.chunkSize
  2530. });
  2531. const internals = this[kInternals] = {
  2532. timeWindow: options.timeWindow,
  2533. chunkSize: options.chunkSize,
  2534. maxRate: options.maxRate,
  2535. minChunkSize: options.minChunkSize,
  2536. bytesSeen: 0,
  2537. isCaptured: false,
  2538. notifiedBytesLoaded: 0,
  2539. ts: Date.now(),
  2540. bytes: 0,
  2541. onReadCallback: null
  2542. };
  2543. this.on('newListener', event => {
  2544. if (event === 'progress') {
  2545. if (!internals.isCaptured) {
  2546. internals.isCaptured = true;
  2547. }
  2548. }
  2549. });
  2550. }
  2551. _read(size) {
  2552. const internals = this[kInternals];
  2553. if (internals.onReadCallback) {
  2554. internals.onReadCallback();
  2555. }
  2556. return super._read(size);
  2557. }
  2558. _transform(chunk, encoding, callback) {
  2559. const internals = this[kInternals];
  2560. const maxRate = internals.maxRate;
  2561. const readableHighWaterMark = this.readableHighWaterMark;
  2562. const timeWindow = internals.timeWindow;
  2563. const divider = 1000 / timeWindow;
  2564. const bytesThreshold = maxRate / divider;
  2565. const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
  2566. const pushChunk = (_chunk, _callback) => {
  2567. const bytes = Buffer.byteLength(_chunk);
  2568. internals.bytesSeen += bytes;
  2569. internals.bytes += bytes;
  2570. internals.isCaptured && this.emit('progress', internals.bytesSeen);
  2571. if (this.push(_chunk)) {
  2572. process.nextTick(_callback);
  2573. } else {
  2574. internals.onReadCallback = () => {
  2575. internals.onReadCallback = null;
  2576. process.nextTick(_callback);
  2577. };
  2578. }
  2579. };
  2580. const transformChunk = (_chunk, _callback) => {
  2581. const chunkSize = Buffer.byteLength(_chunk);
  2582. let chunkRemainder = null;
  2583. let maxChunkSize = readableHighWaterMark;
  2584. let bytesLeft;
  2585. let passed = 0;
  2586. if (maxRate) {
  2587. const now = Date.now();
  2588. if (!internals.ts || (passed = now - internals.ts) >= timeWindow) {
  2589. internals.ts = now;
  2590. bytesLeft = bytesThreshold - internals.bytes;
  2591. internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
  2592. passed = 0;
  2593. }
  2594. bytesLeft = bytesThreshold - internals.bytes;
  2595. }
  2596. if (maxRate) {
  2597. if (bytesLeft <= 0) {
  2598. // next time window
  2599. return setTimeout(() => {
  2600. _callback(null, _chunk);
  2601. }, timeWindow - passed);
  2602. }
  2603. if (bytesLeft < maxChunkSize) {
  2604. maxChunkSize = bytesLeft;
  2605. }
  2606. }
  2607. if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) {
  2608. chunkRemainder = _chunk.subarray(maxChunkSize);
  2609. _chunk = _chunk.subarray(0, maxChunkSize);
  2610. }
  2611. pushChunk(_chunk, chunkRemainder ? () => {
  2612. process.nextTick(_callback, null, chunkRemainder);
  2613. } : _callback);
  2614. };
  2615. transformChunk(chunk, function transformNextChunk(err, _chunk) {
  2616. if (err) {
  2617. return callback(err);
  2618. }
  2619. if (_chunk) {
  2620. transformChunk(_chunk, transformNextChunk);
  2621. } else {
  2622. callback(null);
  2623. }
  2624. });
  2625. }
  2626. }
  2627. const {
  2628. asyncIterator
  2629. } = Symbol;
  2630. const readBlob = async function* (blob) {
  2631. if (blob.stream) {
  2632. yield* blob.stream();
  2633. } else if (blob.arrayBuffer) {
  2634. yield await blob.arrayBuffer();
  2635. } else if (blob[asyncIterator]) {
  2636. yield* blob[asyncIterator]();
  2637. } else {
  2638. yield blob;
  2639. }
  2640. };
  2641. const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + '-_';
  2642. const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util.TextEncoder();
  2643. const CRLF = '\r\n';
  2644. const CRLF_BYTES = textEncoder.encode(CRLF);
  2645. const CRLF_BYTES_COUNT = 2;
  2646. class FormDataPart {
  2647. constructor(name, value) {
  2648. const {
  2649. escapeName
  2650. } = this.constructor;
  2651. const isStringValue = utils$1.isString(value);
  2652. let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ''}${CRLF}`;
  2653. if (isStringValue) {
  2654. value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
  2655. } else {
  2656. const safeType = String(value.type || 'application/octet-stream').replace(/[\r\n]/g, '');
  2657. headers += `Content-Type: ${safeType}${CRLF}`;
  2658. }
  2659. this.headers = textEncoder.encode(headers + CRLF);
  2660. this.contentLength = isStringValue ? value.byteLength : value.size;
  2661. this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
  2662. this.name = name;
  2663. this.value = value;
  2664. }
  2665. async *encode() {
  2666. yield this.headers;
  2667. const {
  2668. value
  2669. } = this;
  2670. if (utils$1.isTypedArray(value)) {
  2671. yield value;
  2672. } else {
  2673. yield* readBlob(value);
  2674. }
  2675. yield CRLF_BYTES;
  2676. }
  2677. static escapeName(name) {
  2678. return String(name).replace(/[\r\n"]/g, match => ({
  2679. '\r': '%0D',
  2680. '\n': '%0A',
  2681. '"': '%22'
  2682. })[match]);
  2683. }
  2684. }
  2685. const formDataToStream = (form, headersHandler, options) => {
  2686. const {
  2687. tag = 'form-data-boundary',
  2688. size = 25,
  2689. boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET)
  2690. } = options || {};
  2691. if (!utils$1.isFormData(form)) {
  2692. throw new TypeError('FormData instance required');
  2693. }
  2694. if (boundary.length < 1 || boundary.length > 70) {
  2695. throw new Error('boundary must be 1-70 characters long');
  2696. }
  2697. const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);
  2698. const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF);
  2699. let contentLength = footerBytes.byteLength;
  2700. const parts = Array.from(form.entries()).map(([name, value]) => {
  2701. const part = new FormDataPart(name, value);
  2702. contentLength += part.size;
  2703. return part;
  2704. });
  2705. contentLength += boundaryBytes.byteLength * parts.length;
  2706. contentLength = utils$1.toFiniteNumber(contentLength);
  2707. const computedHeaders = {
  2708. 'Content-Type': `multipart/form-data; boundary=${boundary}`
  2709. };
  2710. if (Number.isFinite(contentLength)) {
  2711. computedHeaders['Content-Length'] = contentLength;
  2712. }
  2713. headersHandler && headersHandler(computedHeaders);
  2714. return stream.Readable.from(async function* () {
  2715. for (const part of parts) {
  2716. yield boundaryBytes;
  2717. yield* part.encode();
  2718. }
  2719. yield footerBytes;
  2720. }());
  2721. };
  2722. class ZlibHeaderTransformStream extends stream.Transform {
  2723. __transform(chunk, encoding, callback) {
  2724. this.push(chunk);
  2725. callback();
  2726. }
  2727. _transform(chunk, encoding, callback) {
  2728. if (chunk.length !== 0) {
  2729. this._transform = this.__transform;
  2730. // Add Default Compression headers if no zlib headers are present
  2731. if (chunk[0] !== 120) {
  2732. // Hex: 78
  2733. const header = Buffer.alloc(2);
  2734. header[0] = 120; // Hex: 78
  2735. header[1] = 156; // Hex: 9C
  2736. this.push(header, encoding);
  2737. }
  2738. }
  2739. this.__transform(chunk, encoding, callback);
  2740. }
  2741. }
  2742. class Http2Sessions {
  2743. constructor() {
  2744. this.sessions = Object.create(null);
  2745. }
  2746. getSession(authority, options) {
  2747. options = Object.assign({
  2748. sessionTimeout: 1000
  2749. }, options);
  2750. let authoritySessions = this.sessions[authority];
  2751. if (authoritySessions) {
  2752. let len = authoritySessions.length;
  2753. for (let i = 0; i < len; i++) {
  2754. const [sessionHandle, sessionOptions] = authoritySessions[i];
  2755. if (!sessionHandle.destroyed && !sessionHandle.closed && util.isDeepStrictEqual(sessionOptions, options)) {
  2756. return sessionHandle;
  2757. }
  2758. }
  2759. }
  2760. const session = http2.connect(authority, options);
  2761. let removed;
  2762. let timer;
  2763. const removeSession = () => {
  2764. if (removed) {
  2765. return;
  2766. }
  2767. removed = true;
  2768. if (timer) {
  2769. clearTimeout(timer);
  2770. timer = null;
  2771. }
  2772. let entries = authoritySessions,
  2773. len = entries.length,
  2774. i = len;
  2775. while (i--) {
  2776. if (entries[i][0] === session) {
  2777. if (len === 1) {
  2778. delete this.sessions[authority];
  2779. } else {
  2780. entries.splice(i, 1);
  2781. }
  2782. if (!session.closed) {
  2783. session.close();
  2784. }
  2785. return;
  2786. }
  2787. }
  2788. };
  2789. const originalRequestFn = session.request;
  2790. const {
  2791. sessionTimeout
  2792. } = options;
  2793. if (sessionTimeout != null) {
  2794. let streamsCount = 0;
  2795. session.request = function () {
  2796. const stream = originalRequestFn.apply(this, arguments);
  2797. streamsCount++;
  2798. if (timer) {
  2799. clearTimeout(timer);
  2800. timer = null;
  2801. }
  2802. stream.once('close', () => {
  2803. if (! --streamsCount) {
  2804. timer = setTimeout(() => {
  2805. timer = null;
  2806. removeSession();
  2807. }, sessionTimeout);
  2808. }
  2809. });
  2810. return stream;
  2811. };
  2812. }
  2813. session.once('close', removeSession);
  2814. let entry = [session, options];
  2815. authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry];
  2816. return session;
  2817. }
  2818. }
  2819. const callbackify = (fn, reducer) => {
  2820. return utils$1.isAsyncFn(fn) ? function (...args) {
  2821. const cb = args.pop();
  2822. fn.apply(this, args).then(value => {
  2823. try {
  2824. reducer ? cb(null, ...reducer(value)) : cb(null, value);
  2825. } catch (err) {
  2826. cb(err);
  2827. }
  2828. }, cb);
  2829. } : fn;
  2830. };
  2831. const LOOPBACK_HOSTNAMES = new Set(['localhost', '0.0.0.0']);
  2832. const isIPv4Loopback = host => {
  2833. const parts = host.split('.');
  2834. if (parts.length !== 4) return false;
  2835. if (parts[0] !== '127') return false;
  2836. return parts.every(p => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255);
  2837. };
  2838. /**
  2839. * Canonicalize an IPv4 address written in shorthand, octal, or hex form into
  2840. * dotted-decimal. IPv6 addresses and non-IP strings are returned unchanged so
  2841. * the existing IPv4-mapped IPv6 unmap path and the isLoopback path can still
  2842. * see them.
  2843. *
  2844. * Shorthand expansion mirrors Node's URL parser: literal parts fill from the
  2845. * left, the final part fills the remaining octets from the right with
  2846. * zero-padding on the left.
  2847. * 127.1 -> 127.0.0.1
  2848. * 127.0.1 -> 127.0.0.1
  2849. * 1.2.3 -> 1.2.0.3
  2850. *
  2851. * Each octet is parsed with an explicit base: 16 for `0x`/`0X` prefix, 8 for
  2852. * zero-prefixed multi-digit all-`0-7` parts, 10 otherwise. Zero-prefixed
  2853. * decimal-looking parts that contain `8` or `9` are rejected to match Node's
  2854. * URL parser, and the comparison layer falls through to non-bypass if either
  2855. * side rejects the form (fail-safe).
  2856. *
  2857. * Returns the input unchanged on any parse failure, out-of-range octet, or
  2858. * unusual shape (1-part, 5+ parts) so the comparison layer fails closed.
  2859. */
  2860. const parseIPv4Octet = text => {
  2861. if (/^0[xX][0-9a-fA-F]+$/.test(text)) {
  2862. const n = parseInt(text.slice(2), 16);
  2863. return Number.isFinite(n) ? n : null;
  2864. }
  2865. if (text.length > 1 && /^0[0-7]+$/.test(text)) {
  2866. const n = parseInt(text, 8);
  2867. return Number.isFinite(n) ? n : null;
  2868. }
  2869. if (text.length > 1 && /^0[0-9]+$/.test(text)) {
  2870. return null;
  2871. }
  2872. if (/^[0-9]+$/.test(text)) {
  2873. const n = parseInt(text, 10);
  2874. return Number.isFinite(n) ? n : null;
  2875. }
  2876. return null;
  2877. };
  2878. const normalizeIPAddress = host => {
  2879. if (typeof host !== 'string' || !host || host.indexOf(':') !== -1) {
  2880. return host;
  2881. }
  2882. let h = host;
  2883. if (h.charAt(0) === '[' && h.charAt(h.length - 1) === ']') {
  2884. h = h.slice(1, -1);
  2885. }
  2886. h = h.replace(/\.+$/, '');
  2887. // Allowed characters for any IPv4 shape: digits, dot, 'x', 'X', hex digits.
  2888. if (!/^[0-9.xXa-fA-F]+$/.test(h)) return host;
  2889. const parts = h.split('.');
  2890. // No part may be empty (e.g. "127..0.1" or "127.0.0."). Trailing dots are
  2891. // already stripped above; this guards against the empty-middle case.
  2892. if (parts.some(p => p === '')) return host;
  2893. if (parts.length === 4) {
  2894. // Full IPv4 form: each part is an octet.
  2895. const octets = parts.map(parseIPv4Octet);
  2896. if (octets.some(n => n === null || n < 0 || n > 255)) return host;
  2897. return octets.join('.');
  2898. }
  2899. if (parts.length > 4) {
  2900. return host;
  2901. }
  2902. // Shorthand: 1..3 parts. Node's URL parser treats a 1-part input as a 32-bit
  2903. // integer split into octets, which has surprising semantics (e.g. "127" ->
  2904. // "0.0.0.127"). Reject 1-part inputs to keep the helper predictable: the
  2905. // fail-safe returns the input unchanged and the comparison layer falls
  2906. // through to non-bypass.
  2907. if (parts.length === 1) return host;
  2908. // 2..3 parts: literal parts fill from the left, tail fills remaining octets
  2909. // from the right with zero-padding.
  2910. const literalOctets = parts.slice(0, -1);
  2911. const tail = parts[parts.length - 1];
  2912. const tailSlots = 4 - literalOctets.length;
  2913. // Tail is parsed as a full IPv4 number (hex/octal/decimal) and packed
  2914. // low-byte-right into the remaining octets, matching Node's URL parser.
  2915. // e.g. 127.65535 (tail 0xFFFF into 3 slots) -> 127.0.255.255;
  2916. // 127.0x00ff (tail 0xFF into 3 slots) -> 127.0.0.255;
  2917. // 127.0.65535 (tail 0xFFFF into 2 slots) -> 127.0.255.255.
  2918. const tailValue = parseIPv4Octet(tail);
  2919. if (tailValue === null) return host;
  2920. const maxTail = (1 << 8 * tailSlots) - 1;
  2921. if (tailValue < 0 || tailValue > maxTail) return host;
  2922. const tailOctets = new Array(tailSlots).fill(0);
  2923. for (let i = tailSlots - 1, v = tailValue; i >= 0; i--, v >>= 8) {
  2924. tailOctets[i] = v & 0xff;
  2925. }
  2926. const literal = literalOctets.map(parseIPv4Octet);
  2927. if (literal.some(n => n === null || n < 0 || n > 255)) return host;
  2928. return [...literal, ...tailOctets].join('.');
  2929. };
  2930. const isIPv6ZeroGroup = group => /^0{1,4}$/.test(group);
  2931. // The unspecified address (IPv4 0.0.0.0 / IPv6 ::) resolves to the local host
  2932. // for outbound connections, so treat it as loopback-equivalent for NO_PROXY
  2933. // matching. 0.0.0.0 is covered by LOOPBACK_HOSTNAMES; this handles compressed
  2934. // and full IPv6 all-zero forms so both families bypass symmetrically.
  2935. const isIPv6Unspecified = host => {
  2936. if (host === '::') return true;
  2937. const compressionIndex = host.indexOf('::');
  2938. if (compressionIndex !== -1) {
  2939. if (compressionIndex !== host.lastIndexOf('::')) return false;
  2940. const left = host.slice(0, compressionIndex);
  2941. const right = host.slice(compressionIndex + 2);
  2942. const leftGroups = left ? left.split(':') : [];
  2943. const rightGroups = right ? right.split(':') : [];
  2944. const explicitGroups = leftGroups.length + rightGroups.length;
  2945. return explicitGroups < 8 && leftGroups.every(isIPv6ZeroGroup) && rightGroups.every(isIPv6ZeroGroup);
  2946. }
  2947. const groups = host.split(':');
  2948. return groups.length === 8 && groups.every(isIPv6ZeroGroup);
  2949. };
  2950. const isIPv6Loopback = host => {
  2951. // Collapse all-zero groups: any form of ::1 / 0:0:...:0:1
  2952. // First, strip any leading "::" by normalising with Set lookup of common forms,
  2953. // then fall back to structural check.
  2954. if (host === '::1') return true;
  2955. // Check IPv4-mapped IPv6 loopback: ::ffff:<v4-loopback> or ::ffff:<hex-v4-loopback>
  2956. // Node's URL parser normalises ::ffff:127.0.0.1 → ::ffff:7f00:1
  2957. const v4MappedDotted = host.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
  2958. if (v4MappedDotted) return isIPv4Loopback(v4MappedDotted[1]);
  2959. const v4MappedHex = host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
  2960. if (v4MappedHex) {
  2961. const high = parseInt(v4MappedHex[1], 16);
  2962. // High 16 bits must start with 127 (0x7f) — i.e. 0x7f00..0x7fff
  2963. return high >= 0x7f00 && high <= 0x7fff;
  2964. }
  2965. // Full-form ::1 variants: any number of zero groups followed by trailing 1
  2966. // e.g. 0:0:0:0:0:0:0:1, 0000:...:0001
  2967. const groups = host.split(':');
  2968. if (groups.length === 8) {
  2969. for (let i = 0; i < 7; i++) {
  2970. if (!/^0+$/.test(groups[i])) return false;
  2971. }
  2972. return /^0*1$/.test(groups[7]);
  2973. }
  2974. return false;
  2975. };
  2976. const isLoopback = host => {
  2977. if (!host) return false;
  2978. if (LOOPBACK_HOSTNAMES.has(host)) return true;
  2979. if (isIPv4Loopback(host)) return true;
  2980. if (isIPv6Unspecified(host)) return true;
  2981. return isIPv6Loopback(host);
  2982. };
  2983. const DEFAULT_PORTS = {
  2984. http: 80,
  2985. https: 443,
  2986. ws: 80,
  2987. wss: 443,
  2988. ftp: 21
  2989. };
  2990. const parseNoProxyEntry = entry => {
  2991. let entryHost = entry;
  2992. let entryPort = 0;
  2993. if (entryHost.charAt(0) === '[') {
  2994. const bracketIndex = entryHost.indexOf(']');
  2995. if (bracketIndex !== -1) {
  2996. const host = entryHost.slice(1, bracketIndex);
  2997. const rest = entryHost.slice(bracketIndex + 1);
  2998. if (rest.charAt(0) === ':' && /^\d+$/.test(rest.slice(1))) {
  2999. entryPort = Number.parseInt(rest.slice(1), 10);
  3000. }
  3001. return [host, entryPort];
  3002. }
  3003. }
  3004. const firstColon = entryHost.indexOf(':');
  3005. const lastColon = entryHost.lastIndexOf(':');
  3006. if (firstColon !== -1 && firstColon === lastColon && /^\d+$/.test(entryHost.slice(lastColon + 1))) {
  3007. entryPort = Number.parseInt(entryHost.slice(lastColon + 1), 10);
  3008. entryHost = entryHost.slice(0, lastColon);
  3009. }
  3010. return [entryHost, entryPort];
  3011. };
  3012. // Convert IPv4-mapped IPv6 (::ffff:0:0/96 prefix) to IPv4 dotted form so both
  3013. // sides of a NO_PROXY comparison see the same canonical address. Without this,
  3014. // `NO_PROXY=192.168.1.5` would not match a request to `http://[::ffff:192.168.1.5]/`
  3015. // (Node's URL parser normalises that to `[::ffff:c0a8:105]`), and vice-versa,
  3016. // allowing the proxy-bypass policy to be circumvented by using the alternate
  3017. // representation. Returns the input unchanged when not IPv4-mapped.
  3018. const IPV4_MAPPED_DOTTED_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i;
  3019. const IPV4_MAPPED_HEX_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;
  3020. const unmapIPv4MappedIPv6 = host => {
  3021. if (typeof host !== 'string' || host.indexOf(':') === -1) return host;
  3022. const dotted = host.match(IPV4_MAPPED_DOTTED_RE);
  3023. if (dotted) return dotted[1];
  3024. const hex = host.match(IPV4_MAPPED_HEX_RE);
  3025. if (hex) {
  3026. const high = parseInt(hex[1], 16);
  3027. const low = parseInt(hex[2], 16);
  3028. return `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;
  3029. }
  3030. return host;
  3031. };
  3032. const normalizeNoProxyHost = hostname => {
  3033. if (!hostname) {
  3034. return hostname;
  3035. }
  3036. if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') {
  3037. hostname = hostname.slice(1, -1);
  3038. }
  3039. const trimmed = hostname.replace(/\.+$/, '');
  3040. // IPv4 shorthand/octal/hex → dotted-decimal; helper is a no-op for inputs
  3041. // containing ':' (IPv6 and IPv4-mapped IPv6) so we fall through to unmap.
  3042. const ipv4 = normalizeIPAddress(trimmed);
  3043. if (ipv4 !== trimmed) {
  3044. return ipv4;
  3045. }
  3046. return unmapIPv4MappedIPv6(trimmed);
  3047. };
  3048. function shouldBypassProxy(location) {
  3049. let parsed;
  3050. try {
  3051. parsed = new URL(location);
  3052. } catch (_err) {
  3053. return false;
  3054. }
  3055. const noProxy = (process.env.no_proxy || process.env.NO_PROXY || '').toLowerCase();
  3056. if (!noProxy) {
  3057. return false;
  3058. }
  3059. if (noProxy === '*') {
  3060. return true;
  3061. }
  3062. const port = Number.parseInt(parsed.port, 10) || DEFAULT_PORTS[parsed.protocol.split(':', 1)[0]] || 0;
  3063. const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase());
  3064. return noProxy.split(/[\s,]+/).some(entry => {
  3065. if (!entry) {
  3066. return false;
  3067. }
  3068. if (entry === '*') {
  3069. return true;
  3070. }
  3071. let [entryHost, entryPort] = parseNoProxyEntry(entry);
  3072. entryHost = normalizeNoProxyHost(entryHost);
  3073. if (!entryHost) {
  3074. return false;
  3075. }
  3076. if (entryPort && entryPort !== port) {
  3077. return false;
  3078. }
  3079. if (entryHost.charAt(0) === '*') {
  3080. entryHost = entryHost.slice(1);
  3081. }
  3082. if (entryHost.charAt(0) === '.') {
  3083. return hostname.endsWith(entryHost);
  3084. }
  3085. return hostname === entryHost || isLoopback(hostname) && isLoopback(entryHost);
  3086. });
  3087. }
  3088. /**
  3089. * Calculate data maxRate
  3090. * @param {Number} [samplesCount= 10]
  3091. * @param {Number} [min= 1000]
  3092. * @returns {Function}
  3093. */
  3094. function speedometer(samplesCount, min) {
  3095. samplesCount = samplesCount || 10;
  3096. const bytes = new Array(samplesCount);
  3097. const timestamps = new Array(samplesCount);
  3098. let head = 0;
  3099. let tail = 0;
  3100. let firstSampleTS;
  3101. min = min !== undefined ? min : 1000;
  3102. return function push(chunkLength) {
  3103. const now = Date.now();
  3104. const startedAt = timestamps[tail];
  3105. if (!firstSampleTS) {
  3106. firstSampleTS = now;
  3107. }
  3108. bytes[head] = chunkLength;
  3109. timestamps[head] = now;
  3110. let i = tail;
  3111. let bytesCount = 0;
  3112. while (i !== head) {
  3113. bytesCount += bytes[i++];
  3114. i = i % samplesCount;
  3115. }
  3116. head = (head + 1) % samplesCount;
  3117. if (head === tail) {
  3118. tail = (tail + 1) % samplesCount;
  3119. }
  3120. if (now - firstSampleTS < min) {
  3121. return;
  3122. }
  3123. const passed = startedAt && now - startedAt;
  3124. return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
  3125. };
  3126. }
  3127. /**
  3128. * Throttle decorator
  3129. * @param {Function} fn
  3130. * @param {Number} freq
  3131. * @return {Function}
  3132. */
  3133. function throttle(fn, freq) {
  3134. let timestamp = 0;
  3135. let threshold = 1000 / freq;
  3136. let lastArgs;
  3137. let timer;
  3138. const invoke = (args, now = Date.now()) => {
  3139. timestamp = now;
  3140. lastArgs = null;
  3141. if (timer) {
  3142. clearTimeout(timer);
  3143. timer = null;
  3144. }
  3145. fn(...args);
  3146. };
  3147. const throttled = (...args) => {
  3148. const now = Date.now();
  3149. const passed = now - timestamp;
  3150. if (passed >= threshold) {
  3151. invoke(args, now);
  3152. } else {
  3153. lastArgs = args;
  3154. if (!timer) {
  3155. timer = setTimeout(() => {
  3156. timer = null;
  3157. invoke(lastArgs);
  3158. }, threshold - passed);
  3159. }
  3160. }
  3161. };
  3162. const flush = () => lastArgs && invoke(lastArgs);
  3163. return [throttled, flush];
  3164. }
  3165. const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
  3166. let bytesNotified = 0;
  3167. const _speedometer = speedometer(50, 250);
  3168. return throttle(e => {
  3169. if (!e || typeof e.loaded !== 'number') {
  3170. return;
  3171. }
  3172. const rawLoaded = e.loaded;
  3173. const total = e.lengthComputable ? e.total : undefined;
  3174. const loaded = Math.max(0, total != null ? Math.min(rawLoaded, total) : rawLoaded);
  3175. const progressBytes = Math.max(0, loaded - bytesNotified);
  3176. const rate = _speedometer(progressBytes);
  3177. bytesNotified = Math.max(bytesNotified, loaded);
  3178. const data = {
  3179. loaded,
  3180. total,
  3181. progress: total ? loaded / total : undefined,
  3182. bytes: progressBytes,
  3183. rate: rate ? rate : undefined,
  3184. estimated: rate && total ? (total - loaded) / rate : undefined,
  3185. event: e,
  3186. lengthComputable: total != null,
  3187. [isDownloadStream ? 'download' : 'upload']: true
  3188. };
  3189. listener(data);
  3190. }, freq);
  3191. };
  3192. const progressEventDecorator = (total, throttled) => {
  3193. const lengthComputable = total != null;
  3194. return [loaded => throttled[0]({
  3195. lengthComputable,
  3196. total,
  3197. loaded
  3198. }), throttled[1]];
  3199. };
  3200. const asyncDecorator = (fn, scheduler = utils$1.asap) => (...args) => scheduler(() => fn(...args));
  3201. /**
  3202. * Estimate data: URL byte lengths *without* allocating large buffers.
  3203. * - Fetch percent-decodes a base64 body before decoding it.
  3204. * - Node's Buffer.from(body, 'base64') sizes its backing allocation from the
  3205. * raw body, including ignored characters and content after padding.
  3206. * - Non-base64 data is percent-decoded and then encoded as UTF-8.
  3207. */
  3208. const isHexDigit = charCode => charCode >= 48 && charCode <= 57 || charCode >= 65 && charCode <= 70 || charCode >= 97 && charCode <= 102;
  3209. const isPercentEncodedByte = (str, i, len) => i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));
  3210. const hexValue = charCode => charCode <= 57 ? charCode - 48 : (charCode & 0xdf) - 55;
  3211. const isBase64Char = charCode => charCode >= 65 && charCode <= 90 ||
  3212. // A-Z
  3213. charCode >= 97 && charCode <= 122 ||
  3214. // a-z
  3215. charCode >= 48 && charCode <= 57 ||
  3216. // 0-9
  3217. charCode === 43 ||
  3218. // +
  3219. charCode === 47 ||
  3220. // /
  3221. charCode === 45 ||
  3222. // - (base64url)
  3223. charCode === 95; // _ (base64url)
  3224. const isBase64Whitespace = charCode => charCode === 9 || charCode === 10 || charCode === 12 || charCode === 13 || charCode === 32;
  3225. const base64Bytes = significant => {
  3226. const groups = Math.floor(significant / 4);
  3227. const remainder = significant % 4;
  3228. return groups * 3 + (remainder === 2 ? 1 : remainder === 3 ? 2 : 0);
  3229. };
  3230. // Buffer.byteLength(body, 'base64') uses the raw string length as an allocation
  3231. // upper bound even when Buffer.from later ignores characters or stops at '='.
  3232. const estimateBase64BufferAllocation = body => {
  3233. const len = body.length;
  3234. let padding = 0;
  3235. if (len > 0 && body.charCodeAt(len - 1) === 61 /* '=' */) {
  3236. padding++;
  3237. if (len > 1 && body.charCodeAt(len - 2) === 61 /* '=' */) {
  3238. padding++;
  3239. }
  3240. }
  3241. return Math.floor((len - padding) * 3 / 4);
  3242. };
  3243. const estimatePercentDecodedBase64Bytes = body => {
  3244. const len = body.length;
  3245. let significant = 0;
  3246. let padding = 0;
  3247. let invalid = false;
  3248. for (let i = 0; i < len; i++) {
  3249. let code = body.charCodeAt(i);
  3250. if (code === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
  3251. code = hexValue(body.charCodeAt(i + 1)) * 16 + hexValue(body.charCodeAt(i + 2));
  3252. i += 2;
  3253. }
  3254. if (isBase64Whitespace(code)) {
  3255. continue;
  3256. }
  3257. if (code === 61 /* '=' */) {
  3258. padding++;
  3259. continue;
  3260. }
  3261. if (!isBase64Char(code) || padding > 0) {
  3262. invalid = true;
  3263. continue;
  3264. }
  3265. significant++;
  3266. }
  3267. // Fetch rejects malformed forgiving-base64 input. Returning the raw-size
  3268. // allocation bound keeps that invalid input from becoming a pre-check bypass.
  3269. if (invalid || padding > 2 || padding > 0 && (significant + padding) % 4 !== 0 || significant % 4 === 1) {
  3270. return estimateBase64BufferAllocation(body);
  3271. }
  3272. return base64Bytes(significant);
  3273. };
  3274. const estimateDataURLBytes = (url, estimateBase64) => {
  3275. if (!url || typeof url !== 'string') return 0;
  3276. if (!url.startsWith('data:')) return 0;
  3277. const comma = url.indexOf(',');
  3278. if (comma < 0) return 0;
  3279. const meta = url.slice(5, comma);
  3280. const body = url.slice(comma + 1);
  3281. const isBase64 = /;base64/i.test(meta);
  3282. if (isBase64) {
  3283. return estimateBase64(body);
  3284. }
  3285. // Compute UTF-8 byte length directly from UTF-16 code units without allocating
  3286. // a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
  3287. // Valid %XX triplets count as one decoded byte; this matches the bytes that
  3288. // decodeURIComponent(body) would produce before Buffer re-encodes the string.
  3289. let bytes = 0;
  3290. for (let i = 0, len = body.length; i < len; i++) {
  3291. const c = body.charCodeAt(i);
  3292. if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
  3293. bytes += 1;
  3294. i += 2;
  3295. } else if (c < 0x80) {
  3296. bytes += 1;
  3297. } else if (c < 0x800) {
  3298. bytes += 2;
  3299. } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
  3300. const next = body.charCodeAt(i + 1);
  3301. if (next >= 0xdc00 && next <= 0xdfff) {
  3302. bytes += 4;
  3303. i++;
  3304. } else {
  3305. bytes += 3;
  3306. }
  3307. } else {
  3308. bytes += 3;
  3309. }
  3310. }
  3311. return bytes;
  3312. };
  3313. /**
  3314. * Estimate the percent-decoded payload size used by Fetch data: URLs.
  3315. *
  3316. * @param {string} url
  3317. * @returns {number}
  3318. */
  3319. function estimateDataURLDecodedBytes(url) {
  3320. // Fetch removes URL fragments before processing a data: URL.
  3321. const fragmentIndex = typeof url === 'string' ? url.indexOf('#') : -1;
  3322. return estimateDataURLBytes(fragmentIndex === -1 ? url : url.slice(0, fragmentIndex), estimatePercentDecodedBase64Bytes);
  3323. }
  3324. /**
  3325. * Estimate the Buffer backing allocation used by Node's raw base64 decoder.
  3326. *
  3327. * @param {string} url
  3328. * @returns {number}
  3329. */
  3330. function estimateDataURLBufferAllocation(url) {
  3331. return estimateDataURLBytes(url, estimateBase64BufferAllocation);
  3332. }
  3333. const zlibOptions = {
  3334. flush: zlib.constants.Z_SYNC_FLUSH,
  3335. finishFlush: zlib.constants.Z_SYNC_FLUSH
  3336. };
  3337. const brotliOptions = {
  3338. flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  3339. finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
  3340. };
  3341. const zstdOptions = {
  3342. flush: zlib.constants.ZSTD_e_flush,
  3343. finishFlush: zlib.constants.ZSTD_e_flush
  3344. };
  3345. const isBrotliSupported = utils$1.isFunction(zlib.createBrotliDecompress);
  3346. const isZstdSupported = utils$1.isFunction(zlib.createZstdDecompress);
  3347. const ACCEPT_ENCODING = 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : '');
  3348. const ACCEPT_ENCODING_WITH_ZSTD = ACCEPT_ENCODING + (isZstdSupported ? ', zstd' : '');
  3349. const scheduleProgress = typeof process !== 'undefined' && process.nextTick ? process.nextTick.bind(process) : utils$1.asap;
  3350. const {
  3351. http: httpFollow,
  3352. https: httpsFollow
  3353. } = followRedirects;
  3354. const isHttps = /https:?/;
  3355. // Symbols used to bind a single 'error' listener to a pooled socket and track
  3356. // the request currently owning that socket across keep-alive reuse (issue #10780).
  3357. const kAxiosSocketListener = Symbol('axios.http.socketListener');
  3358. const kAxiosCurrentReq = Symbol('axios.http.currentReq');
  3359. // Tags HttpsProxyAgent instances installed by setProxy() so the redirect path
  3360. // can strip them without clobbering a user-supplied agent that happens to be
  3361. // an HttpsProxyAgent.
  3362. const kAxiosInstalledTunnel = Symbol('axios.http.installedTunnel');
  3363. // Cache of CONNECT-tunneling agents keyed by proxy config so repeat requests
  3364. // through the same proxy reuse a single agent (and its socket pool). The
  3365. // keyspace is bounded by the set of distinct proxy configs the process uses,
  3366. // so unbounded growth is not a concern in practice.
  3367. const tunnelingAgentCache = new Map();
  3368. const tunnelingAgentCacheUser = new WeakMap();
  3369. // Minimum minor versions where Node's HTTP Agent supports native proxyEnv
  3370. // handling. Checking the selected agent below also covers startup modes such
  3371. // as NODE_OPTIONS=--use-env-proxy and --no-use-env-proxy precedence.
  3372. const NODE_NATIVE_ENV_PROXY_SUPPORT = {
  3373. 22: 21,
  3374. 24: 5
  3375. };
  3376. function isNodeNativeEnvProxySupported(nodeVersion = process.versions && process.versions.node) {
  3377. if (!nodeVersion) {
  3378. return false;
  3379. }
  3380. const [major, minor] = nodeVersion.split('.').map(part => Number(part));
  3381. if (!Number.isInteger(major) || !Number.isInteger(minor)) {
  3382. return false;
  3383. }
  3384. if (major > 24) {
  3385. return true;
  3386. }
  3387. return NODE_NATIVE_ENV_PROXY_SUPPORT[major] != null && minor >= NODE_NATIVE_ENV_PROXY_SUPPORT[major];
  3388. }
  3389. function isNodeEnvProxyEnabled(agent, nodeVersion = process.versions && process.versions.node) {
  3390. if (!isNodeNativeEnvProxySupported(nodeVersion)) {
  3391. return false;
  3392. }
  3393. const agentOptions = agent && agent.options;
  3394. return Boolean(agentOptions && utils$1.hasOwnProp(agentOptions, 'proxyEnv') && agentOptions.proxyEnv != null);
  3395. }
  3396. function getProxyEnvAgent(options, configHttpAgent, configHttpsAgent) {
  3397. return isHttps.test(options.protocol) ? configHttpsAgent || https.globalAgent : configHttpAgent || http.globalAgent;
  3398. }
  3399. function getTunnelingAgent(agentOptions, userHttpsAgent) {
  3400. const key = agentOptions.protocol + '//' + agentOptions.hostname + ':' + (agentOptions.port || '') + '#' + (agentOptions.auth || '');
  3401. const cache = userHttpsAgent ? tunnelingAgentCacheUser.get(userHttpsAgent) || tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent) : tunnelingAgentCache;
  3402. let agent = cache.get(key);
  3403. if (agent) return agent;
  3404. // Forward the user's TLS options (custom CA, rejectUnauthorized, client cert,
  3405. // etc.) into the tunneling agent so they apply to the origin TLS upgrade
  3406. // performed after CONNECT. Our proxy fields take precedence on conflict.
  3407. const merged = userHttpsAgent && userHttpsAgent.options ? {
  3408. ...userHttpsAgent.options,
  3409. ...agentOptions
  3410. } : agentOptions;
  3411. agent = new HttpsProxyAgent(merged);
  3412. if (userHttpsAgent && userHttpsAgent.options) {
  3413. const originTLSOptions = {
  3414. ...userHttpsAgent.options
  3415. };
  3416. const callback = agent.callback;
  3417. agent.callback = function axiosTunnelingAgentCallback(req, opts) {
  3418. // HttpsProxyAgent v5 reads callback opts for the post-CONNECT origin TLS upgrade.
  3419. return callback.call(this, req, {
  3420. ...originTLSOptions,
  3421. ...opts
  3422. });
  3423. };
  3424. }
  3425. agent[kAxiosInstalledTunnel] = true;
  3426. cache.set(key, agent);
  3427. return agent;
  3428. }
  3429. const supportedProtocols = platform.protocols.map(protocol => {
  3430. return protocol + ':';
  3431. });
  3432. // Node's WHATWG URL parser returns `username` and `password` percent-encoded.
  3433. // Decode before composing the `auth` option so credentials such as
  3434. // `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
  3435. // original value for malformed input so a bad encoding never throws.
  3436. const decodeURIComponentSafe$1 = value => {
  3437. if (!utils$1.isString(value)) {
  3438. return value;
  3439. }
  3440. try {
  3441. return decodeURIComponent(value);
  3442. } catch (error) {
  3443. return value;
  3444. }
  3445. };
  3446. const flushOnFinish = (stream, [throttled, flush]) => {
  3447. stream.on('end', flush).on('error', flush);
  3448. return throttled;
  3449. };
  3450. const http2Sessions = new Http2Sessions();
  3451. /**
  3452. * If the proxy, auth, sensitive header, or config beforeRedirects functions are defined,
  3453. * call them with the options object.
  3454. *
  3455. * @param {Object<string, any>} options - The options object that was passed to the request.
  3456. *
  3457. * @returns {Object<string, any>}
  3458. */
  3459. function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
  3460. if (options.beforeRedirects.proxy) {
  3461. options.beforeRedirects.proxy(options);
  3462. }
  3463. if (options.beforeRedirects.auth) {
  3464. options.beforeRedirects.auth(options);
  3465. }
  3466. if (options.beforeRedirects.sensitiveHeaders) {
  3467. options.beforeRedirects.sensitiveHeaders(options, requestDetails);
  3468. }
  3469. if (options.beforeRedirects.config) {
  3470. options.beforeRedirects.config(options, responseDetails, requestDetails);
  3471. }
  3472. }
  3473. function stripMatchingHeaders(headers, sensitiveSet) {
  3474. if (!headers) {
  3475. return;
  3476. }
  3477. Object.keys(headers).forEach(header => {
  3478. if (sensitiveSet.has(header.toLowerCase())) {
  3479. delete headers[header];
  3480. }
  3481. });
  3482. }
  3483. function isSameOriginRedirect(redirectOptions, requestDetails) {
  3484. if (!requestDetails) {
  3485. return false;
  3486. }
  3487. try {
  3488. return new URL(requestDetails.url).origin === new URL(redirectOptions.href).origin;
  3489. } catch (e) {
  3490. // If origin comparison fails, treat the redirect as unsafe.
  3491. return false;
  3492. }
  3493. }
  3494. /**
  3495. * If the proxy or config afterRedirects functions are defined, call them with the options
  3496. *
  3497. * @param {http.ClientRequestArgs} options
  3498. * @param {AxiosProxyConfig} configProxy configuration from Axios options object
  3499. * @param {string} location
  3500. *
  3501. * @returns {http.ClientRequestArgs}
  3502. */
  3503. function setProxy(options, configProxy, location, isRedirect, configHttpsAgent, configHttpAgent) {
  3504. let proxy = configProxy;
  3505. const proxyEnvAgent = getProxyEnvAgent(options, configHttpAgent, configHttpsAgent);
  3506. if (!proxy && proxy !== false && !isNodeEnvProxyEnabled(proxyEnvAgent)) {
  3507. const proxyUrl = getProxyForUrl(location);
  3508. if (proxyUrl) {
  3509. if (!shouldBypassProxy(location)) {
  3510. proxy = new URL(proxyUrl);
  3511. }
  3512. }
  3513. }
  3514. // On redirect re-invocation, strip any stale Proxy-Authorization header carried
  3515. // over from the prior request (e.g. new target no longer uses a proxy, or uses
  3516. // a different proxy). Skip on the initial request so user-supplied headers are
  3517. // preserved. Header names are case-insensitive, so remove every case variant.
  3518. if (isRedirect && options.headers) {
  3519. for (const name of Object.keys(options.headers)) {
  3520. if (name.toLowerCase() === 'proxy-authorization') {
  3521. delete options.headers[name];
  3522. }
  3523. }
  3524. }
  3525. // Strip any tunneling agent we installed for the previous hop so a redirect
  3526. // that drops the proxy or crosses an HTTPS↔HTTP boundary doesn't reuse a
  3527. // stale one. Match on our Symbol marker so a user-supplied HttpsProxyAgent
  3528. // (which won't carry the marker) is left alone.
  3529. if (isRedirect && options.agent && options.agent[kAxiosInstalledTunnel]) {
  3530. options.agent = undefined;
  3531. }
  3532. if (proxy) {
  3533. // Read proxy fields without traversing the prototype chain. URL instances expose
  3534. // username/password/hostname/host/port/protocol via getters on URL.prototype (so
  3535. // direct reads are shielded), but plain object proxies — and the `auth` field
  3536. // (which URL does not expose) — must be guarded so a polluted Object.prototype
  3537. // (e.g. Object.prototype.auth = { username, password }) cannot inject
  3538. // attacker-controlled credentials into the Proxy-Authorization header or
  3539. // redirect proxying to an attacker-controlled host.
  3540. const isProxyURL = proxy instanceof URL;
  3541. const readProxyField = key => isProxyURL || utils$1.hasOwnProp(proxy, key) ? proxy[key] : undefined;
  3542. const proxyUsername = readProxyField('username');
  3543. const proxyPassword = readProxyField('password');
  3544. let proxyAuth = utils$1.hasOwnProp(proxy, 'auth') ? proxy.auth : undefined;
  3545. // Basic proxy authorization
  3546. if (proxyUsername) {
  3547. proxyAuth = (proxyUsername || '') + ':' + (proxyPassword || '');
  3548. }
  3549. if (proxyAuth) {
  3550. // Support proxy auth object form. Read sub-fields via own-prop checks so a
  3551. // plain object inheriting from polluted Object.prototype cannot leak creds.
  3552. const authIsObject = typeof proxyAuth === 'object';
  3553. const authUsername = authIsObject && utils$1.hasOwnProp(proxyAuth, 'username') ? proxyAuth.username : undefined;
  3554. const authPassword = authIsObject && utils$1.hasOwnProp(proxyAuth, 'password') ? proxyAuth.password : undefined;
  3555. const validProxyAuth = Boolean(authUsername || authPassword);
  3556. if (validProxyAuth) {
  3557. proxyAuth = (authUsername || '') + ':' + (authPassword || '');
  3558. } else if (authIsObject) {
  3559. throw new AxiosError('Invalid proxy authorization', AxiosError.ERR_BAD_OPTION, {
  3560. proxy
  3561. });
  3562. }
  3563. }
  3564. const targetIsHttps = isHttps.test(options.protocol);
  3565. if (targetIsHttps) {
  3566. // CONNECT-tunneling path for HTTPS targets. Preserves end-to-end TLS to
  3567. // the origin so the proxy cannot inspect the URL, headers, or body — the
  3568. // behavior already promised by THREATMODEL.md (T-R9). HttpsProxyAgent
  3569. // sends Proxy-Authorization on the CONNECT request only, never on the
  3570. // wrapped TLS request, which is why we don't stamp it onto
  3571. // options.headers here. If the user already supplied an HttpsProxyAgent,
  3572. // they own tunneling end-to-end and we leave them alone; otherwise we
  3573. // install our own tunneling agent and forward their TLS options (if any)
  3574. // so a custom httpsAgent for cert pinning / rejectUnauthorized still
  3575. // applies to the origin TLS upgrade.
  3576. if (!(configHttpsAgent instanceof HttpsProxyAgent)) {
  3577. const proxyHost = readProxyField('hostname') || readProxyField('host');
  3578. const proxyPort = readProxyField('port');
  3579. const rawProxyProtocol = readProxyField('protocol');
  3580. const normalizedProtocol = rawProxyProtocol ? rawProxyProtocol.includes(':') ? rawProxyProtocol : `${rawProxyProtocol}:` : 'http:';
  3581. // Bracket IPv6 literals for URL parsing; URL.hostname strips the
  3582. // brackets again on read so the agent receives the raw form.
  3583. const proxyHostForURL = proxyHost && proxyHost.includes(':') && !proxyHost.startsWith('[') ? `[${proxyHost}]` : proxyHost;
  3584. const proxyURL = new URL(`${normalizedProtocol}//${proxyHostForURL}${proxyPort ? ':' + proxyPort : ''}`);
  3585. const agentOptions = {
  3586. protocol: proxyURL.protocol,
  3587. hostname: proxyURL.hostname.replace(/^\[|\]$/g, ''),
  3588. port: proxyURL.port,
  3589. auth: proxyAuth && typeof proxyAuth === 'string' ? proxyAuth : undefined
  3590. };
  3591. if (proxyURL.protocol === 'https:') {
  3592. agentOptions.ALPNProtocols = ['http/1.1'];
  3593. }
  3594. const tunnelingAgent = getTunnelingAgent(agentOptions, configHttpsAgent);
  3595. // Set both: `options.agent` is consumed by the native https.request path
  3596. // (maxRedirects === 0); `options.agents.https` is consumed by
  3597. // follow-redirects, which ignores `options.agent` when `options.agents`
  3598. // is present.
  3599. options.agent = tunnelingAgent;
  3600. if (options.agents) {
  3601. options.agents.https = tunnelingAgent;
  3602. }
  3603. }
  3604. } else {
  3605. // Forward-proxy mode for plaintext HTTP targets. The request line carries
  3606. // the absolute URL and the proxy sees everything — acceptable for plain
  3607. // HTTP since the wire was already plaintext.
  3608. if (proxyAuth) {
  3609. const base64 = Buffer.from(proxyAuth, 'utf8').toString('base64');
  3610. options.headers['Proxy-Authorization'] = 'Basic ' + base64;
  3611. }
  3612. // Preserve a user-supplied Host header (case-insensitive) so callers can override
  3613. // the value forwarded to the proxy; otherwise default to the request URL's host.
  3614. let hasUserHostHeader = false;
  3615. for (const name of Object.keys(options.headers)) {
  3616. if (name.toLowerCase() === 'host') {
  3617. hasUserHostHeader = true;
  3618. break;
  3619. }
  3620. }
  3621. if (!hasUserHostHeader) {
  3622. options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
  3623. }
  3624. const proxyHost = readProxyField('hostname') || readProxyField('host');
  3625. options.hostname = proxyHost;
  3626. // Replace 'host' since options is not a URL object
  3627. options.host = proxyHost;
  3628. options.port = readProxyField('port');
  3629. options.path = location;
  3630. const proxyProtocol = readProxyField('protocol');
  3631. if (proxyProtocol) {
  3632. options.protocol = proxyProtocol.includes(':') ? proxyProtocol : `${proxyProtocol}:`;
  3633. }
  3634. }
  3635. }
  3636. options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
  3637. // Configure proxy for redirected request, passing the original config proxy to apply
  3638. // the exact same logic as if the redirected request was performed by axios directly.
  3639. setProxy(redirectOptions, configProxy, redirectOptions.href, true, configHttpsAgent, configHttpAgent);
  3640. };
  3641. }
  3642. const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process';
  3643. // temporary hotfix
  3644. const wrapAsync = asyncExecutor => {
  3645. return new Promise((resolve, reject) => {
  3646. let onDone;
  3647. let isDone;
  3648. const done = (value, isRejected) => {
  3649. if (isDone) return;
  3650. isDone = true;
  3651. onDone && onDone(value, isRejected);
  3652. };
  3653. const _resolve = value => {
  3654. done(value);
  3655. resolve(value);
  3656. };
  3657. const _reject = reason => {
  3658. done(reason, true);
  3659. reject(reason);
  3660. };
  3661. asyncExecutor(_resolve, _reject, onDoneHandler => onDone = onDoneHandler).catch(_reject);
  3662. });
  3663. };
  3664. const resolveFamily = ({
  3665. address,
  3666. family
  3667. }) => {
  3668. if (!utils$1.isString(address)) {
  3669. throw TypeError('address must be a string');
  3670. }
  3671. return {
  3672. address,
  3673. family: family || (address.indexOf('.') < 0 ? 6 : 4)
  3674. };
  3675. };
  3676. const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {
  3677. address,
  3678. family
  3679. });
  3680. const http2Transport = {
  3681. request(options, cb) {
  3682. const authority = options.protocol + '//' + options.hostname + ':' + (options.port || (options.protocol === 'https:' ? 443 : 80));
  3683. const {
  3684. http2Options,
  3685. headers
  3686. } = options;
  3687. const session = http2Sessions.getSession(authority, http2Options);
  3688. const {
  3689. HTTP2_HEADER_SCHEME,
  3690. HTTP2_HEADER_METHOD,
  3691. HTTP2_HEADER_PATH,
  3692. HTTP2_HEADER_STATUS
  3693. } = http2.constants;
  3694. const http2Headers = {
  3695. [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''),
  3696. [HTTP2_HEADER_METHOD]: options.method,
  3697. [HTTP2_HEADER_PATH]: options.path
  3698. };
  3699. utils$1.forEach(headers, (header, name) => {
  3700. name.charAt(0) !== ':' && (http2Headers[name] = header);
  3701. });
  3702. const req = session.request(http2Headers);
  3703. req.once('response', responseHeaders => {
  3704. const response = req; //duplex
  3705. responseHeaders = Object.assign({}, responseHeaders);
  3706. const status = responseHeaders[HTTP2_HEADER_STATUS];
  3707. delete responseHeaders[HTTP2_HEADER_STATUS];
  3708. response.headers = responseHeaders;
  3709. response.statusCode = +status;
  3710. cb(response);
  3711. });
  3712. return req;
  3713. }
  3714. };
  3715. /*eslint consistent-return:0*/
  3716. var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
  3717. return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
  3718. // Read config pollution-safely: own properties and members inherited from
  3719. // a non-Object.prototype source (e.g. an Object.create(defaults) template)
  3720. // are honored, but values injected onto a polluted Object.prototype are
  3721. // ignored. All behavior-affecting reads in this adapter go through own()
  3722. // so the protection boundary stays consistent.
  3723. const own = key => utils$1.getSafeProp(config, key);
  3724. const transitional = own('transitional') || transitionalDefaults;
  3725. let data = own('data');
  3726. let lookup = own('lookup');
  3727. let family = own('family');
  3728. let httpVersion = own('httpVersion');
  3729. if (httpVersion === undefined) httpVersion = 1;
  3730. let http2Options = own('http2Options');
  3731. const httpAgent = own('httpAgent');
  3732. const httpsAgent = own('httpsAgent');
  3733. const configProxy = own('proxy');
  3734. const responseType = own('responseType');
  3735. const responseEncoding = own('responseEncoding');
  3736. const socketPath = own('socketPath');
  3737. const method = own('method').toUpperCase();
  3738. const maxRedirects = own('maxRedirects');
  3739. const maxBodyLength = own('maxBodyLength');
  3740. const maxContentLength = own('maxContentLength');
  3741. const decompress = own('decompress');
  3742. let isDone;
  3743. let rejected = false;
  3744. let req;
  3745. let connectPhaseTimer;
  3746. httpVersion = +httpVersion;
  3747. if (Number.isNaN(httpVersion)) {
  3748. throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);
  3749. }
  3750. if (httpVersion !== 1 && httpVersion !== 2) {
  3751. throw TypeError(`Unsupported protocol version '${httpVersion}'`);
  3752. }
  3753. const isHttp2 = httpVersion === 2;
  3754. if (lookup) {
  3755. const _lookup = callbackify(lookup, value => utils$1.isArray(value) ? value : [value]);
  3756. // hotfix to support opt.all option which is required for node 20.x
  3757. lookup = (hostname, opt, cb) => {
  3758. _lookup(hostname, opt, (err, arg0, arg1) => {
  3759. if (err) {
  3760. return cb(err);
  3761. }
  3762. const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
  3763. opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
  3764. });
  3765. };
  3766. }
  3767. const abortEmitter = new events.EventEmitter();
  3768. function abort(reason) {
  3769. try {
  3770. abortEmitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
  3771. } catch (err) {
  3772. // ignore emit errors
  3773. }
  3774. }
  3775. function clearConnectPhaseTimer() {
  3776. if (connectPhaseTimer) {
  3777. clearTimeout(connectPhaseTimer);
  3778. connectPhaseTimer = null;
  3779. }
  3780. }
  3781. function createTimeoutError() {
  3782. const configTimeout = own('timeout');
  3783. let timeoutErrorMessage = configTimeout ? 'timeout of ' + configTimeout + 'ms exceeded' : 'timeout exceeded';
  3784. const configTimeoutErrorMessage = own('timeoutErrorMessage');
  3785. if (configTimeoutErrorMessage) {
  3786. timeoutErrorMessage = configTimeoutErrorMessage;
  3787. }
  3788. return new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, req);
  3789. }
  3790. abortEmitter.once('abort', reject);
  3791. const onFinished = () => {
  3792. clearConnectPhaseTimer();
  3793. if (config.cancelToken) {
  3794. config.cancelToken.unsubscribe(abort);
  3795. }
  3796. if (config.signal) {
  3797. config.signal.removeEventListener('abort', abort);
  3798. }
  3799. abortEmitter.removeAllListeners();
  3800. };
  3801. if (config.cancelToken || config.signal) {
  3802. config.cancelToken && config.cancelToken.subscribe(abort);
  3803. if (config.signal) {
  3804. config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
  3805. }
  3806. }
  3807. onDone((response, isRejected) => {
  3808. isDone = true;
  3809. clearConnectPhaseTimer();
  3810. if (isRejected) {
  3811. rejected = true;
  3812. onFinished();
  3813. return;
  3814. }
  3815. const {
  3816. data
  3817. } = response;
  3818. if (data instanceof stream.Readable || data instanceof stream.Duplex) {
  3819. const offListeners = stream.finished(data, () => {
  3820. offListeners();
  3821. onFinished();
  3822. });
  3823. } else {
  3824. onFinished();
  3825. }
  3826. });
  3827. // Parse url
  3828. const fullPath = buildFullPath(own('baseURL'), own('url'), own('allowAbsoluteUrls'), config);
  3829. // Unix-socket requests (own socketPath) commonly pass a path-only url
  3830. // like '/foo'; supply a synthetic base so new URL() can still parse it.
  3831. // Use the own-property value (not config.socketPath) so a polluted
  3832. // prototype cannot influence URL base selection.
  3833. const urlBase = socketPath ? 'http://localhost' : platform.hasBrowserEnv ? platform.origin : undefined;
  3834. const parsed = new URL(fullPath, urlBase);
  3835. const protocol = parsed.protocol || supportedProtocols[0];
  3836. if (protocol === 'data:') {
  3837. // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set.
  3838. if (maxContentLength > -1) {
  3839. // Use the exact string passed to fromDataURI (the configured url); fall back to fullPath if needed.
  3840. const dataUrl = String(own('url') || fullPath || '');
  3841. const estimated = estimateDataURLBufferAllocation(dataUrl);
  3842. if (estimated > maxContentLength) {
  3843. return reject(new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config));
  3844. }
  3845. }
  3846. let convertedData;
  3847. if (method !== 'GET') {
  3848. return settle(resolve, reject, {
  3849. status: 405,
  3850. statusText: 'method not allowed',
  3851. headers: {},
  3852. config
  3853. });
  3854. }
  3855. try {
  3856. convertedData = fromDataURI(own('url'), responseType === 'blob', {
  3857. Blob: config.env && config.env.Blob
  3858. });
  3859. } catch (err) {
  3860. throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
  3861. }
  3862. if (responseType === 'text') {
  3863. convertedData = convertedData.toString(responseEncoding);
  3864. if (!responseEncoding || responseEncoding === 'utf8') {
  3865. convertedData = utils$1.stripBOM(convertedData);
  3866. }
  3867. } else if (responseType === 'stream') {
  3868. convertedData = stream.Readable.from(convertedData);
  3869. }
  3870. return settle(resolve, reject, {
  3871. data: convertedData,
  3872. status: 200,
  3873. statusText: 'OK',
  3874. headers: new AxiosHeaders(),
  3875. config
  3876. });
  3877. }
  3878. if (supportedProtocols.indexOf(protocol) === -1) {
  3879. return reject(new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_BAD_REQUEST, config));
  3880. }
  3881. const headers = AxiosHeaders.from(config.headers).normalize();
  3882. // Set User-Agent (required by some servers)
  3883. // See https://github.com/axios/axios/issues/69
  3884. // User-Agent is specified; handle case where no UA header is desired
  3885. // Only set header if it hasn't been set in config
  3886. headers.set('User-Agent', 'axios/' + VERSION, false);
  3887. const {
  3888. onUploadProgress,
  3889. onDownloadProgress
  3890. } = config;
  3891. const maxRate = config.maxRate;
  3892. let maxUploadRate = undefined;
  3893. let maxDownloadRate = undefined;
  3894. // support for spec compliant FormData objects
  3895. if (utils$1.isSpecCompliantForm(data)) {
  3896. const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
  3897. data = formDataToStream(data, formHeaders => {
  3898. headers.set(formHeaders);
  3899. }, {
  3900. tag: `axios-${VERSION}-boundary`,
  3901. boundary: userBoundary && userBoundary[1] || undefined
  3902. });
  3903. // support for https://www.npmjs.com/package/form-data api
  3904. } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders) && data.getHeaders !== Object.prototype.getHeaders) {
  3905. setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
  3906. if (!headers.hasContentLength()) {
  3907. try {
  3908. const knownLength = await util.promisify(data.getLength).call(data);
  3909. Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
  3910. /*eslint no-empty:0*/
  3911. } catch (e) {}
  3912. }
  3913. } else if (utils$1.isBlob(data) || utils$1.isFile(data)) {
  3914. data.size && headers.setContentType(data.type || 'application/octet-stream');
  3915. headers.setContentLength(data.size || 0);
  3916. data = stream.Readable.from(readBlob(data));
  3917. } else if (data && !utils$1.isStream(data)) {
  3918. if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) {
  3919. data = Buffer.from(new Uint8Array(data));
  3920. } else if (utils$1.isString(data)) {
  3921. data = Buffer.from(data, 'utf-8');
  3922. } else {
  3923. return reject(new AxiosError('Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', AxiosError.ERR_BAD_REQUEST, config));
  3924. }
  3925. // Add Content-Length header if data exists
  3926. headers.setContentLength(data.length, false);
  3927. if (maxBodyLength > -1 && data.length > maxBodyLength) {
  3928. return reject(new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config));
  3929. }
  3930. }
  3931. const contentLength = utils$1.toFiniteNumber(headers.getContentLength());
  3932. if (utils$1.isArray(maxRate)) {
  3933. maxUploadRate = maxRate[0];
  3934. maxDownloadRate = maxRate[1];
  3935. } else {
  3936. maxUploadRate = maxDownloadRate = maxRate;
  3937. }
  3938. if (data && (onUploadProgress || maxUploadRate)) {
  3939. if (!utils$1.isStream(data)) {
  3940. data = stream.Readable.from(data, {
  3941. objectMode: false
  3942. });
  3943. }
  3944. data = stream.pipeline([data, new AxiosTransformStream({
  3945. maxRate: utils$1.toFiniteNumber(maxUploadRate)
  3946. })], utils$1.noop);
  3947. onUploadProgress && data.on('progress', flushOnFinish(data, progressEventDecorator(contentLength, progressEventReducer(asyncDecorator(onUploadProgress, scheduleProgress), false, 3))));
  3948. }
  3949. // HTTP basic authentication
  3950. let auth = undefined;
  3951. const configAuth = own('auth');
  3952. if (configAuth) {
  3953. const username = utils$1.getSafeProp(configAuth, 'username') || '';
  3954. const password = utils$1.getSafeProp(configAuth, 'password') || '';
  3955. auth = username + ':' + password;
  3956. }
  3957. if (!auth && (parsed.username || parsed.password)) {
  3958. const urlUsername = decodeURIComponentSafe$1(parsed.username);
  3959. const urlPassword = decodeURIComponentSafe$1(parsed.password);
  3960. auth = urlUsername + ':' + urlPassword;
  3961. }
  3962. auth && headers.delete('authorization');
  3963. let path$1;
  3964. try {
  3965. path$1 = buildURL(parsed.pathname + parsed.search, own('params'), own('paramsSerializer')).replace(/^\?/, '');
  3966. } catch (err) {
  3967. return reject(AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config, null, null, {
  3968. url: own('url'),
  3969. exists: true
  3970. }));
  3971. }
  3972. headers.set('Accept-Encoding', utils$1.hasOwnProp(transitional, 'advertiseZstdAcceptEncoding') && transitional.advertiseZstdAcceptEncoding === true ? ACCEPT_ENCODING_WITH_ZSTD : ACCEPT_ENCODING, false);
  3973. // Null-prototype to block prototype pollution gadgets on properties read
  3974. // directly by Node's http.request (e.g. insecureHTTPParser, lookup).
  3975. const options = Object.assign(Object.create(null), {
  3976. path: path$1,
  3977. method: method,
  3978. headers: toByteStringHeaderObject(headers),
  3979. agents: {
  3980. http: httpAgent,
  3981. https: httpsAgent
  3982. },
  3983. auth,
  3984. protocol,
  3985. family,
  3986. beforeRedirect: dispatchBeforeRedirect,
  3987. beforeRedirects: Object.create(null),
  3988. http2Options
  3989. });
  3990. // cacheable-lookup integration hotfix
  3991. !utils$1.isUndefined(lookup) && (options.lookup = lookup);
  3992. if (socketPath) {
  3993. if (typeof socketPath !== 'string') {
  3994. return reject(new AxiosError('socketPath must be a string', AxiosError.ERR_BAD_OPTION_VALUE, config));
  3995. }
  3996. const allowedSocketPaths = own('allowedSocketPaths');
  3997. if (allowedSocketPaths != null) {
  3998. const allowed = Array.isArray(allowedSocketPaths) ? allowedSocketPaths : [allowedSocketPaths];
  3999. const resolvedSocket = path.resolve(socketPath);
  4000. const isAllowed = allowed.some(entry => typeof entry === 'string' && path.resolve(entry) === resolvedSocket);
  4001. if (!isAllowed) {
  4002. return reject(new AxiosError(`socketPath "${socketPath}" is not permitted by allowedSocketPaths`, AxiosError.ERR_BAD_OPTION_VALUE, config));
  4003. }
  4004. }
  4005. options.socketPath = socketPath;
  4006. } else {
  4007. options.hostname = parsed.hostname.startsWith('[') ? parsed.hostname.slice(1, -1) : parsed.hostname;
  4008. options.port = parsed.port;
  4009. setProxy(options, configProxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path, false, httpsAgent, httpAgent);
  4010. }
  4011. let transport;
  4012. let isNativeTransport = false;
  4013. // True only for the follow-redirects transport, which applies
  4014. // options.maxBodyLength itself. Every other transport (http2, native
  4015. // http/https, a user-supplied custom transport) needs the explicit
  4016. // byte-counting pipeline below to enforce maxBodyLength on streamed uploads.
  4017. let transportEnforcesMaxBodyLength = false;
  4018. const isHttpsRequest = isHttps.test(options.protocol);
  4019. // Don't clobber a CONNECT-tunneling agent installed by setProxy() for an
  4020. // HTTPS target.
  4021. if (options.agent == null) {
  4022. options.agent = isHttpsRequest ? httpsAgent : httpAgent;
  4023. }
  4024. if (isHttp2) {
  4025. transport = http2Transport;
  4026. } else {
  4027. const configTransport = own('transport');
  4028. if (configTransport) {
  4029. transport = configTransport;
  4030. } else if (maxRedirects === 0) {
  4031. transport = isHttpsRequest ? https : http;
  4032. isNativeTransport = true;
  4033. } else {
  4034. transportEnforcesMaxBodyLength = true;
  4035. options.sensitiveHeaders = [];
  4036. if (maxRedirects) {
  4037. options.maxRedirects = maxRedirects;
  4038. }
  4039. const configBeforeRedirect = own('beforeRedirect');
  4040. if (configBeforeRedirect) {
  4041. options.beforeRedirects.config = configBeforeRedirect;
  4042. }
  4043. if (auth) {
  4044. // Restore HTTP Basic credentials on same-origin redirects only.
  4045. // follow-redirects >= 1.15.8 strips Authorization on every redirect (see #6929);
  4046. // cross-origin stripping is the documented mitigation for T-R2 in THREATMODEL.md
  4047. // and is preserved by deliberately not restoring on origin change.
  4048. const requestOrigin = parsed.origin;
  4049. const authToRestore = auth;
  4050. options.beforeRedirects.auth = function beforeRedirectAuth(redirectOptions) {
  4051. try {
  4052. if (new URL(redirectOptions.href).origin === requestOrigin) {
  4053. redirectOptions.auth = authToRestore;
  4054. }
  4055. } catch (e) {
  4056. // ignore malformed URL: leaving auth stripped is fail-safe
  4057. }
  4058. };
  4059. }
  4060. const sensitiveHeaders = own('sensitiveHeaders');
  4061. if (sensitiveHeaders != null) {
  4062. if (!utils$1.isArray(sensitiveHeaders)) {
  4063. return reject(new AxiosError('sensitiveHeaders must be an array of strings', AxiosError.ERR_BAD_OPTION_VALUE, config));
  4064. }
  4065. const sensitiveSet = new Set();
  4066. for (const header of sensitiveHeaders) {
  4067. if (!utils$1.isString(header)) {
  4068. return reject(new AxiosError('sensitiveHeaders must be an array of strings', AxiosError.ERR_BAD_OPTION_VALUE, config));
  4069. }
  4070. sensitiveSet.add(header.toLowerCase());
  4071. }
  4072. if (sensitiveSet.size) {
  4073. options.sensitiveHeaders = Array.from(sensitiveSet);
  4074. options.beforeRedirects.sensitiveHeaders = function beforeRedirectSensitiveHeaders(redirectOptions, requestDetails) {
  4075. if (!isSameOriginRedirect(redirectOptions, requestDetails)) {
  4076. stripMatchingHeaders(redirectOptions.headers, sensitiveSet);
  4077. }
  4078. };
  4079. }
  4080. }
  4081. transport = isHttpsRequest ? httpsFollow : httpFollow;
  4082. }
  4083. }
  4084. // Set an explicit maxBodyLength option for transports that inspect it.
  4085. // When maxBodyLength is -1 (default/unlimited), use Infinity so
  4086. // follow-redirects does not fall back to its own 10MB default.
  4087. if (maxBodyLength > -1) {
  4088. options.maxBodyLength = maxBodyLength;
  4089. } else {
  4090. options.maxBodyLength = Infinity;
  4091. }
  4092. // Always set an explicit own value so a polluted
  4093. // Object.prototype.insecureHTTPParser cannot enable the lenient parser
  4094. // through Node's internal options copy
  4095. options.insecureHTTPParser = Boolean(own('insecureHTTPParser'));
  4096. // Create the request
  4097. req = transport.request(options, function handleResponse(res) {
  4098. clearConnectPhaseTimer();
  4099. if (req.destroyed) return;
  4100. const streams = [res];
  4101. const responseLength = utils$1.toFiniteNumber(res.headers['content-length']);
  4102. if (onDownloadProgress || maxDownloadRate) {
  4103. const transformStream = new AxiosTransformStream({
  4104. maxRate: utils$1.toFiniteNumber(maxDownloadRate)
  4105. });
  4106. onDownloadProgress && transformStream.on('progress', flushOnFinish(transformStream, progressEventDecorator(responseLength, progressEventReducer(asyncDecorator(onDownloadProgress, scheduleProgress), true, 3))));
  4107. streams.push(transformStream);
  4108. }
  4109. // decompress the response body transparently if required
  4110. let responseStream = res;
  4111. // return the last request in case of redirects
  4112. const lastRequest = res.req || req;
  4113. // if decompress disabled we should not decompress
  4114. if (decompress !== false && res.headers['content-encoding']) {
  4115. // if no content, but headers still say that it is encoded,
  4116. // remove the header not confuse downstream operations
  4117. if (method === 'HEAD' || res.statusCode === 204) {
  4118. delete res.headers['content-encoding'];
  4119. }
  4120. switch ((res.headers['content-encoding'] || '').toLowerCase()) {
  4121. /*eslint default-case:0*/
  4122. case 'gzip':
  4123. case 'x-gzip':
  4124. case 'compress':
  4125. case 'x-compress':
  4126. // add the unzipper to the body stream processing pipeline
  4127. streams.push(zlib.createUnzip(zlibOptions));
  4128. // remove the content-encoding in order to not confuse downstream operations
  4129. delete res.headers['content-encoding'];
  4130. break;
  4131. case 'deflate':
  4132. streams.push(new ZlibHeaderTransformStream());
  4133. // add the unzipper to the body stream processing pipeline
  4134. streams.push(zlib.createUnzip(zlibOptions));
  4135. // remove the content-encoding in order to not confuse downstream operations
  4136. delete res.headers['content-encoding'];
  4137. break;
  4138. case 'br':
  4139. if (isBrotliSupported) {
  4140. streams.push(zlib.createBrotliDecompress(brotliOptions));
  4141. delete res.headers['content-encoding'];
  4142. }
  4143. break;
  4144. case 'zstd':
  4145. if (isZstdSupported) {
  4146. streams.push(zlib.createZstdDecompress(zstdOptions));
  4147. delete res.headers['content-encoding'];
  4148. }
  4149. break;
  4150. }
  4151. }
  4152. responseStream = streams.length > 1 ? stream.pipeline(streams, utils$1.noop) : streams[0];
  4153. const response = {
  4154. status: res.statusCode,
  4155. statusText: res.statusMessage,
  4156. headers: new AxiosHeaders(res.headers),
  4157. config,
  4158. request: lastRequest
  4159. };
  4160. if (responseType === 'stream') {
  4161. // Enforce maxContentLength on streamed responses; previously this
  4162. // was applied only to buffered responses.
  4163. if (maxContentLength > -1) {
  4164. const limit = maxContentLength;
  4165. const source = responseStream;
  4166. async function* enforceMaxContentLength() {
  4167. let totalResponseBytes = 0;
  4168. for await (const chunk of source) {
  4169. totalResponseBytes += chunk.length;
  4170. if (totalResponseBytes > limit) {
  4171. throw new AxiosError('maxContentLength size of ' + limit + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, lastRequest);
  4172. }
  4173. yield chunk;
  4174. }
  4175. }
  4176. responseStream = stream.Readable.from(enforceMaxContentLength(), {
  4177. objectMode: false
  4178. });
  4179. }
  4180. response.data = responseStream;
  4181. settle(resolve, reject, response);
  4182. } else {
  4183. const responseBuffer = [];
  4184. let totalResponseBytes = 0;
  4185. responseStream.on('data', function handleStreamData(chunk) {
  4186. responseBuffer.push(chunk);
  4187. totalResponseBytes += chunk.length;
  4188. // make sure the content length is not over the maxContentLength if specified
  4189. if (maxContentLength > -1 && totalResponseBytes > maxContentLength) {
  4190. // stream.destroy() emit aborted event before calling reject() on Node.js v16
  4191. rejected = true;
  4192. responseStream.destroy();
  4193. abort(new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
  4194. }
  4195. });
  4196. responseStream.on('aborted', function handlerStreamAborted() {
  4197. if (rejected) {
  4198. return;
  4199. }
  4200. const err = new AxiosError('stream has been aborted', AxiosError.ERR_BAD_RESPONSE, config, lastRequest, response);
  4201. responseStream.destroy(err);
  4202. reject(err);
  4203. });
  4204. responseStream.on('error', function handleStreamError(err) {
  4205. if (rejected) return;
  4206. reject(AxiosError.from(err, null, config, lastRequest, response));
  4207. });
  4208. responseStream.on('end', function handleStreamEnd() {
  4209. try {
  4210. let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
  4211. if (responseType !== 'arraybuffer') {
  4212. responseData = responseData.toString(responseEncoding);
  4213. if (!responseEncoding || responseEncoding === 'utf8') {
  4214. responseData = utils$1.stripBOM(responseData);
  4215. }
  4216. }
  4217. response.data = responseData;
  4218. } catch (err) {
  4219. return reject(AxiosError.from(err, null, config, response.request, response));
  4220. }
  4221. settle(resolve, reject, response);
  4222. });
  4223. }
  4224. abortEmitter.once('abort', err => {
  4225. if (!responseStream.destroyed) {
  4226. responseStream.emit('error', err);
  4227. responseStream.destroy();
  4228. }
  4229. });
  4230. });
  4231. abortEmitter.once('abort', err => {
  4232. if (req.close) {
  4233. req.close();
  4234. } else {
  4235. req.destroy(err);
  4236. }
  4237. });
  4238. // Handle errors
  4239. req.on('error', function handleRequestError(err) {
  4240. reject(AxiosError.from(err, null, config, req));
  4241. });
  4242. // set tcp keep alive to prevent drop connection by peer
  4243. // Track every socket bound to this outer RedirectableRequest so a single
  4244. // 'close' listener can release ownership on all of them. follow-redirects
  4245. // re-emits the 'socket' event for each hop's native request onto the same
  4246. // outer request, so attaching per-request listeners inside this handler
  4247. // would accumulate across hops and trigger MaxListenersExceededWarning at
  4248. // >= 11 redirects. Clearing only the last-bound socket would leave stale
  4249. // kAxiosCurrentReq refs on earlier hop sockets returned to the keep-alive
  4250. // pool, causing an idle-pool 'error' to be attributed to a closed req.
  4251. const boundSockets = new Set();
  4252. req.on('socket', function handleRequestSocket(socket) {
  4253. // default interval of sending ack packet is 1 minute
  4254. // proxy agents (e.g. agent-base) may return a generic Duplex stream
  4255. // that doesn't have setKeepAlive, so guard before calling
  4256. if (typeof socket.setKeepAlive === 'function') {
  4257. socket.setKeepAlive(true, 1000 * 60);
  4258. }
  4259. // Install a single 'error' listener per socket (not per request) to avoid
  4260. // accumulating listeners on pooled keep-alive sockets that get reassigned
  4261. // to new requests before the previous request's 'close' fires (issue #10780).
  4262. // The listener is bound to the socket's currently-active request via a
  4263. // symbol, which is swapped as the socket is reassigned.
  4264. if (!socket[kAxiosSocketListener]) {
  4265. socket.on('error', function handleSocketError(err) {
  4266. const current = socket[kAxiosCurrentReq];
  4267. if (current && !current.destroyed) {
  4268. current.destroy(err);
  4269. }
  4270. });
  4271. socket[kAxiosSocketListener] = true;
  4272. }
  4273. socket[kAxiosCurrentReq] = req;
  4274. boundSockets.add(socket);
  4275. });
  4276. req.once('close', function clearCurrentReq() {
  4277. clearConnectPhaseTimer();
  4278. for (const socket of boundSockets) {
  4279. if (socket[kAxiosCurrentReq] === req) {
  4280. socket[kAxiosCurrentReq] = null;
  4281. }
  4282. }
  4283. boundSockets.clear();
  4284. });
  4285. // Handle request timeout
  4286. if (own('timeout')) {
  4287. // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
  4288. const timeout = parseInt(own('timeout'), 10);
  4289. if (Number.isNaN(timeout)) {
  4290. abort(new AxiosError('error trying to parse `config.timeout` to int', AxiosError.ERR_BAD_OPTION_VALUE, config, req));
  4291. return;
  4292. }
  4293. const handleTimeout = function handleTimeout() {
  4294. if (isDone) return;
  4295. abort(createTimeoutError());
  4296. };
  4297. if (isNativeTransport && timeout > 0) {
  4298. // Native ClientRequest#setTimeout starts from the socket lifecycle and
  4299. // may not fire while TCP connect is still pending. Mirror the
  4300. // follow-redirects wall-clock timer for the maxRedirects === 0 path.
  4301. connectPhaseTimer = setTimeout(handleTimeout, timeout);
  4302. }
  4303. // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
  4304. // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
  4305. // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
  4306. // And then these socket which be hang up will devouring CPU little by little.
  4307. // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
  4308. req.setTimeout(timeout, handleTimeout);
  4309. } else {
  4310. // explicitly reset the socket timeout value for a possible `keep-alive` request
  4311. req.setTimeout(0);
  4312. }
  4313. // Send the request
  4314. if (utils$1.isStream(data)) {
  4315. let ended = false;
  4316. let errored = false;
  4317. data.on('end', () => {
  4318. ended = true;
  4319. });
  4320. data.once('error', err => {
  4321. errored = true;
  4322. req.destroy(err);
  4323. });
  4324. data.on('close', () => {
  4325. if (!ended && !errored) {
  4326. abort(new CanceledError('Request stream has been aborted', config, req));
  4327. }
  4328. });
  4329. // Enforce maxBodyLength for streamed uploads on every transport that
  4330. // does not apply options.maxBodyLength itself (native http/https, http2,
  4331. // and user-supplied custom transports). The follow-redirects transport
  4332. // enforces it on the redirected HTTP/1 path.
  4333. let uploadStream = data;
  4334. if (maxBodyLength > -1 && !transportEnforcesMaxBodyLength) {
  4335. const limit = maxBodyLength;
  4336. let bytesSent = 0;
  4337. uploadStream = stream.pipeline([data, new stream.Transform({
  4338. transform(chunk, _enc, cb) {
  4339. bytesSent += chunk.length;
  4340. if (bytesSent > limit) {
  4341. return cb(new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config, req));
  4342. }
  4343. cb(null, chunk);
  4344. }
  4345. })], utils$1.noop);
  4346. uploadStream.on('error', err => {
  4347. if (!req.destroyed) req.destroy(err);
  4348. });
  4349. }
  4350. uploadStream.pipe(req);
  4351. } else {
  4352. data && req.write(data);
  4353. req.end();
  4354. }
  4355. });
  4356. };
  4357. var isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => url => {
  4358. url = new URL(url, platform.origin);
  4359. return origin.protocol === url.protocol && origin.host === url.host && (isMSIE || origin.port === url.port);
  4360. })(new URL(platform.origin), platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)) : () => true;
  4361. var cookies = platform.hasStandardBrowserEnv ?
  4362. // Standard browser envs support document.cookie
  4363. {
  4364. write(name, value, expires, path, domain, secure, sameSite) {
  4365. if (typeof document === 'undefined') return;
  4366. const cookie = [`${name}=${encodeURIComponent(value)}`];
  4367. if (utils$1.isNumber(expires)) {
  4368. cookie.push(`expires=${new Date(expires).toUTCString()}`);
  4369. }
  4370. if (utils$1.isString(path)) {
  4371. cookie.push(`path=${path}`);
  4372. }
  4373. if (utils$1.isString(domain)) {
  4374. cookie.push(`domain=${domain}`);
  4375. }
  4376. if (secure === true) {
  4377. cookie.push('secure');
  4378. }
  4379. if (utils$1.isString(sameSite)) {
  4380. cookie.push(`SameSite=${sameSite}`);
  4381. }
  4382. document.cookie = cookie.join('; ');
  4383. },
  4384. read(name) {
  4385. if (typeof document === 'undefined') return null;
  4386. // Match name=value by splitting on the semicolon separator instead of building a
  4387. // RegExp from `name` — interpolating an unescaped string into a RegExp would let
  4388. // metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
  4389. // match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
  4390. // "; ", so ignore optional whitespace before each cookie name.
  4391. const cookies = document.cookie.split(';');
  4392. for (let i = 0; i < cookies.length; i++) {
  4393. const cookie = cookies[i].replace(/^\s+/, '');
  4394. const eq = cookie.indexOf('=');
  4395. if (eq !== -1 && cookie.slice(0, eq) === name) {
  4396. try {
  4397. return decodeURIComponent(cookie.slice(eq + 1));
  4398. } catch (e) {
  4399. return cookie.slice(eq + 1);
  4400. }
  4401. }
  4402. }
  4403. return null;
  4404. },
  4405. remove(name) {
  4406. this.write(name, '', Date.now() - 86400000, '/');
  4407. }
  4408. } :
  4409. // Non-standard browser env (web workers, react-native) lack needed support.
  4410. {
  4411. write() {},
  4412. read() {
  4413. return null;
  4414. },
  4415. remove() {}
  4416. };
  4417. const headersToObject = thing => thing instanceof AxiosHeaders ? {
  4418. ...thing
  4419. } : thing;
  4420. const ownEnumerableKeys = thing => {
  4421. if (Object.getOwnPropertySymbols && Object.getOwnPropertyDescriptor) {
  4422. return Object.keys(thing).concat(Object.getOwnPropertySymbols(thing).filter(symbol => Object.getOwnPropertyDescriptor(thing, symbol).enumerable));
  4423. }
  4424. return Object.keys(thing);
  4425. };
  4426. /**
  4427. * Config-specific merge-function which creates a new config-object
  4428. * by merging two configuration objects together.
  4429. *
  4430. * @param {Object} config1
  4431. * @param {Object} config2
  4432. *
  4433. * @returns {Object} New object resulting from merging config2 to config1
  4434. */
  4435. function mergeConfig(config1, config2) {
  4436. // eslint-disable-next-line no-param-reassign
  4437. config1 = config1 || {};
  4438. config2 = config2 || {};
  4439. // Use a null-prototype object so that downstream reads such as `config.auth`
  4440. // or `config.baseURL` cannot inherit polluted values from Object.prototype.
  4441. // `hasOwnProperty` is restored as a non-enumerable own slot to preserve
  4442. // ergonomics for user code that relies on it.
  4443. const config = Object.create(null);
  4444. Object.defineProperty(config, 'hasOwnProperty', {
  4445. // Null-proto descriptor so a polluted Object.prototype.get cannot turn
  4446. // this data descriptor into an accessor descriptor on the way in.
  4447. __proto__: null,
  4448. value: Object.prototype.hasOwnProperty,
  4449. enumerable: false,
  4450. writable: true,
  4451. configurable: true
  4452. });
  4453. function getMergedValue(target, source, prop, caseless) {
  4454. if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
  4455. return utils$1.merge.call({
  4456. caseless
  4457. }, target, source);
  4458. } else if (utils$1.isPlainObject(source)) {
  4459. return utils$1.merge({}, source);
  4460. } else if (utils$1.isArray(source)) {
  4461. return source.slice();
  4462. }
  4463. return source;
  4464. }
  4465. function mergeDeepProperties(a, b, prop, caseless) {
  4466. if (!utils$1.isUndefined(b)) {
  4467. return getMergedValue(a, b, prop, caseless);
  4468. } else if (!utils$1.isUndefined(a)) {
  4469. return getMergedValue(undefined, a, prop, caseless);
  4470. }
  4471. }
  4472. // eslint-disable-next-line consistent-return
  4473. function valueFromConfig2(a, b) {
  4474. if (!utils$1.isUndefined(b)) {
  4475. return getMergedValue(undefined, b);
  4476. }
  4477. }
  4478. // eslint-disable-next-line consistent-return
  4479. function defaultToConfig2(a, b) {
  4480. if (!utils$1.isUndefined(b)) {
  4481. return getMergedValue(undefined, b);
  4482. } else if (!utils$1.isUndefined(a)) {
  4483. return getMergedValue(undefined, a);
  4484. }
  4485. }
  4486. function getMergedTransitionalOption(prop) {
  4487. const transitional2 = utils$1.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined;
  4488. if (!utils$1.isUndefined(transitional2)) {
  4489. if (utils$1.isPlainObject(transitional2)) {
  4490. if (utils$1.hasOwnProp(transitional2, prop)) {
  4491. return transitional2[prop];
  4492. }
  4493. } else {
  4494. return undefined;
  4495. }
  4496. }
  4497. const transitional1 = utils$1.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined;
  4498. if (utils$1.isPlainObject(transitional1) && utils$1.hasOwnProp(transitional1, prop)) {
  4499. return transitional1[prop];
  4500. }
  4501. return undefined;
  4502. }
  4503. // eslint-disable-next-line consistent-return
  4504. function mergeDirectKeys(a, b, prop) {
  4505. if (utils$1.hasOwnProp(config2, prop)) {
  4506. return getMergedValue(a, b);
  4507. } else if (utils$1.hasOwnProp(config1, prop)) {
  4508. return getMergedValue(undefined, a);
  4509. }
  4510. }
  4511. const mergeMap = {
  4512. url: valueFromConfig2,
  4513. method: valueFromConfig2,
  4514. data: valueFromConfig2,
  4515. baseURL: defaultToConfig2,
  4516. transformRequest: defaultToConfig2,
  4517. transformResponse: defaultToConfig2,
  4518. paramsSerializer: defaultToConfig2,
  4519. timeout: defaultToConfig2,
  4520. timeoutMessage: defaultToConfig2,
  4521. withCredentials: defaultToConfig2,
  4522. withXSRFToken: defaultToConfig2,
  4523. adapter: defaultToConfig2,
  4524. responseType: defaultToConfig2,
  4525. xsrfCookieName: defaultToConfig2,
  4526. xsrfHeaderName: defaultToConfig2,
  4527. onUploadProgress: defaultToConfig2,
  4528. onDownloadProgress: defaultToConfig2,
  4529. decompress: defaultToConfig2,
  4530. maxContentLength: defaultToConfig2,
  4531. maxBodyLength: defaultToConfig2,
  4532. beforeRedirect: defaultToConfig2,
  4533. transport: defaultToConfig2,
  4534. httpAgent: defaultToConfig2,
  4535. httpsAgent: defaultToConfig2,
  4536. cancelToken: defaultToConfig2,
  4537. socketPath: defaultToConfig2,
  4538. allowedSocketPaths: defaultToConfig2,
  4539. responseEncoding: defaultToConfig2,
  4540. validateStatus: mergeDirectKeys,
  4541. headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
  4542. };
  4543. utils$1.forEach(ownEnumerableKeys({
  4544. ...config1,
  4545. ...config2
  4546. }), function computeConfigValue(prop) {
  4547. if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return;
  4548. const merge = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
  4549. const a = utils$1.hasOwnProp(config1, prop) ? config1[prop] : undefined;
  4550. const b = utils$1.hasOwnProp(config2, prop) ? config2[prop] : undefined;
  4551. const configValue = merge(a, b, prop);
  4552. utils$1.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue);
  4553. });
  4554. if (utils$1.hasOwnProp(config2, 'validateStatus') && utils$1.isUndefined(config2.validateStatus) && getMergedTransitionalOption('validateStatusUndefinedResolves') === false) {
  4555. if (utils$1.hasOwnProp(config1, 'validateStatus')) {
  4556. config.validateStatus = getMergedValue(undefined, config1.validateStatus);
  4557. } else {
  4558. delete config.validateStatus;
  4559. }
  4560. }
  4561. return config;
  4562. }
  4563. /**
  4564. * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
  4565. * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
  4566. *
  4567. * @param {string} str The string to encode
  4568. *
  4569. * @returns {string} UTF-8 bytes as a Latin-1 string
  4570. */
  4571. const encodeUTF8$1 = str => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
  4572. function resolveConfig(config) {
  4573. const newConfig = mergeConfig({}, config);
  4574. // Read only own properties to prevent prototype pollution gadgets
  4575. // (e.g. Object.prototype.baseURL = 'https://evil.com').
  4576. const own = key => utils$1.hasOwnProp(newConfig, key) ? newConfig[key] : undefined;
  4577. const data = own('data');
  4578. let withXSRFToken = own('withXSRFToken');
  4579. const xsrfHeaderName = own('xsrfHeaderName');
  4580. const xsrfCookieName = own('xsrfCookieName');
  4581. let headers = own('headers');
  4582. const auth = own('auth');
  4583. const baseURL = own('baseURL');
  4584. const allowAbsoluteUrls = own('allowAbsoluteUrls');
  4585. const url = own('url');
  4586. newConfig.headers = headers = AxiosHeaders.from(headers);
  4587. newConfig.url = buildURL(buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig), own('params'), own('paramsSerializer'));
  4588. // HTTP basic authentication
  4589. if (auth) {
  4590. const username = utils$1.getSafeProp(auth, 'username') || '';
  4591. const password = utils$1.getSafeProp(auth, 'password') || '';
  4592. try {
  4593. headers.set('Authorization', 'Basic ' + btoa(username + ':' + (password ? encodeUTF8$1(password) : '')));
  4594. } catch (e) {
  4595. throw AxiosError.from(e, AxiosError.ERR_BAD_OPTION_VALUE, config);
  4596. }
  4597. }
  4598. if (utils$1.isFormData(data)) {
  4599. if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv || utils$1.isReactNative(data)) {
  4600. headers.setContentType(undefined); // browser/web worker/RN handles it
  4601. } else if (utils$1.isFunction(data.getHeaders)) {
  4602. // Node.js FormData (like form-data package)
  4603. setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
  4604. }
  4605. }
  4606. // Add xsrf header
  4607. // This is only done if running in a standard browser environment.
  4608. // Specifically not if we're in a web worker, or react-native.
  4609. if (platform.hasStandardBrowserEnv) {
  4610. if (utils$1.isFunction(withXSRFToken)) {
  4611. withXSRFToken = withXSRFToken(newConfig);
  4612. }
  4613. // Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
  4614. // and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
  4615. // the XSRF token cross-origin.
  4616. const shouldSendXSRF = withXSRFToken === true || withXSRFToken == null && isURLSameOrigin(newConfig.url);
  4617. if (shouldSendXSRF) {
  4618. const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
  4619. if (xsrfValue) {
  4620. headers.set(xsrfHeaderName, xsrfValue);
  4621. }
  4622. }
  4623. }
  4624. return newConfig;
  4625. }
  4626. const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
  4627. var xhrAdapter = isXHRAdapterSupported && function (config) {
  4628. return new Promise(function dispatchXhrRequest(resolve, reject) {
  4629. const _config = resolveConfig(config);
  4630. let requestData = _config.data;
  4631. const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
  4632. let {
  4633. responseType,
  4634. onUploadProgress,
  4635. onDownloadProgress
  4636. } = _config;
  4637. let onCanceled;
  4638. let uploadThrottled, downloadThrottled;
  4639. let flushUpload, flushDownload;
  4640. function done() {
  4641. flushUpload && flushUpload(); // flush events
  4642. flushDownload && flushDownload(); // flush events
  4643. _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
  4644. _config.signal && _config.signal.removeEventListener('abort', onCanceled);
  4645. }
  4646. let request = new XMLHttpRequest();
  4647. request.open(_config.method.toUpperCase(), _config.url, true);
  4648. // Set the request timeout in MS
  4649. request.timeout = _config.timeout;
  4650. function onloadend() {
  4651. if (!request) {
  4652. return;
  4653. }
  4654. // Prepare the response
  4655. const responseHeaders = AxiosHeaders.from('getAllResponseHeaders' in request && request.getAllResponseHeaders());
  4656. const responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response;
  4657. const response = {
  4658. data: responseData,
  4659. status: request.status,
  4660. statusText: request.statusText,
  4661. headers: responseHeaders,
  4662. config,
  4663. request
  4664. };
  4665. settle(function _resolve(value) {
  4666. resolve(value);
  4667. done();
  4668. }, function _reject(err) {
  4669. reject(err);
  4670. done();
  4671. }, response);
  4672. // Clean up request
  4673. request = null;
  4674. }
  4675. if ('onloadend' in request) {
  4676. // Use onloadend if available
  4677. request.onloadend = onloadend;
  4678. } else {
  4679. // Listen for ready state to emulate onloadend
  4680. request.onreadystatechange = function handleLoad() {
  4681. if (!request || request.readyState !== 4) {
  4682. return;
  4683. }
  4684. // The request errored out and we didn't get a response, this will be
  4685. // handled by onerror instead
  4686. // With one exception: request that using file: protocol, most browsers
  4687. // will return status as 0 even though it's a successful request
  4688. if (request.status === 0 && !(request.responseURL && request.responseURL.startsWith('file:'))) {
  4689. return;
  4690. }
  4691. // readystate handler is calling before onerror or ontimeout handlers,
  4692. // so we should call onloadend on the next 'tick'
  4693. setTimeout(onloadend);
  4694. };
  4695. }
  4696. // Handle browser request cancellation (as opposed to a manual cancellation)
  4697. request.onabort = function handleAbort() {
  4698. if (!request) {
  4699. return;
  4700. }
  4701. reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
  4702. done();
  4703. // Clean up request
  4704. request = null;
  4705. };
  4706. // Handle low level network errors
  4707. request.onerror = function handleError(event) {
  4708. // Browsers deliver a ProgressEvent in XHR onerror
  4709. // (message may be empty; when present, surface it)
  4710. // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
  4711. const msg = event && event.message ? event.message : 'Network Error';
  4712. const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
  4713. // attach the underlying event for consumers who want details
  4714. err.event = event || null;
  4715. reject(err);
  4716. done();
  4717. request = null;
  4718. };
  4719. // Handle timeout
  4720. request.ontimeout = function handleTimeout() {
  4721. let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
  4722. const transitional = _config.transitional || transitionalDefaults;
  4723. if (_config.timeoutErrorMessage) {
  4724. timeoutErrorMessage = _config.timeoutErrorMessage;
  4725. }
  4726. reject(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request));
  4727. done();
  4728. // Clean up request
  4729. request = null;
  4730. };
  4731. // Remove Content-Type if data is undefined
  4732. requestData === undefined && requestHeaders.setContentType(null);
  4733. // Add headers to the request
  4734. if ('setRequestHeader' in request) {
  4735. utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
  4736. request.setRequestHeader(key, val);
  4737. });
  4738. }
  4739. // Add withCredentials to request if needed
  4740. if (!utils$1.isUndefined(_config.withCredentials)) {
  4741. request.withCredentials = !!_config.withCredentials;
  4742. }
  4743. // Add responseType to request if needed
  4744. if (responseType && responseType !== 'json') {
  4745. request.responseType = _config.responseType;
  4746. }
  4747. // Handle progress if needed
  4748. if (onDownloadProgress) {
  4749. [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
  4750. request.addEventListener('progress', downloadThrottled);
  4751. }
  4752. // Not all browsers support upload events
  4753. if (onUploadProgress && request.upload) {
  4754. [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
  4755. request.upload.addEventListener('progress', uploadThrottled);
  4756. request.upload.addEventListener('loadend', flushUpload);
  4757. }
  4758. if (_config.cancelToken || _config.signal) {
  4759. // Handle cancellation
  4760. // eslint-disable-next-line func-names
  4761. onCanceled = cancel => {
  4762. if (!request) {
  4763. return;
  4764. }
  4765. reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
  4766. request.abort();
  4767. done();
  4768. request = null;
  4769. };
  4770. _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
  4771. if (_config.signal) {
  4772. _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
  4773. }
  4774. }
  4775. const protocol = parseProtocol(_config.url);
  4776. if (protocol && !platform.protocols.includes(protocol)) {
  4777. reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
  4778. done();
  4779. return;
  4780. }
  4781. // Send the request
  4782. request.send(requestData || null);
  4783. });
  4784. };
  4785. const composeSignals = (signals, timeout) => {
  4786. signals = signals ? signals.filter(Boolean) : [];
  4787. if (!timeout && !signals.length) {
  4788. return;
  4789. }
  4790. const controller = new AbortController();
  4791. let aborted = false;
  4792. const onabort = function (reason) {
  4793. if (!aborted) {
  4794. aborted = true;
  4795. unsubscribe();
  4796. const err = reason instanceof Error ? reason : this.reason;
  4797. controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
  4798. }
  4799. };
  4800. let timer = timeout && setTimeout(() => {
  4801. timer = null;
  4802. onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
  4803. }, timeout);
  4804. const unsubscribe = () => {
  4805. if (!signals) {
  4806. return;
  4807. }
  4808. timer && clearTimeout(timer);
  4809. timer = null;
  4810. signals.forEach(signal => {
  4811. signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
  4812. });
  4813. signals = null;
  4814. };
  4815. signals.forEach(signal => {
  4816. if (aborted) {
  4817. return;
  4818. }
  4819. if (signal.aborted) {
  4820. onabort.call(signal);
  4821. return;
  4822. }
  4823. signal.addEventListener('abort', onabort, {
  4824. once: true
  4825. });
  4826. });
  4827. const {
  4828. signal
  4829. } = controller;
  4830. signal.unsubscribe = () => utils$1.asap(unsubscribe);
  4831. return signal;
  4832. };
  4833. const streamChunk = function* (chunk, chunkSize) {
  4834. let len = chunk.byteLength;
  4835. if (len < chunkSize) {
  4836. yield chunk;
  4837. return;
  4838. }
  4839. let pos = 0;
  4840. let end;
  4841. while (pos < len) {
  4842. end = pos + chunkSize;
  4843. yield chunk.slice(pos, end);
  4844. pos = end;
  4845. }
  4846. };
  4847. const readBytes = async function* (iterable, chunkSize) {
  4848. for await (const chunk of readStream(iterable)) {
  4849. yield* streamChunk(chunk, chunkSize);
  4850. }
  4851. };
  4852. const readStream = async function* (stream) {
  4853. if (stream[Symbol.asyncIterator]) {
  4854. yield* stream;
  4855. return;
  4856. }
  4857. const reader = stream.getReader();
  4858. try {
  4859. for (;;) {
  4860. const {
  4861. done,
  4862. value
  4863. } = await reader.read();
  4864. if (done) {
  4865. break;
  4866. }
  4867. yield value;
  4868. }
  4869. } finally {
  4870. await reader.cancel();
  4871. }
  4872. };
  4873. const trackStream = (stream, chunkSize, onProgress, onFinish) => {
  4874. const iterator = readBytes(stream, chunkSize);
  4875. let bytes = 0;
  4876. let done;
  4877. let _onFinish = e => {
  4878. if (!done) {
  4879. done = true;
  4880. onFinish && onFinish(e);
  4881. }
  4882. };
  4883. return new ReadableStream({
  4884. async pull(controller) {
  4885. try {
  4886. const {
  4887. done,
  4888. value
  4889. } = await iterator.next();
  4890. if (done) {
  4891. _onFinish();
  4892. controller.close();
  4893. return;
  4894. }
  4895. let len = value.byteLength;
  4896. if (onProgress) {
  4897. let loadedBytes = bytes += len;
  4898. onProgress(loadedBytes);
  4899. }
  4900. controller.enqueue(new Uint8Array(value));
  4901. } catch (err) {
  4902. _onFinish(err);
  4903. throw err;
  4904. }
  4905. },
  4906. cancel(reason) {
  4907. _onFinish(reason);
  4908. return iterator.return();
  4909. }
  4910. }, {
  4911. highWaterMark: 2
  4912. });
  4913. };
  4914. const DEFAULT_CHUNK_SIZE = 64 * 1024;
  4915. const {
  4916. isFunction
  4917. } = utils$1;
  4918. /**
  4919. * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
  4920. * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
  4921. *
  4922. * @param {string} str The string to encode
  4923. *
  4924. * @returns {string} UTF-8 bytes as a Latin-1 string
  4925. */
  4926. const encodeUTF8 = str => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
  4927. // Node's WHATWG URL parser returns `username` and `password` percent-encoded.
  4928. // Decode before composing the `auth` option so credentials such as
  4929. // `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
  4930. // original value for malformed input so a bad encoding never throws.
  4931. const decodeURIComponentSafe = value => {
  4932. if (!utils$1.isString(value)) {
  4933. return value;
  4934. }
  4935. try {
  4936. return decodeURIComponent(value);
  4937. } catch (error) {
  4938. return value;
  4939. }
  4940. };
  4941. const test = (fn, ...args) => {
  4942. try {
  4943. return !!fn(...args);
  4944. } catch (e) {
  4945. return false;
  4946. }
  4947. };
  4948. const maybeWithAuthCredentials = url => {
  4949. const protocolIndex = url.indexOf('://');
  4950. let urlToCheck = url;
  4951. if (protocolIndex !== -1) {
  4952. urlToCheck = urlToCheck.slice(protocolIndex + 3);
  4953. }
  4954. return urlToCheck.includes('@') || urlToCheck.includes(':');
  4955. };
  4956. const factory = env => {
  4957. const globalObject = utils$1.global !== undefined && utils$1.global !== null ? utils$1.global : globalThis;
  4958. const {
  4959. ReadableStream,
  4960. TextEncoder
  4961. } = globalObject;
  4962. env = utils$1.merge.call({
  4963. skipUndefined: true
  4964. }, {
  4965. Request: globalObject.Request,
  4966. Response: globalObject.Response
  4967. }, env);
  4968. const {
  4969. fetch: envFetch,
  4970. Request,
  4971. Response
  4972. } = env;
  4973. const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
  4974. const isRequestSupported = isFunction(Request);
  4975. const isResponseSupported = isFunction(Response);
  4976. if (!isFetchSupported) {
  4977. return false;
  4978. }
  4979. const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
  4980. const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? (encoder => str => encoder.encode(str))(new TextEncoder()) : async str => new Uint8Array(await new Request(str).arrayBuffer()));
  4981. const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
  4982. let duplexAccessed = false;
  4983. const request = new Request(platform.origin, {
  4984. body: new ReadableStream(),
  4985. method: 'POST',
  4986. get duplex() {
  4987. duplexAccessed = true;
  4988. return 'half';
  4989. }
  4990. });
  4991. const hasContentType = request.headers.has('Content-Type');
  4992. if (request.body != null) {
  4993. request.body.cancel();
  4994. }
  4995. return duplexAccessed && !hasContentType;
  4996. });
  4997. const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response('').body));
  4998. const resolvers = {
  4999. stream: supportsResponseStream && (res => res.body)
  5000. };
  5001. isFetchSupported && (() => {
  5002. ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
  5003. !resolvers[type] && (resolvers[type] = (res, config) => {
  5004. let method = res && res[type];
  5005. if (method) {
  5006. return method.call(res);
  5007. }
  5008. throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
  5009. });
  5010. });
  5011. })();
  5012. const getBodyLength = async body => {
  5013. if (body == null) {
  5014. return 0;
  5015. }
  5016. if (utils$1.isBlob(body)) {
  5017. return body.size;
  5018. }
  5019. if (utils$1.isSpecCompliantForm(body)) {
  5020. const _request = new Request(platform.origin, {
  5021. method: 'POST',
  5022. body
  5023. });
  5024. return (await _request.arrayBuffer()).byteLength;
  5025. }
  5026. if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
  5027. return body.byteLength;
  5028. }
  5029. if (utils$1.isURLSearchParams(body)) {
  5030. body = body + '';
  5031. }
  5032. if (utils$1.isString(body)) {
  5033. return (await encodeText(body)).byteLength;
  5034. }
  5035. };
  5036. const resolveBodyLength = async (headers, body) => {
  5037. const length = utils$1.toFiniteNumber(headers.getContentLength());
  5038. return length == null ? getBodyLength(body) : length;
  5039. };
  5040. return async config => {
  5041. let {
  5042. url,
  5043. method,
  5044. data,
  5045. signal,
  5046. cancelToken,
  5047. timeout,
  5048. onDownloadProgress,
  5049. onUploadProgress,
  5050. responseType,
  5051. headers,
  5052. withCredentials = 'same-origin',
  5053. fetchOptions,
  5054. maxContentLength,
  5055. maxBodyLength
  5056. } = resolveConfig(config);
  5057. const hasMaxContentLength = utils$1.isNumber(maxContentLength) && maxContentLength > -1;
  5058. const hasMaxBodyLength = utils$1.isNumber(maxBodyLength) && maxBodyLength > -1;
  5059. const own = key => utils$1.hasOwnProp(config, key) ? config[key] : undefined;
  5060. let _fetch = envFetch || fetch;
  5061. responseType = responseType ? (responseType + '').toLowerCase() : 'text';
  5062. let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
  5063. let request = null;
  5064. const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
  5065. composedSignal.unsubscribe();
  5066. });
  5067. let requestContentLength;
  5068. // AxiosError we raise while the request body is being streamed. Captured
  5069. // by identity so the catch block can surface it directly, regardless of
  5070. // how the runtime wraps the resulting fetch rejection (undici exposes it
  5071. // as `err.cause`; some browsers drop the original error entirely).
  5072. let pendingBodyError = null;
  5073. const maxBodyLengthError = () => new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config, request);
  5074. try {
  5075. // HTTP basic authentication
  5076. let auth = undefined;
  5077. const configAuth = own('auth');
  5078. if (configAuth) {
  5079. const username = utils$1.getSafeProp(configAuth, 'username') || '';
  5080. const password = utils$1.getSafeProp(configAuth, 'password') || '';
  5081. auth = {
  5082. username,
  5083. password
  5084. };
  5085. }
  5086. if (maybeWithAuthCredentials(url)) {
  5087. const parsedURL = new URL(url, platform.origin);
  5088. if (!auth && (parsedURL.username || parsedURL.password)) {
  5089. const urlUsername = decodeURIComponentSafe(parsedURL.username);
  5090. const urlPassword = decodeURIComponentSafe(parsedURL.password);
  5091. auth = {
  5092. username: urlUsername,
  5093. password: urlPassword
  5094. };
  5095. }
  5096. if (parsedURL.username || parsedURL.password) {
  5097. parsedURL.username = '';
  5098. parsedURL.password = '';
  5099. url = parsedURL.href;
  5100. }
  5101. }
  5102. if (auth) {
  5103. headers.delete('authorization');
  5104. headers.set('Authorization', 'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || ''))));
  5105. }
  5106. // Enforce maxContentLength for data: URLs up-front so we never materialize
  5107. // an oversized payload. The HTTP adapter applies the same check (see http.js
  5108. // "if (protocol === 'data:')" branch).
  5109. if (hasMaxContentLength && typeof url === 'string' && url.startsWith('data:')) {
  5110. const estimated = estimateDataURLDecodedBytes(url);
  5111. if (estimated > maxContentLength) {
  5112. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  5113. }
  5114. }
  5115. // Enforce maxBodyLength against known-size bodies before dispatch using
  5116. // the body's *actual* size — never a caller-declared Content-Length,
  5117. // which could under-report to slip an oversized body past the check.
  5118. // Unknown-size streams return undefined here and are counted per-chunk
  5119. // below as fetch consumes them.
  5120. if (hasMaxBodyLength && method !== 'get' && method !== 'head') {
  5121. const outboundLength = await getBodyLength(data);
  5122. if (typeof outboundLength === 'number' && isFinite(outboundLength)) {
  5123. requestContentLength = outboundLength;
  5124. if (outboundLength > maxBodyLength) {
  5125. throw maxBodyLengthError();
  5126. }
  5127. }
  5128. }
  5129. // A streamed body under maxBodyLength must be counted as fetch consumes
  5130. // it; its size is never trusted from a caller-declared Content-Length.
  5131. const mustEnforceStreamBody = hasMaxBodyLength && (utils$1.isReadableStream(data) || utils$1.isStream(data));
  5132. const trackRequestStream = (stream, onProgress, flush) => trackStream(stream, DEFAULT_CHUNK_SIZE, loadedBytes => {
  5133. if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
  5134. throw pendingBodyError = maxBodyLengthError();
  5135. }
  5136. onProgress && onProgress(loadedBytes);
  5137. }, flush);
  5138. if (supportsRequestStream && method !== 'get' && method !== 'head' && (onUploadProgress || mustEnforceStreamBody)) {
  5139. requestContentLength = requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength;
  5140. // A declared length of 0 is only trusted to skip the wrap when we are
  5141. // not enforcing a stream limit (which must not rely on that header).
  5142. if (requestContentLength !== 0 || mustEnforceStreamBody) {
  5143. let _request = new Request(url, {
  5144. method: 'POST',
  5145. body: data,
  5146. duplex: 'half'
  5147. });
  5148. let contentTypeHeader;
  5149. if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
  5150. headers.setContentType(contentTypeHeader);
  5151. }
  5152. if (_request.body) {
  5153. const [onProgress, flush] = onUploadProgress && progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress))) || [];
  5154. data = trackRequestStream(_request.body, onProgress, flush);
  5155. }
  5156. }
  5157. } else if (mustEnforceStreamBody && !isRequestSupported && isReadableStreamSupported && method !== 'get' && method !== 'head') {
  5158. data = trackRequestStream(data);
  5159. } else if (mustEnforceStreamBody && isRequestSupported && !supportsRequestStream && method !== 'get' && method !== 'head') {
  5160. throw new AxiosError('Stream request bodies are not supported by the current fetch implementation', AxiosError.ERR_NOT_SUPPORT, config, request);
  5161. }
  5162. if (!utils$1.isString(withCredentials)) {
  5163. withCredentials = withCredentials ? 'include' : 'omit';
  5164. }
  5165. // Cloudflare Workers throws when credentials are defined
  5166. // see https://github.com/cloudflare/workerd/issues/902
  5167. const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;
  5168. // If data is FormData and Content-Type is multipart/form-data without boundary,
  5169. // delete it so fetch can set it correctly with the boundary
  5170. if (utils$1.isFormData(data)) {
  5171. const contentType = headers.getContentType();
  5172. if (contentType && /^multipart\/form-data/i.test(contentType) && !/boundary=/i.test(contentType)) {
  5173. headers.delete('content-type');
  5174. }
  5175. }
  5176. // Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
  5177. headers.set('User-Agent', 'axios/' + VERSION, false);
  5178. const resolvedOptions = {
  5179. ...fetchOptions,
  5180. signal: composedSignal,
  5181. method: method.toUpperCase(),
  5182. headers: toByteStringHeaderObject(headers.normalize()),
  5183. body: data,
  5184. duplex: 'half',
  5185. credentials: isCredentialsSupported ? withCredentials : undefined
  5186. };
  5187. request = isRequestSupported && new Request(url, resolvedOptions);
  5188. let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
  5189. const responseHeaders = AxiosHeaders.from(response.headers);
  5190. // Cheap pre-check: if the server honestly declares a content-length that
  5191. // already exceeds the cap, reject before we start streaming.
  5192. if (hasMaxContentLength) {
  5193. const declaredLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
  5194. if (declaredLength != null && declaredLength > maxContentLength) {
  5195. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  5196. }
  5197. }
  5198. const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
  5199. if (supportsResponseStream && response.body && (onDownloadProgress || hasMaxContentLength || isStreamResponse && unsubscribe)) {
  5200. const options = {};
  5201. ['status', 'statusText', 'headers'].forEach(prop => {
  5202. options[prop] = response[prop];
  5203. });
  5204. const responseContentLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
  5205. const [onProgress, flush] = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [];
  5206. let bytesRead = 0;
  5207. const onChunkProgress = loadedBytes => {
  5208. if (hasMaxContentLength) {
  5209. bytesRead = loadedBytes;
  5210. if (bytesRead > maxContentLength) {
  5211. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  5212. }
  5213. }
  5214. onProgress && onProgress(loadedBytes);
  5215. };
  5216. response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
  5217. flush && flush();
  5218. unsubscribe && unsubscribe();
  5219. }), options);
  5220. }
  5221. responseType = responseType || 'text';
  5222. let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
  5223. // Fallback enforcement for environments without ReadableStream support
  5224. // (legacy runtimes). Detect materialized size from typed output; skip
  5225. // streams/Response passthrough since the user will read those themselves.
  5226. if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
  5227. let materializedSize;
  5228. if (responseData != null) {
  5229. if (typeof responseData.byteLength === 'number') {
  5230. materializedSize = responseData.byteLength;
  5231. } else if (typeof responseData.size === 'number') {
  5232. materializedSize = responseData.size;
  5233. } else if (typeof responseData === 'string') {
  5234. materializedSize = typeof TextEncoder === 'function' ? new TextEncoder().encode(responseData).byteLength : responseData.length;
  5235. }
  5236. }
  5237. if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {
  5238. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  5239. }
  5240. }
  5241. !isStreamResponse && unsubscribe && unsubscribe();
  5242. return await new Promise((resolve, reject) => {
  5243. settle(resolve, reject, {
  5244. data: responseData,
  5245. headers: AxiosHeaders.from(response.headers),
  5246. status: response.status,
  5247. statusText: response.statusText,
  5248. config,
  5249. request
  5250. });
  5251. });
  5252. } catch (err) {
  5253. unsubscribe && unsubscribe();
  5254. // Safari can surface fetch aborts as a DOMException-like object whose
  5255. // branded getters throw. Prefer our composed signal reason before reading
  5256. // the caught error, preserving timeout vs cancellation semantics.
  5257. if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) {
  5258. const canceledError = composedSignal.reason;
  5259. canceledError.config = config;
  5260. request && (canceledError.request = request);
  5261. if (err !== canceledError) {
  5262. // Non-enumerable to match native Error `cause` semantics so loggers
  5263. // don't recurse into circular fetch internals (see #7205).
  5264. Object.defineProperty(canceledError, 'cause', {
  5265. __proto__: null,
  5266. value: err,
  5267. writable: true,
  5268. enumerable: false,
  5269. configurable: true
  5270. });
  5271. }
  5272. throw canceledError;
  5273. }
  5274. // Surface a maxBodyLength violation we raised while the request body was
  5275. // being streamed. Matching by identity (rather than reading
  5276. // `err.cause.isAxiosError`) keeps the error deterministic across runtimes
  5277. // and avoids both prototype-pollution reads and mis-attributing a foreign
  5278. // AxiosError that merely happened to land in `err.cause`.
  5279. if (pendingBodyError) {
  5280. request && !pendingBodyError.request && (pendingBodyError.request = request);
  5281. throw pendingBodyError;
  5282. }
  5283. // Re-throw AxiosErrors we raised synchronously (data: URL / content-length
  5284. // pre-checks, response size enforcement) without re-wrapping them.
  5285. if (err instanceof AxiosError) {
  5286. request && !err.request && (err.request = request);
  5287. throw err;
  5288. }
  5289. if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
  5290. const networkError = new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, err && err.response);
  5291. // Non-enumerable to match native Error `cause` semantics so loggers
  5292. // don't recurse into circular fetch internals (see #7205).
  5293. Object.defineProperty(networkError, 'cause', {
  5294. __proto__: null,
  5295. value: err.cause || err,
  5296. writable: true,
  5297. enumerable: false,
  5298. configurable: true
  5299. });
  5300. throw networkError;
  5301. }
  5302. throw AxiosError.from(err, err && err.code, config, request, err && err.response);
  5303. }
  5304. };
  5305. };
  5306. const seedCache = new Map();
  5307. const getFetch = config => {
  5308. let env = config && config.env || {};
  5309. const {
  5310. fetch,
  5311. Request,
  5312. Response
  5313. } = env;
  5314. const seeds = [Request, Response, fetch];
  5315. let len = seeds.length,
  5316. i = len,
  5317. seed,
  5318. target,
  5319. map = seedCache;
  5320. while (i--) {
  5321. seed = seeds[i];
  5322. target = map.get(seed);
  5323. target === undefined && map.set(seed, target = i ? new Map() : factory(env));
  5324. map = target;
  5325. }
  5326. return target;
  5327. };
  5328. getFetch();
  5329. /**
  5330. * Known adapters mapping.
  5331. * Provides environment-specific adapters for Axios:
  5332. * - `http` for Node.js
  5333. * - `xhr` for browsers
  5334. * - `fetch` for fetch API-based requests
  5335. *
  5336. * @type {Object<string, Function|Object>}
  5337. */
  5338. const knownAdapters = {
  5339. http: httpAdapter,
  5340. xhr: xhrAdapter,
  5341. fetch: {
  5342. get: getFetch
  5343. }
  5344. };
  5345. // Assign adapter names for easier debugging and identification
  5346. utils$1.forEach(knownAdapters, (fn, value) => {
  5347. if (fn) {
  5348. try {
  5349. // Null-proto descriptors so a polluted Object.prototype.get cannot turn
  5350. // these data descriptors into accessor descriptors on the way in.
  5351. Object.defineProperty(fn, 'name', {
  5352. __proto__: null,
  5353. value
  5354. });
  5355. } catch (e) {
  5356. // eslint-disable-next-line no-empty
  5357. }
  5358. Object.defineProperty(fn, 'adapterName', {
  5359. __proto__: null,
  5360. value
  5361. });
  5362. }
  5363. });
  5364. /**
  5365. * Render a rejection reason string for unknown or unsupported adapters
  5366. *
  5367. * @param {string} reason
  5368. * @returns {string}
  5369. */
  5370. const renderReason = reason => `- ${reason}`;
  5371. /**
  5372. * Check if the adapter is resolved (function, null, or false)
  5373. *
  5374. * @param {Function|null|false} adapter
  5375. * @returns {boolean}
  5376. */
  5377. const isResolvedHandle = adapter => utils$1.isFunction(adapter) || adapter === null || adapter === false;
  5378. /**
  5379. * Get the first suitable adapter from the provided list.
  5380. * Tries each adapter in order until a supported one is found.
  5381. * Throws an AxiosError if no adapter is suitable.
  5382. *
  5383. * @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
  5384. * @param {Object} config - Axios request configuration
  5385. * @throws {AxiosError} If no suitable adapter is available
  5386. * @returns {Function} The resolved adapter function
  5387. */
  5388. function getAdapter(adapters, config) {
  5389. adapters = utils$1.isArray(adapters) ? adapters : [adapters];
  5390. const {
  5391. length
  5392. } = adapters;
  5393. let nameOrAdapter;
  5394. let adapter;
  5395. const rejectedReasons = {};
  5396. for (let i = 0; i < length; i++) {
  5397. nameOrAdapter = adapters[i];
  5398. let id;
  5399. adapter = nameOrAdapter;
  5400. if (!isResolvedHandle(nameOrAdapter)) {
  5401. adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
  5402. if (adapter === undefined) {
  5403. throw new AxiosError(`Unknown adapter '${id}'`);
  5404. }
  5405. }
  5406. if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
  5407. break;
  5408. }
  5409. rejectedReasons[id || '#' + i] = adapter;
  5410. }
  5411. if (!adapter) {
  5412. const reasons = Object.entries(rejectedReasons).map(([id, state]) => `adapter ${id} ` + (state === false ? 'is not supported by the environment' : 'is not available in the build'));
  5413. let s = length ? reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0]) : 'as no adapter specified';
  5414. throw new AxiosError(`There is no suitable adapter to dispatch the request ` + s, AxiosError.ERR_NOT_SUPPORT);
  5415. }
  5416. return adapter;
  5417. }
  5418. /**
  5419. * Exports Axios adapters and utility to resolve an adapter
  5420. */
  5421. var adapters = {
  5422. /**
  5423. * Resolve an adapter from a list of adapter names or functions.
  5424. * @type {Function}
  5425. */
  5426. getAdapter,
  5427. /**
  5428. * Exposes all known adapters
  5429. * @type {Object<string, Function|Object>}
  5430. */
  5431. adapters: knownAdapters
  5432. };
  5433. /**
  5434. * Throws a `CanceledError` if cancellation has been requested.
  5435. *
  5436. * @param {Object} config The config that is to be used for the request
  5437. *
  5438. * @returns {void}
  5439. */
  5440. function throwIfCancellationRequested(config) {
  5441. if (config.cancelToken) {
  5442. config.cancelToken.throwIfRequested();
  5443. }
  5444. if (config.signal && config.signal.aborted) {
  5445. throw new CanceledError(null, config);
  5446. }
  5447. }
  5448. /**
  5449. * Dispatch a request to the server using the configured adapter.
  5450. *
  5451. * @param {object} config The config that is to be used for the request
  5452. *
  5453. * @returns {Promise} The Promise to be fulfilled
  5454. */
  5455. function dispatchRequest(config) {
  5456. throwIfCancellationRequested(config);
  5457. config.headers = AxiosHeaders.from(config.headers);
  5458. // Transform request data
  5459. config.data = transformData.call(config, config.transformRequest);
  5460. if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
  5461. config.headers.setContentType('application/x-www-form-urlencoded', false);
  5462. }
  5463. const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
  5464. return adapter(config).then(function onAdapterResolution(response) {
  5465. throwIfCancellationRequested(config);
  5466. // Expose the current response on config so that transformResponse can
  5467. // attach it to any AxiosError it throws (e.g. on JSON parse failure).
  5468. // We clean it up afterwards to avoid polluting the config object.
  5469. config.response = response;
  5470. try {
  5471. response.data = transformData.call(config, config.transformResponse, response);
  5472. } finally {
  5473. delete config.response;
  5474. }
  5475. response.headers = AxiosHeaders.from(response.headers);
  5476. return response;
  5477. }, function onAdapterRejection(reason) {
  5478. if (!isCancel(reason)) {
  5479. throwIfCancellationRequested(config);
  5480. // Transform response data
  5481. if (reason && reason.response) {
  5482. config.response = reason.response;
  5483. try {
  5484. reason.response.data = transformData.call(config, config.transformResponse, reason.response);
  5485. } finally {
  5486. delete config.response;
  5487. }
  5488. reason.response.headers = AxiosHeaders.from(reason.response.headers);
  5489. }
  5490. }
  5491. return Promise.reject(reason);
  5492. });
  5493. }
  5494. const validators$1 = {};
  5495. // eslint-disable-next-line func-names
  5496. ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
  5497. validators$1[type] = function validator(thing) {
  5498. return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  5499. };
  5500. });
  5501. const deprecatedWarnings = {};
  5502. /**
  5503. * Transitional option validator
  5504. *
  5505. * @param {function|boolean?} validator - set to false if the transitional option has been removed
  5506. * @param {string?} version - deprecated version / removed since version
  5507. * @param {string?} message - some message with additional info
  5508. *
  5509. * @returns {function}
  5510. */
  5511. validators$1.transitional = function transitional(validator, version, message) {
  5512. function formatMessage(opt, desc) {
  5513. return '[Axios v' + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? '. ' + message : '');
  5514. }
  5515. // eslint-disable-next-line func-names
  5516. return (value, opt, opts) => {
  5517. if (validator === false) {
  5518. throw new AxiosError(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), AxiosError.ERR_DEPRECATED);
  5519. }
  5520. if (version && !deprecatedWarnings[opt]) {
  5521. deprecatedWarnings[opt] = true;
  5522. // eslint-disable-next-line no-console
  5523. console.warn(formatMessage(opt, ' has been deprecated since v' + version + ' and will be removed in the near future'));
  5524. }
  5525. return validator ? validator(value, opt, opts) : true;
  5526. };
  5527. };
  5528. validators$1.spelling = function spelling(correctSpelling) {
  5529. return (value, opt) => {
  5530. // eslint-disable-next-line no-console
  5531. console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
  5532. return true;
  5533. };
  5534. };
  5535. /**
  5536. * Assert object's properties type
  5537. *
  5538. * @param {object} options
  5539. * @param {object} schema
  5540. * @param {boolean?} allowUnknown
  5541. *
  5542. * @returns {object}
  5543. */
  5544. function assertOptions(options, schema, allowUnknown) {
  5545. if (typeof options !== 'object' || options === null) {
  5546. throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
  5547. }
  5548. const keys = Object.keys(options);
  5549. let i = keys.length;
  5550. while (i-- > 0) {
  5551. const opt = keys[i];
  5552. // Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply
  5553. // a non-function validator and cause a TypeError.
  5554. const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;
  5555. if (validator) {
  5556. const value = options[opt];
  5557. const result = value === undefined || validator(value, opt, options);
  5558. if (result !== true) {
  5559. throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
  5560. }
  5561. continue;
  5562. }
  5563. if (allowUnknown !== true) {
  5564. throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
  5565. }
  5566. }
  5567. }
  5568. var validator = {
  5569. assertOptions,
  5570. validators: validators$1
  5571. };
  5572. const validators = validator.validators;
  5573. /**
  5574. * Create a new instance of Axios
  5575. *
  5576. * @param {Object} instanceConfig The default config for the instance
  5577. *
  5578. * @return {Axios} A new instance of Axios
  5579. */
  5580. class Axios {
  5581. constructor(instanceConfig) {
  5582. this.defaults = instanceConfig || {};
  5583. this.interceptors = {
  5584. request: new InterceptorManager(),
  5585. response: new InterceptorManager()
  5586. };
  5587. }
  5588. /**
  5589. * Dispatch a request
  5590. *
  5591. * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
  5592. * @param {?Object} config
  5593. *
  5594. * @returns {Promise} The Promise to be fulfilled
  5595. */
  5596. async request(configOrUrl, config) {
  5597. try {
  5598. return await this._request(configOrUrl, config);
  5599. } catch (err) {
  5600. if (err instanceof Error) {
  5601. let dummy = {};
  5602. Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
  5603. // slice off the Error: ... line
  5604. const stack = (() => {
  5605. if (!dummy.stack) {
  5606. return '';
  5607. }
  5608. const firstNewlineIndex = dummy.stack.indexOf('\n');
  5609. return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1);
  5610. })();
  5611. try {
  5612. if (!err.stack) {
  5613. err.stack = stack;
  5614. // match without the 2 top stack lines
  5615. } else if (stack) {
  5616. const firstNewlineIndex = stack.indexOf('\n');
  5617. const secondNewlineIndex = firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1);
  5618. const stackWithoutTwoTopLines = secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1);
  5619. if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) {
  5620. err.stack += '\n' + stack;
  5621. }
  5622. }
  5623. } catch (e) {
  5624. // ignore the case where "stack" is an un-writable property
  5625. }
  5626. }
  5627. throw err;
  5628. }
  5629. }
  5630. _request(configOrUrl, config) {
  5631. /*eslint no-param-reassign:0*/
  5632. // Allow for axios('example/url'[, config]) a la fetch API
  5633. if (typeof configOrUrl === 'string') {
  5634. config = config || {};
  5635. config.url = configOrUrl;
  5636. } else {
  5637. config = configOrUrl || {};
  5638. }
  5639. config = mergeConfig(this.defaults, config);
  5640. const {
  5641. transitional,
  5642. paramsSerializer,
  5643. headers
  5644. } = config;
  5645. if (transitional !== undefined) {
  5646. validator.assertOptions(transitional, {
  5647. silentJSONParsing: validators.transitional(validators.boolean),
  5648. forcedJSONParsing: validators.transitional(validators.boolean),
  5649. clarifyTimeoutError: validators.transitional(validators.boolean),
  5650. legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
  5651. advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),
  5652. validateStatusUndefinedResolves: validators.transitional(validators.boolean)
  5653. }, false);
  5654. }
  5655. if (paramsSerializer != null) {
  5656. if (utils$1.isFunction(paramsSerializer)) {
  5657. config.paramsSerializer = {
  5658. serialize: paramsSerializer
  5659. };
  5660. } else {
  5661. validator.assertOptions(paramsSerializer, {
  5662. encode: validators.function,
  5663. serialize: validators.function
  5664. }, true);
  5665. }
  5666. }
  5667. // Set config.allowAbsoluteUrls
  5668. if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
  5669. config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
  5670. } else {
  5671. config.allowAbsoluteUrls = true;
  5672. }
  5673. validator.assertOptions(config, {
  5674. baseUrl: validators.spelling('baseURL'),
  5675. withXsrfToken: validators.spelling('withXSRFToken')
  5676. }, true);
  5677. // Set config.method
  5678. config.method = (config.method || this.defaults.method || 'get').toLowerCase();
  5679. // Flatten headers
  5680. let contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]);
  5681. headers && utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], method => {
  5682. delete headers[method];
  5683. });
  5684. config.headers = AxiosHeaders.concat(contextHeaders, headers);
  5685. // filter out skipped interceptors
  5686. const requestInterceptorChain = [];
  5687. let synchronousRequestInterceptors = true;
  5688. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  5689. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  5690. return;
  5691. }
  5692. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  5693. const transitional = config.transitional || transitionalDefaults;
  5694. const legacyInterceptorReqResOrdering = transitional && transitional.legacyInterceptorReqResOrdering;
  5695. if (legacyInterceptorReqResOrdering) {
  5696. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  5697. } else {
  5698. requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  5699. }
  5700. });
  5701. const responseInterceptorChain = [];
  5702. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  5703. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  5704. });
  5705. let promise;
  5706. let i = 0;
  5707. let len;
  5708. if (!synchronousRequestInterceptors) {
  5709. const chain = [dispatchRequest.bind(this), undefined];
  5710. chain.unshift(...requestInterceptorChain);
  5711. chain.push(...responseInterceptorChain);
  5712. len = chain.length;
  5713. promise = Promise.resolve(config);
  5714. while (i < len) {
  5715. promise = promise.then(chain[i++], chain[i++]);
  5716. }
  5717. return promise;
  5718. }
  5719. len = requestInterceptorChain.length;
  5720. let newConfig = config;
  5721. while (i < len) {
  5722. const onFulfilled = requestInterceptorChain[i++];
  5723. const onRejected = requestInterceptorChain[i++];
  5724. try {
  5725. newConfig = onFulfilled ? onFulfilled(newConfig) : newConfig;
  5726. } catch (error) {
  5727. if (!onRejected) {
  5728. promise = Promise.reject(error);
  5729. break;
  5730. }
  5731. try {
  5732. const rejectedResult = onRejected.call(this, error);
  5733. if (utils$1.isThenable(rejectedResult)) {
  5734. promise = Promise.resolve(rejectedResult).then(() => dispatchRequest.call(this, newConfig));
  5735. }
  5736. } catch (rejectedError) {
  5737. promise = Promise.reject(rejectedError);
  5738. }
  5739. break;
  5740. }
  5741. }
  5742. if (!promise) {
  5743. try {
  5744. promise = dispatchRequest.call(this, newConfig);
  5745. } catch (error) {
  5746. promise = Promise.reject(error);
  5747. }
  5748. }
  5749. i = 0;
  5750. len = responseInterceptorChain.length;
  5751. while (i < len) {
  5752. promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
  5753. }
  5754. return promise;
  5755. }
  5756. getUri(config) {
  5757. config = mergeConfig(this.defaults, config);
  5758. const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
  5759. return buildURL(fullPath, config.params, config.paramsSerializer);
  5760. }
  5761. }
  5762. // Provide aliases for supported request methods
  5763. utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  5764. /*eslint func-names:0*/
  5765. Axios.prototype[method] = function (url, config) {
  5766. return this.request(mergeConfig(config || {}, {
  5767. method,
  5768. url,
  5769. data: config && utils$1.hasOwnProp(config, 'data') ? config.data : undefined
  5770. }));
  5771. };
  5772. });
  5773. utils$1.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
  5774. function generateHTTPMethod(isForm) {
  5775. return function httpMethod(url, data, config) {
  5776. return this.request(mergeConfig(config || {}, {
  5777. method,
  5778. headers: isForm ? {
  5779. 'Content-Type': 'multipart/form-data'
  5780. } : {},
  5781. url,
  5782. data
  5783. }));
  5784. };
  5785. }
  5786. Axios.prototype[method] = generateHTTPMethod();
  5787. // QUERY is a safe/idempotent read method; multipart form bodies don't fit
  5788. // its semantics, so no queryForm shorthand is generated.
  5789. if (method !== 'query') {
  5790. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  5791. }
  5792. });
  5793. /**
  5794. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  5795. *
  5796. * @param {Function} executor The executor function.
  5797. *
  5798. * @returns {CancelToken}
  5799. */
  5800. class CancelToken {
  5801. constructor(executor) {
  5802. if (typeof executor !== 'function') {
  5803. throw new TypeError('executor must be a function.');
  5804. }
  5805. let resolvePromise;
  5806. this.promise = new Promise(function promiseExecutor(resolve) {
  5807. resolvePromise = resolve;
  5808. });
  5809. const token = this;
  5810. // eslint-disable-next-line func-names
  5811. this.promise.then(cancel => {
  5812. if (!token._listeners) return;
  5813. let i = token._listeners.length;
  5814. while (i-- > 0) {
  5815. token._listeners[i](cancel);
  5816. }
  5817. token._listeners = null;
  5818. });
  5819. // eslint-disable-next-line func-names
  5820. this.promise.then = onfulfilled => {
  5821. let _resolve;
  5822. // eslint-disable-next-line func-names
  5823. const promise = new Promise(resolve => {
  5824. token.subscribe(resolve);
  5825. _resolve = resolve;
  5826. }).then(onfulfilled);
  5827. promise.cancel = function reject() {
  5828. token.unsubscribe(_resolve);
  5829. };
  5830. return promise;
  5831. };
  5832. executor(function cancel(message, config, request) {
  5833. if (token.reason) {
  5834. // Cancellation has already been requested
  5835. return;
  5836. }
  5837. token.reason = new CanceledError(message, config, request);
  5838. resolvePromise(token.reason);
  5839. });
  5840. }
  5841. /**
  5842. * Throws a `CanceledError` if cancellation has been requested.
  5843. */
  5844. throwIfRequested() {
  5845. if (this.reason) {
  5846. throw this.reason;
  5847. }
  5848. }
  5849. /**
  5850. * Subscribe to the cancel signal
  5851. */
  5852. subscribe(listener) {
  5853. if (this.reason) {
  5854. listener(this.reason);
  5855. return;
  5856. }
  5857. if (this._listeners) {
  5858. this._listeners.push(listener);
  5859. } else {
  5860. this._listeners = [listener];
  5861. }
  5862. }
  5863. /**
  5864. * Unsubscribe from the cancel signal
  5865. */
  5866. unsubscribe(listener) {
  5867. if (!this._listeners) {
  5868. return;
  5869. }
  5870. const index = this._listeners.indexOf(listener);
  5871. if (index !== -1) {
  5872. this._listeners.splice(index, 1);
  5873. }
  5874. }
  5875. toAbortSignal() {
  5876. const controller = new AbortController();
  5877. const abort = err => {
  5878. controller.abort(err);
  5879. };
  5880. this.subscribe(abort);
  5881. controller.signal.unsubscribe = () => this.unsubscribe(abort);
  5882. return controller.signal;
  5883. }
  5884. /**
  5885. * Returns an object that contains a new `CancelToken` and a function that, when called,
  5886. * cancels the `CancelToken`.
  5887. */
  5888. static source() {
  5889. let cancel;
  5890. const token = new CancelToken(function executor(c) {
  5891. cancel = c;
  5892. });
  5893. return {
  5894. token,
  5895. cancel
  5896. };
  5897. }
  5898. }
  5899. /**
  5900. * Syntactic sugar for invoking a function and expanding an array for arguments.
  5901. *
  5902. * Common use case would be to use `Function.prototype.apply`.
  5903. *
  5904. * ```js
  5905. * function f(x, y, z) {}
  5906. * const args = [1, 2, 3];
  5907. * f.apply(null, args);
  5908. * ```
  5909. *
  5910. * With `spread` this example can be re-written.
  5911. *
  5912. * ```js
  5913. * spread(function(x, y, z) {})([1, 2, 3]);
  5914. * ```
  5915. *
  5916. * @param {Function} callback
  5917. *
  5918. * @returns {Function}
  5919. */
  5920. function spread(callback) {
  5921. return function wrap(arr) {
  5922. return callback.apply(null, arr);
  5923. };
  5924. }
  5925. /**
  5926. * Determines whether the payload is an error thrown by Axios
  5927. *
  5928. * @param {*} payload The value to test
  5929. *
  5930. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  5931. */
  5932. function isAxiosError(payload) {
  5933. return utils$1.isObject(payload) && payload.isAxiosError === true;
  5934. }
  5935. const HttpStatusCode = {
  5936. Continue: 100,
  5937. SwitchingProtocols: 101,
  5938. Processing: 102,
  5939. EarlyHints: 103,
  5940. Ok: 200,
  5941. Created: 201,
  5942. Accepted: 202,
  5943. NonAuthoritativeInformation: 203,
  5944. NoContent: 204,
  5945. ResetContent: 205,
  5946. PartialContent: 206,
  5947. MultiStatus: 207,
  5948. AlreadyReported: 208,
  5949. ImUsed: 226,
  5950. MultipleChoices: 300,
  5951. MovedPermanently: 301,
  5952. Found: 302,
  5953. SeeOther: 303,
  5954. NotModified: 304,
  5955. UseProxy: 305,
  5956. Unused: 306,
  5957. TemporaryRedirect: 307,
  5958. PermanentRedirect: 308,
  5959. BadRequest: 400,
  5960. Unauthorized: 401,
  5961. PaymentRequired: 402,
  5962. Forbidden: 403,
  5963. NotFound: 404,
  5964. MethodNotAllowed: 405,
  5965. NotAcceptable: 406,
  5966. ProxyAuthenticationRequired: 407,
  5967. RequestTimeout: 408,
  5968. Conflict: 409,
  5969. Gone: 410,
  5970. LengthRequired: 411,
  5971. PreconditionFailed: 412,
  5972. PayloadTooLarge: 413,
  5973. UriTooLong: 414,
  5974. UnsupportedMediaType: 415,
  5975. RangeNotSatisfiable: 416,
  5976. ExpectationFailed: 417,
  5977. ImATeapot: 418,
  5978. MisdirectedRequest: 421,
  5979. UnprocessableEntity: 422,
  5980. Locked: 423,
  5981. FailedDependency: 424,
  5982. TooEarly: 425,
  5983. UpgradeRequired: 426,
  5984. PreconditionRequired: 428,
  5985. TooManyRequests: 429,
  5986. RequestHeaderFieldsTooLarge: 431,
  5987. UnavailableForLegalReasons: 451,
  5988. InternalServerError: 500,
  5989. NotImplemented: 501,
  5990. BadGateway: 502,
  5991. ServiceUnavailable: 503,
  5992. GatewayTimeout: 504,
  5993. HttpVersionNotSupported: 505,
  5994. VariantAlsoNegotiates: 506,
  5995. InsufficientStorage: 507,
  5996. LoopDetected: 508,
  5997. NotExtended: 510,
  5998. NetworkAuthenticationRequired: 511,
  5999. WebServerReturnsAnUnknownError: 520,
  6000. WebServerIsDown: 521,
  6001. ConnectionTimedOut: 522,
  6002. OriginIsUnreachable: 523,
  6003. TimeoutOccurred: 524,
  6004. SslHandshakeFailed: 525,
  6005. InvalidSslCertificate: 526
  6006. };
  6007. Object.entries(HttpStatusCode).forEach(([key, value]) => {
  6008. HttpStatusCode[value] = key;
  6009. });
  6010. /**
  6011. * Create an instance of Axios
  6012. *
  6013. * @param {Object} defaultConfig The default config for the instance
  6014. *
  6015. * @returns {Axios} A new instance of Axios
  6016. */
  6017. function createInstance(defaultConfig) {
  6018. const context = new Axios(defaultConfig);
  6019. const instance = bind(Axios.prototype.request, context);
  6020. // Copy axios.prototype to instance
  6021. utils$1.extend(instance, Axios.prototype, context, {
  6022. allOwnKeys: true
  6023. });
  6024. // Copy context to instance
  6025. utils$1.extend(instance, context, null, {
  6026. allOwnKeys: true
  6027. });
  6028. // Factory for creating new instances
  6029. instance.create = function create(instanceConfig) {
  6030. return createInstance(mergeConfig(defaultConfig, instanceConfig));
  6031. };
  6032. return instance;
  6033. }
  6034. // Create the default instance to be exported
  6035. const axios = createInstance(defaults);
  6036. // Expose Axios class to allow class inheritance
  6037. axios.Axios = Axios;
  6038. // Expose Cancel & CancelToken
  6039. axios.CanceledError = CanceledError;
  6040. axios.CancelToken = CancelToken;
  6041. axios.isCancel = isCancel;
  6042. axios.VERSION = VERSION;
  6043. axios.toFormData = toFormData;
  6044. // Expose AxiosError class
  6045. axios.AxiosError = AxiosError;
  6046. // alias for CanceledError for backward compatibility
  6047. axios.Cancel = axios.CanceledError;
  6048. // Expose all/spread
  6049. axios.all = function all(promises) {
  6050. return Promise.all(promises);
  6051. };
  6052. axios.spread = spread;
  6053. // Expose isAxiosError
  6054. axios.isAxiosError = isAxiosError;
  6055. // Expose mergeConfig
  6056. axios.mergeConfig = mergeConfig;
  6057. axios.AxiosHeaders = AxiosHeaders;
  6058. axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
  6059. axios.getAdapter = adapters.getAdapter;
  6060. axios.HttpStatusCode = HttpStatusCode;
  6061. axios.default = axios;
  6062. module.exports = axios;