智慧水务管理系统 - 精河县供水工程综合管理平台

axios.cjs 137KB

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