axios.cjs 110 KB

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