axios.cjs 125 KB

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