axios.cjs 116 KB

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