axios.cjs 145 KB

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