axios.cjs 170 KB

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