axios.js 99 KB

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