axios.cjs 100 KB

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