axios.cjs 182 KB

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