axios.cjs 126 KB

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