keymetrics.es5.js 497 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Keymetrics = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. (function (process){(function (){
  3. "use strict";
  4. var pkg = require('./package.json');
  5. var config = {
  6. headers: {
  7. 'X-JS-API-Version': pkg.version
  8. },
  9. services: {
  10. API: 'https://app.keymetrics.io',
  11. OAUTH: 'https://id.keymetrics.io'
  12. },
  13. OAUTH_AUTHORIZE_ENDPOINT: '/api/oauth/authorize',
  14. OAUTH_CLIENT_ID: '795984050',
  15. ENVIRONNEMENT: process && process.versions && process.versions.node ? 'node' : 'browser',
  16. VERSION: pkg.version,
  17. // put in debug when using km.io with browser OR when DEBUG=true with nodejs
  18. IS_DEBUG: typeof window !== 'undefined' && window.location.host.match(/km.(io|local)/) || typeof process !== 'undefined' && process.env.DEBUG === 'true'
  19. };
  20. module.exports = Object.assign({}, config);
  21. }).call(this)}).call(this,require('_process'))
  22. },{"./package.json":37,"_process":35}],2:[function(require,module,exports){
  23. (function (process,global,setImmediate){(function (){
  24. (function (global, factory) {
  25. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  26. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  27. (factory((global.async = global.async || {})));
  28. }(this, (function (exports) { 'use strict';
  29. function slice(arrayLike, start) {
  30. start = start|0;
  31. var newLen = Math.max(arrayLike.length - start, 0);
  32. var newArr = Array(newLen);
  33. for(var idx = 0; idx < newLen; idx++) {
  34. newArr[idx] = arrayLike[start + idx];
  35. }
  36. return newArr;
  37. }
  38. /**
  39. * Creates a continuation function with some arguments already applied.
  40. *
  41. * Useful as a shorthand when combined with other control flow functions. Any
  42. * arguments passed to the returned function are added to the arguments
  43. * originally passed to apply.
  44. *
  45. * @name apply
  46. * @static
  47. * @memberOf module:Utils
  48. * @method
  49. * @category Util
  50. * @param {Function} fn - The function you want to eventually apply all
  51. * arguments to. Invokes with (arguments...).
  52. * @param {...*} arguments... - Any number of arguments to automatically apply
  53. * when the continuation is called.
  54. * @returns {Function} the partially-applied function
  55. * @example
  56. *
  57. * // using apply
  58. * async.parallel([
  59. * async.apply(fs.writeFile, 'testfile1', 'test1'),
  60. * async.apply(fs.writeFile, 'testfile2', 'test2')
  61. * ]);
  62. *
  63. *
  64. * // the same process without using apply
  65. * async.parallel([
  66. * function(callback) {
  67. * fs.writeFile('testfile1', 'test1', callback);
  68. * },
  69. * function(callback) {
  70. * fs.writeFile('testfile2', 'test2', callback);
  71. * }
  72. * ]);
  73. *
  74. * // It's possible to pass any number of additional arguments when calling the
  75. * // continuation:
  76. *
  77. * node> var fn = async.apply(sys.puts, 'one');
  78. * node> fn('two', 'three');
  79. * one
  80. * two
  81. * three
  82. */
  83. var apply = function(fn/*, ...args*/) {
  84. var args = slice(arguments, 1);
  85. return function(/*callArgs*/) {
  86. var callArgs = slice(arguments);
  87. return fn.apply(null, args.concat(callArgs));
  88. };
  89. };
  90. var initialParams = function (fn) {
  91. return function (/*...args, callback*/) {
  92. var args = slice(arguments);
  93. var callback = args.pop();
  94. fn.call(this, args, callback);
  95. };
  96. };
  97. /**
  98. * Checks if `value` is the
  99. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  100. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  101. *
  102. * @static
  103. * @memberOf _
  104. * @since 0.1.0
  105. * @category Lang
  106. * @param {*} value The value to check.
  107. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  108. * @example
  109. *
  110. * _.isObject({});
  111. * // => true
  112. *
  113. * _.isObject([1, 2, 3]);
  114. * // => true
  115. *
  116. * _.isObject(_.noop);
  117. * // => true
  118. *
  119. * _.isObject(null);
  120. * // => false
  121. */
  122. function isObject(value) {
  123. var type = typeof value;
  124. return value != null && (type == 'object' || type == 'function');
  125. }
  126. var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
  127. var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
  128. function fallback(fn) {
  129. setTimeout(fn, 0);
  130. }
  131. function wrap(defer) {
  132. return function (fn/*, ...args*/) {
  133. var args = slice(arguments, 1);
  134. defer(function () {
  135. fn.apply(null, args);
  136. });
  137. };
  138. }
  139. var _defer;
  140. if (hasSetImmediate) {
  141. _defer = setImmediate;
  142. } else if (hasNextTick) {
  143. _defer = process.nextTick;
  144. } else {
  145. _defer = fallback;
  146. }
  147. var setImmediate$1 = wrap(_defer);
  148. /**
  149. * Take a sync function and make it async, passing its return value to a
  150. * callback. This is useful for plugging sync functions into a waterfall,
  151. * series, or other async functions. Any arguments passed to the generated
  152. * function will be passed to the wrapped function (except for the final
  153. * callback argument). Errors thrown will be passed to the callback.
  154. *
  155. * If the function passed to `asyncify` returns a Promise, that promises's
  156. * resolved/rejected state will be used to call the callback, rather than simply
  157. * the synchronous return value.
  158. *
  159. * This also means you can asyncify ES2017 `async` functions.
  160. *
  161. * @name asyncify
  162. * @static
  163. * @memberOf module:Utils
  164. * @method
  165. * @alias wrapSync
  166. * @category Util
  167. * @param {Function} func - The synchronous function, or Promise-returning
  168. * function to convert to an {@link AsyncFunction}.
  169. * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
  170. * invoked with `(args..., callback)`.
  171. * @example
  172. *
  173. * // passing a regular synchronous function
  174. * async.waterfall([
  175. * async.apply(fs.readFile, filename, "utf8"),
  176. * async.asyncify(JSON.parse),
  177. * function (data, next) {
  178. * // data is the result of parsing the text.
  179. * // If there was a parsing error, it would have been caught.
  180. * }
  181. * ], callback);
  182. *
  183. * // passing a function returning a promise
  184. * async.waterfall([
  185. * async.apply(fs.readFile, filename, "utf8"),
  186. * async.asyncify(function (contents) {
  187. * return db.model.create(contents);
  188. * }),
  189. * function (model, next) {
  190. * // `model` is the instantiated model object.
  191. * // If there was an error, this function would be skipped.
  192. * }
  193. * ], callback);
  194. *
  195. * // es2017 example, though `asyncify` is not needed if your JS environment
  196. * // supports async functions out of the box
  197. * var q = async.queue(async.asyncify(async function(file) {
  198. * var intermediateStep = await processFile(file);
  199. * return await somePromise(intermediateStep)
  200. * }));
  201. *
  202. * q.push(files);
  203. */
  204. function asyncify(func) {
  205. return initialParams(function (args, callback) {
  206. var result;
  207. try {
  208. result = func.apply(this, args);
  209. } catch (e) {
  210. return callback(e);
  211. }
  212. // if result is Promise object
  213. if (isObject(result) && typeof result.then === 'function') {
  214. result.then(function(value) {
  215. invokeCallback(callback, null, value);
  216. }, function(err) {
  217. invokeCallback(callback, err.message ? err : new Error(err));
  218. });
  219. } else {
  220. callback(null, result);
  221. }
  222. });
  223. }
  224. function invokeCallback(callback, error, value) {
  225. try {
  226. callback(error, value);
  227. } catch (e) {
  228. setImmediate$1(rethrow, e);
  229. }
  230. }
  231. function rethrow(error) {
  232. throw error;
  233. }
  234. var supportsSymbol = typeof Symbol === 'function';
  235. function isAsync(fn) {
  236. return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction';
  237. }
  238. function wrapAsync(asyncFn) {
  239. return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
  240. }
  241. function applyEach$1(eachfn) {
  242. return function(fns/*, ...args*/) {
  243. var args = slice(arguments, 1);
  244. var go = initialParams(function(args, callback) {
  245. var that = this;
  246. return eachfn(fns, function (fn, cb) {
  247. wrapAsync(fn).apply(that, args.concat(cb));
  248. }, callback);
  249. });
  250. if (args.length) {
  251. return go.apply(this, args);
  252. }
  253. else {
  254. return go;
  255. }
  256. };
  257. }
  258. /** Detect free variable `global` from Node.js. */
  259. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  260. /** Detect free variable `self`. */
  261. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  262. /** Used as a reference to the global object. */
  263. var root = freeGlobal || freeSelf || Function('return this')();
  264. /** Built-in value references. */
  265. var Symbol$1 = root.Symbol;
  266. /** Used for built-in method references. */
  267. var objectProto = Object.prototype;
  268. /** Used to check objects for own properties. */
  269. var hasOwnProperty = objectProto.hasOwnProperty;
  270. /**
  271. * Used to resolve the
  272. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  273. * of values.
  274. */
  275. var nativeObjectToString = objectProto.toString;
  276. /** Built-in value references. */
  277. var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
  278. /**
  279. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  280. *
  281. * @private
  282. * @param {*} value The value to query.
  283. * @returns {string} Returns the raw `toStringTag`.
  284. */
  285. function getRawTag(value) {
  286. var isOwn = hasOwnProperty.call(value, symToStringTag$1),
  287. tag = value[symToStringTag$1];
  288. try {
  289. value[symToStringTag$1] = undefined;
  290. var unmasked = true;
  291. } catch (e) {}
  292. var result = nativeObjectToString.call(value);
  293. if (unmasked) {
  294. if (isOwn) {
  295. value[symToStringTag$1] = tag;
  296. } else {
  297. delete value[symToStringTag$1];
  298. }
  299. }
  300. return result;
  301. }
  302. /** Used for built-in method references. */
  303. var objectProto$1 = Object.prototype;
  304. /**
  305. * Used to resolve the
  306. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  307. * of values.
  308. */
  309. var nativeObjectToString$1 = objectProto$1.toString;
  310. /**
  311. * Converts `value` to a string using `Object.prototype.toString`.
  312. *
  313. * @private
  314. * @param {*} value The value to convert.
  315. * @returns {string} Returns the converted string.
  316. */
  317. function objectToString(value) {
  318. return nativeObjectToString$1.call(value);
  319. }
  320. /** `Object#toString` result references. */
  321. var nullTag = '[object Null]';
  322. var undefinedTag = '[object Undefined]';
  323. /** Built-in value references. */
  324. var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
  325. /**
  326. * The base implementation of `getTag` without fallbacks for buggy environments.
  327. *
  328. * @private
  329. * @param {*} value The value to query.
  330. * @returns {string} Returns the `toStringTag`.
  331. */
  332. function baseGetTag(value) {
  333. if (value == null) {
  334. return value === undefined ? undefinedTag : nullTag;
  335. }
  336. return (symToStringTag && symToStringTag in Object(value))
  337. ? getRawTag(value)
  338. : objectToString(value);
  339. }
  340. /** `Object#toString` result references. */
  341. var asyncTag = '[object AsyncFunction]';
  342. var funcTag = '[object Function]';
  343. var genTag = '[object GeneratorFunction]';
  344. var proxyTag = '[object Proxy]';
  345. /**
  346. * Checks if `value` is classified as a `Function` object.
  347. *
  348. * @static
  349. * @memberOf _
  350. * @since 0.1.0
  351. * @category Lang
  352. * @param {*} value The value to check.
  353. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  354. * @example
  355. *
  356. * _.isFunction(_);
  357. * // => true
  358. *
  359. * _.isFunction(/abc/);
  360. * // => false
  361. */
  362. function isFunction(value) {
  363. if (!isObject(value)) {
  364. return false;
  365. }
  366. // The use of `Object#toString` avoids issues with the `typeof` operator
  367. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  368. var tag = baseGetTag(value);
  369. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  370. }
  371. /** Used as references for various `Number` constants. */
  372. var MAX_SAFE_INTEGER = 9007199254740991;
  373. /**
  374. * Checks if `value` is a valid array-like length.
  375. *
  376. * **Note:** This method is loosely based on
  377. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  378. *
  379. * @static
  380. * @memberOf _
  381. * @since 4.0.0
  382. * @category Lang
  383. * @param {*} value The value to check.
  384. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  385. * @example
  386. *
  387. * _.isLength(3);
  388. * // => true
  389. *
  390. * _.isLength(Number.MIN_VALUE);
  391. * // => false
  392. *
  393. * _.isLength(Infinity);
  394. * // => false
  395. *
  396. * _.isLength('3');
  397. * // => false
  398. */
  399. function isLength(value) {
  400. return typeof value == 'number' &&
  401. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  402. }
  403. /**
  404. * Checks if `value` is array-like. A value is considered array-like if it's
  405. * not a function and has a `value.length` that's an integer greater than or
  406. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  407. *
  408. * @static
  409. * @memberOf _
  410. * @since 4.0.0
  411. * @category Lang
  412. * @param {*} value The value to check.
  413. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  414. * @example
  415. *
  416. * _.isArrayLike([1, 2, 3]);
  417. * // => true
  418. *
  419. * _.isArrayLike(document.body.children);
  420. * // => true
  421. *
  422. * _.isArrayLike('abc');
  423. * // => true
  424. *
  425. * _.isArrayLike(_.noop);
  426. * // => false
  427. */
  428. function isArrayLike(value) {
  429. return value != null && isLength(value.length) && !isFunction(value);
  430. }
  431. // A temporary value used to identify if the loop should be broken.
  432. // See #1064, #1293
  433. var breakLoop = {};
  434. /**
  435. * This method returns `undefined`.
  436. *
  437. * @static
  438. * @memberOf _
  439. * @since 2.3.0
  440. * @category Util
  441. * @example
  442. *
  443. * _.times(2, _.noop);
  444. * // => [undefined, undefined]
  445. */
  446. function noop() {
  447. // No operation performed.
  448. }
  449. function once(fn) {
  450. return function () {
  451. if (fn === null) return;
  452. var callFn = fn;
  453. fn = null;
  454. callFn.apply(this, arguments);
  455. };
  456. }
  457. var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator;
  458. var getIterator = function (coll) {
  459. return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol]();
  460. };
  461. /**
  462. * The base implementation of `_.times` without support for iteratee shorthands
  463. * or max array length checks.
  464. *
  465. * @private
  466. * @param {number} n The number of times to invoke `iteratee`.
  467. * @param {Function} iteratee The function invoked per iteration.
  468. * @returns {Array} Returns the array of results.
  469. */
  470. function baseTimes(n, iteratee) {
  471. var index = -1,
  472. result = Array(n);
  473. while (++index < n) {
  474. result[index] = iteratee(index);
  475. }
  476. return result;
  477. }
  478. /**
  479. * Checks if `value` is object-like. A value is object-like if it's not `null`
  480. * and has a `typeof` result of "object".
  481. *
  482. * @static
  483. * @memberOf _
  484. * @since 4.0.0
  485. * @category Lang
  486. * @param {*} value The value to check.
  487. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  488. * @example
  489. *
  490. * _.isObjectLike({});
  491. * // => true
  492. *
  493. * _.isObjectLike([1, 2, 3]);
  494. * // => true
  495. *
  496. * _.isObjectLike(_.noop);
  497. * // => false
  498. *
  499. * _.isObjectLike(null);
  500. * // => false
  501. */
  502. function isObjectLike(value) {
  503. return value != null && typeof value == 'object';
  504. }
  505. /** `Object#toString` result references. */
  506. var argsTag = '[object Arguments]';
  507. /**
  508. * The base implementation of `_.isArguments`.
  509. *
  510. * @private
  511. * @param {*} value The value to check.
  512. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  513. */
  514. function baseIsArguments(value) {
  515. return isObjectLike(value) && baseGetTag(value) == argsTag;
  516. }
  517. /** Used for built-in method references. */
  518. var objectProto$3 = Object.prototype;
  519. /** Used to check objects for own properties. */
  520. var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
  521. /** Built-in value references. */
  522. var propertyIsEnumerable = objectProto$3.propertyIsEnumerable;
  523. /**
  524. * Checks if `value` is likely an `arguments` object.
  525. *
  526. * @static
  527. * @memberOf _
  528. * @since 0.1.0
  529. * @category Lang
  530. * @param {*} value The value to check.
  531. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  532. * else `false`.
  533. * @example
  534. *
  535. * _.isArguments(function() { return arguments; }());
  536. * // => true
  537. *
  538. * _.isArguments([1, 2, 3]);
  539. * // => false
  540. */
  541. var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
  542. return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') &&
  543. !propertyIsEnumerable.call(value, 'callee');
  544. };
  545. /**
  546. * Checks if `value` is classified as an `Array` object.
  547. *
  548. * @static
  549. * @memberOf _
  550. * @since 0.1.0
  551. * @category Lang
  552. * @param {*} value The value to check.
  553. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  554. * @example
  555. *
  556. * _.isArray([1, 2, 3]);
  557. * // => true
  558. *
  559. * _.isArray(document.body.children);
  560. * // => false
  561. *
  562. * _.isArray('abc');
  563. * // => false
  564. *
  565. * _.isArray(_.noop);
  566. * // => false
  567. */
  568. var isArray = Array.isArray;
  569. /**
  570. * This method returns `false`.
  571. *
  572. * @static
  573. * @memberOf _
  574. * @since 4.13.0
  575. * @category Util
  576. * @returns {boolean} Returns `false`.
  577. * @example
  578. *
  579. * _.times(2, _.stubFalse);
  580. * // => [false, false]
  581. */
  582. function stubFalse() {
  583. return false;
  584. }
  585. /** Detect free variable `exports`. */
  586. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  587. /** Detect free variable `module`. */
  588. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  589. /** Detect the popular CommonJS extension `module.exports`. */
  590. var moduleExports = freeModule && freeModule.exports === freeExports;
  591. /** Built-in value references. */
  592. var Buffer = moduleExports ? root.Buffer : undefined;
  593. /* Built-in method references for those with the same name as other `lodash` methods. */
  594. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  595. /**
  596. * Checks if `value` is a buffer.
  597. *
  598. * @static
  599. * @memberOf _
  600. * @since 4.3.0
  601. * @category Lang
  602. * @param {*} value The value to check.
  603. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  604. * @example
  605. *
  606. * _.isBuffer(new Buffer(2));
  607. * // => true
  608. *
  609. * _.isBuffer(new Uint8Array(2));
  610. * // => false
  611. */
  612. var isBuffer = nativeIsBuffer || stubFalse;
  613. /** Used as references for various `Number` constants. */
  614. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  615. /** Used to detect unsigned integer values. */
  616. var reIsUint = /^(?:0|[1-9]\d*)$/;
  617. /**
  618. * Checks if `value` is a valid array-like index.
  619. *
  620. * @private
  621. * @param {*} value The value to check.
  622. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  623. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  624. */
  625. function isIndex(value, length) {
  626. var type = typeof value;
  627. length = length == null ? MAX_SAFE_INTEGER$1 : length;
  628. return !!length &&
  629. (type == 'number' ||
  630. (type != 'symbol' && reIsUint.test(value))) &&
  631. (value > -1 && value % 1 == 0 && value < length);
  632. }
  633. /** `Object#toString` result references. */
  634. var argsTag$1 = '[object Arguments]';
  635. var arrayTag = '[object Array]';
  636. var boolTag = '[object Boolean]';
  637. var dateTag = '[object Date]';
  638. var errorTag = '[object Error]';
  639. var funcTag$1 = '[object Function]';
  640. var mapTag = '[object Map]';
  641. var numberTag = '[object Number]';
  642. var objectTag = '[object Object]';
  643. var regexpTag = '[object RegExp]';
  644. var setTag = '[object Set]';
  645. var stringTag = '[object String]';
  646. var weakMapTag = '[object WeakMap]';
  647. var arrayBufferTag = '[object ArrayBuffer]';
  648. var dataViewTag = '[object DataView]';
  649. var float32Tag = '[object Float32Array]';
  650. var float64Tag = '[object Float64Array]';
  651. var int8Tag = '[object Int8Array]';
  652. var int16Tag = '[object Int16Array]';
  653. var int32Tag = '[object Int32Array]';
  654. var uint8Tag = '[object Uint8Array]';
  655. var uint8ClampedTag = '[object Uint8ClampedArray]';
  656. var uint16Tag = '[object Uint16Array]';
  657. var uint32Tag = '[object Uint32Array]';
  658. /** Used to identify `toStringTag` values of typed arrays. */
  659. var typedArrayTags = {};
  660. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  661. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  662. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  663. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  664. typedArrayTags[uint32Tag] = true;
  665. typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
  666. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  667. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  668. typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
  669. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  670. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  671. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  672. typedArrayTags[weakMapTag] = false;
  673. /**
  674. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  675. *
  676. * @private
  677. * @param {*} value The value to check.
  678. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  679. */
  680. function baseIsTypedArray(value) {
  681. return isObjectLike(value) &&
  682. isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
  683. }
  684. /**
  685. * The base implementation of `_.unary` without support for storing metadata.
  686. *
  687. * @private
  688. * @param {Function} func The function to cap arguments for.
  689. * @returns {Function} Returns the new capped function.
  690. */
  691. function baseUnary(func) {
  692. return function(value) {
  693. return func(value);
  694. };
  695. }
  696. /** Detect free variable `exports`. */
  697. var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
  698. /** Detect free variable `module`. */
  699. var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
  700. /** Detect the popular CommonJS extension `module.exports`. */
  701. var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
  702. /** Detect free variable `process` from Node.js. */
  703. var freeProcess = moduleExports$1 && freeGlobal.process;
  704. /** Used to access faster Node.js helpers. */
  705. var nodeUtil = (function() {
  706. try {
  707. // Use `util.types` for Node.js 10+.
  708. var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;
  709. if (types) {
  710. return types;
  711. }
  712. // Legacy `process.binding('util')` for Node.js < 10.
  713. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  714. } catch (e) {}
  715. }());
  716. /* Node.js helper references. */
  717. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  718. /**
  719. * Checks if `value` is classified as a typed array.
  720. *
  721. * @static
  722. * @memberOf _
  723. * @since 3.0.0
  724. * @category Lang
  725. * @param {*} value The value to check.
  726. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  727. * @example
  728. *
  729. * _.isTypedArray(new Uint8Array);
  730. * // => true
  731. *
  732. * _.isTypedArray([]);
  733. * // => false
  734. */
  735. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  736. /** Used for built-in method references. */
  737. var objectProto$2 = Object.prototype;
  738. /** Used to check objects for own properties. */
  739. var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
  740. /**
  741. * Creates an array of the enumerable property names of the array-like `value`.
  742. *
  743. * @private
  744. * @param {*} value The value to query.
  745. * @param {boolean} inherited Specify returning inherited property names.
  746. * @returns {Array} Returns the array of property names.
  747. */
  748. function arrayLikeKeys(value, inherited) {
  749. var isArr = isArray(value),
  750. isArg = !isArr && isArguments(value),
  751. isBuff = !isArr && !isArg && isBuffer(value),
  752. isType = !isArr && !isArg && !isBuff && isTypedArray(value),
  753. skipIndexes = isArr || isArg || isBuff || isType,
  754. result = skipIndexes ? baseTimes(value.length, String) : [],
  755. length = result.length;
  756. for (var key in value) {
  757. if ((inherited || hasOwnProperty$1.call(value, key)) &&
  758. !(skipIndexes && (
  759. // Safari 9 has enumerable `arguments.length` in strict mode.
  760. key == 'length' ||
  761. // Node.js 0.10 has enumerable non-index properties on buffers.
  762. (isBuff && (key == 'offset' || key == 'parent')) ||
  763. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  764. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  765. // Skip index properties.
  766. isIndex(key, length)
  767. ))) {
  768. result.push(key);
  769. }
  770. }
  771. return result;
  772. }
  773. /** Used for built-in method references. */
  774. var objectProto$5 = Object.prototype;
  775. /**
  776. * Checks if `value` is likely a prototype object.
  777. *
  778. * @private
  779. * @param {*} value The value to check.
  780. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  781. */
  782. function isPrototype(value) {
  783. var Ctor = value && value.constructor,
  784. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5;
  785. return value === proto;
  786. }
  787. /**
  788. * Creates a unary function that invokes `func` with its argument transformed.
  789. *
  790. * @private
  791. * @param {Function} func The function to wrap.
  792. * @param {Function} transform The argument transform.
  793. * @returns {Function} Returns the new function.
  794. */
  795. function overArg(func, transform) {
  796. return function(arg) {
  797. return func(transform(arg));
  798. };
  799. }
  800. /* Built-in method references for those with the same name as other `lodash` methods. */
  801. var nativeKeys = overArg(Object.keys, Object);
  802. /** Used for built-in method references. */
  803. var objectProto$4 = Object.prototype;
  804. /** Used to check objects for own properties. */
  805. var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
  806. /**
  807. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  808. *
  809. * @private
  810. * @param {Object} object The object to query.
  811. * @returns {Array} Returns the array of property names.
  812. */
  813. function baseKeys(object) {
  814. if (!isPrototype(object)) {
  815. return nativeKeys(object);
  816. }
  817. var result = [];
  818. for (var key in Object(object)) {
  819. if (hasOwnProperty$3.call(object, key) && key != 'constructor') {
  820. result.push(key);
  821. }
  822. }
  823. return result;
  824. }
  825. /**
  826. * Creates an array of the own enumerable property names of `object`.
  827. *
  828. * **Note:** Non-object values are coerced to objects. See the
  829. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  830. * for more details.
  831. *
  832. * @static
  833. * @since 0.1.0
  834. * @memberOf _
  835. * @category Object
  836. * @param {Object} object The object to query.
  837. * @returns {Array} Returns the array of property names.
  838. * @example
  839. *
  840. * function Foo() {
  841. * this.a = 1;
  842. * this.b = 2;
  843. * }
  844. *
  845. * Foo.prototype.c = 3;
  846. *
  847. * _.keys(new Foo);
  848. * // => ['a', 'b'] (iteration order is not guaranteed)
  849. *
  850. * _.keys('hi');
  851. * // => ['0', '1']
  852. */
  853. function keys(object) {
  854. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  855. }
  856. function createArrayIterator(coll) {
  857. var i = -1;
  858. var len = coll.length;
  859. return function next() {
  860. return ++i < len ? {value: coll[i], key: i} : null;
  861. }
  862. }
  863. function createES2015Iterator(iterator) {
  864. var i = -1;
  865. return function next() {
  866. var item = iterator.next();
  867. if (item.done)
  868. return null;
  869. i++;
  870. return {value: item.value, key: i};
  871. }
  872. }
  873. function createObjectIterator(obj) {
  874. var okeys = keys(obj);
  875. var i = -1;
  876. var len = okeys.length;
  877. return function next() {
  878. var key = okeys[++i];
  879. return i < len ? {value: obj[key], key: key} : null;
  880. };
  881. }
  882. function iterator(coll) {
  883. if (isArrayLike(coll)) {
  884. return createArrayIterator(coll);
  885. }
  886. var iterator = getIterator(coll);
  887. return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
  888. }
  889. function onlyOnce(fn) {
  890. return function() {
  891. if (fn === null) throw new Error("Callback was already called.");
  892. var callFn = fn;
  893. fn = null;
  894. callFn.apply(this, arguments);
  895. };
  896. }
  897. function _eachOfLimit(limit) {
  898. return function (obj, iteratee, callback) {
  899. callback = once(callback || noop);
  900. if (limit <= 0 || !obj) {
  901. return callback(null);
  902. }
  903. var nextElem = iterator(obj);
  904. var done = false;
  905. var running = 0;
  906. var looping = false;
  907. function iterateeCallback(err, value) {
  908. running -= 1;
  909. if (err) {
  910. done = true;
  911. callback(err);
  912. }
  913. else if (value === breakLoop || (done && running <= 0)) {
  914. done = true;
  915. return callback(null);
  916. }
  917. else if (!looping) {
  918. replenish();
  919. }
  920. }
  921. function replenish () {
  922. looping = true;
  923. while (running < limit && !done) {
  924. var elem = nextElem();
  925. if (elem === null) {
  926. done = true;
  927. if (running <= 0) {
  928. callback(null);
  929. }
  930. return;
  931. }
  932. running += 1;
  933. iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
  934. }
  935. looping = false;
  936. }
  937. replenish();
  938. };
  939. }
  940. /**
  941. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
  942. * time.
  943. *
  944. * @name eachOfLimit
  945. * @static
  946. * @memberOf module:Collections
  947. * @method
  948. * @see [async.eachOf]{@link module:Collections.eachOf}
  949. * @alias forEachOfLimit
  950. * @category Collection
  951. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  952. * @param {number} limit - The maximum number of async operations at a time.
  953. * @param {AsyncFunction} iteratee - An async function to apply to each
  954. * item in `coll`. The `key` is the item's key, or index in the case of an
  955. * array.
  956. * Invoked with (item, key, callback).
  957. * @param {Function} [callback] - A callback which is called when all
  958. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  959. */
  960. function eachOfLimit(coll, limit, iteratee, callback) {
  961. _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);
  962. }
  963. function doLimit(fn, limit) {
  964. return function (iterable, iteratee, callback) {
  965. return fn(iterable, limit, iteratee, callback);
  966. };
  967. }
  968. // eachOf implementation optimized for array-likes
  969. function eachOfArrayLike(coll, iteratee, callback) {
  970. callback = once(callback || noop);
  971. var index = 0,
  972. completed = 0,
  973. length = coll.length;
  974. if (length === 0) {
  975. callback(null);
  976. }
  977. function iteratorCallback(err, value) {
  978. if (err) {
  979. callback(err);
  980. } else if ((++completed === length) || value === breakLoop) {
  981. callback(null);
  982. }
  983. }
  984. for (; index < length; index++) {
  985. iteratee(coll[index], index, onlyOnce(iteratorCallback));
  986. }
  987. }
  988. // a generic version of eachOf which can handle array, object, and iterator cases.
  989. var eachOfGeneric = doLimit(eachOfLimit, Infinity);
  990. /**
  991. * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
  992. * to the iteratee.
  993. *
  994. * @name eachOf
  995. * @static
  996. * @memberOf module:Collections
  997. * @method
  998. * @alias forEachOf
  999. * @category Collection
  1000. * @see [async.each]{@link module:Collections.each}
  1001. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  1002. * @param {AsyncFunction} iteratee - A function to apply to each
  1003. * item in `coll`.
  1004. * The `key` is the item's key, or index in the case of an array.
  1005. * Invoked with (item, key, callback).
  1006. * @param {Function} [callback] - A callback which is called when all
  1007. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  1008. * @example
  1009. *
  1010. * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
  1011. * var configs = {};
  1012. *
  1013. * async.forEachOf(obj, function (value, key, callback) {
  1014. * fs.readFile(__dirname + value, "utf8", function (err, data) {
  1015. * if (err) return callback(err);
  1016. * try {
  1017. * configs[key] = JSON.parse(data);
  1018. * } catch (e) {
  1019. * return callback(e);
  1020. * }
  1021. * callback();
  1022. * });
  1023. * }, function (err) {
  1024. * if (err) console.error(err.message);
  1025. * // configs is now a map of JSON data
  1026. * doSomethingWith(configs);
  1027. * });
  1028. */
  1029. var eachOf = function(coll, iteratee, callback) {
  1030. var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
  1031. eachOfImplementation(coll, wrapAsync(iteratee), callback);
  1032. };
  1033. function doParallel(fn) {
  1034. return function (obj, iteratee, callback) {
  1035. return fn(eachOf, obj, wrapAsync(iteratee), callback);
  1036. };
  1037. }
  1038. function _asyncMap(eachfn, arr, iteratee, callback) {
  1039. callback = callback || noop;
  1040. arr = arr || [];
  1041. var results = [];
  1042. var counter = 0;
  1043. var _iteratee = wrapAsync(iteratee);
  1044. eachfn(arr, function (value, _, callback) {
  1045. var index = counter++;
  1046. _iteratee(value, function (err, v) {
  1047. results[index] = v;
  1048. callback(err);
  1049. });
  1050. }, function (err) {
  1051. callback(err, results);
  1052. });
  1053. }
  1054. /**
  1055. * Produces a new collection of values by mapping each value in `coll` through
  1056. * the `iteratee` function. The `iteratee` is called with an item from `coll`
  1057. * and a callback for when it has finished processing. Each of these callback
  1058. * takes 2 arguments: an `error`, and the transformed item from `coll`. If
  1059. * `iteratee` passes an error to its callback, the main `callback` (for the
  1060. * `map` function) is immediately called with the error.
  1061. *
  1062. * Note, that since this function applies the `iteratee` to each item in
  1063. * parallel, there is no guarantee that the `iteratee` functions will complete
  1064. * in order. However, the results array will be in the same order as the
  1065. * original `coll`.
  1066. *
  1067. * If `map` is passed an Object, the results will be an Array. The results
  1068. * will roughly be in the order of the original Objects' keys (but this can
  1069. * vary across JavaScript engines).
  1070. *
  1071. * @name map
  1072. * @static
  1073. * @memberOf module:Collections
  1074. * @method
  1075. * @category Collection
  1076. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  1077. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  1078. * `coll`.
  1079. * The iteratee should complete with the transformed item.
  1080. * Invoked with (item, callback).
  1081. * @param {Function} [callback] - A callback which is called when all `iteratee`
  1082. * functions have finished, or an error occurs. Results is an Array of the
  1083. * transformed items from the `coll`. Invoked with (err, results).
  1084. * @example
  1085. *
  1086. * async.map(['file1','file2','file3'], fs.stat, function(err, results) {
  1087. * // results is now an array of stats for each file
  1088. * });
  1089. */
  1090. var map = doParallel(_asyncMap);
  1091. /**
  1092. * Applies the provided arguments to each function in the array, calling
  1093. * `callback` after all functions have completed. If you only provide the first
  1094. * argument, `fns`, then it will return a function which lets you pass in the
  1095. * arguments as if it were a single function call. If more arguments are
  1096. * provided, `callback` is required while `args` is still optional.
  1097. *
  1098. * @name applyEach
  1099. * @static
  1100. * @memberOf module:ControlFlow
  1101. * @method
  1102. * @category Control Flow
  1103. * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s
  1104. * to all call with the same arguments
  1105. * @param {...*} [args] - any number of separate arguments to pass to the
  1106. * function.
  1107. * @param {Function} [callback] - the final argument should be the callback,
  1108. * called when all functions have completed processing.
  1109. * @returns {Function} - If only the first argument, `fns`, is provided, it will
  1110. * return a function which lets you pass in the arguments as if it were a single
  1111. * function call. The signature is `(..args, callback)`. If invoked with any
  1112. * arguments, `callback` is required.
  1113. * @example
  1114. *
  1115. * async.applyEach([enableSearch, updateSchema], 'bucket', callback);
  1116. *
  1117. * // partial application example:
  1118. * async.each(
  1119. * buckets,
  1120. * async.applyEach([enableSearch, updateSchema]),
  1121. * callback
  1122. * );
  1123. */
  1124. var applyEach = applyEach$1(map);
  1125. function doParallelLimit(fn) {
  1126. return function (obj, limit, iteratee, callback) {
  1127. return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback);
  1128. };
  1129. }
  1130. /**
  1131. * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
  1132. *
  1133. * @name mapLimit
  1134. * @static
  1135. * @memberOf module:Collections
  1136. * @method
  1137. * @see [async.map]{@link module:Collections.map}
  1138. * @category Collection
  1139. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  1140. * @param {number} limit - The maximum number of async operations at a time.
  1141. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  1142. * `coll`.
  1143. * The iteratee should complete with the transformed item.
  1144. * Invoked with (item, callback).
  1145. * @param {Function} [callback] - A callback which is called when all `iteratee`
  1146. * functions have finished, or an error occurs. Results is an array of the
  1147. * transformed items from the `coll`. Invoked with (err, results).
  1148. */
  1149. var mapLimit = doParallelLimit(_asyncMap);
  1150. /**
  1151. * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
  1152. *
  1153. * @name mapSeries
  1154. * @static
  1155. * @memberOf module:Collections
  1156. * @method
  1157. * @see [async.map]{@link module:Collections.map}
  1158. * @category Collection
  1159. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  1160. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  1161. * `coll`.
  1162. * The iteratee should complete with the transformed item.
  1163. * Invoked with (item, callback).
  1164. * @param {Function} [callback] - A callback which is called when all `iteratee`
  1165. * functions have finished, or an error occurs. Results is an array of the
  1166. * transformed items from the `coll`. Invoked with (err, results).
  1167. */
  1168. var mapSeries = doLimit(mapLimit, 1);
  1169. /**
  1170. * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.
  1171. *
  1172. * @name applyEachSeries
  1173. * @static
  1174. * @memberOf module:ControlFlow
  1175. * @method
  1176. * @see [async.applyEach]{@link module:ControlFlow.applyEach}
  1177. * @category Control Flow
  1178. * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all
  1179. * call with the same arguments
  1180. * @param {...*} [args] - any number of separate arguments to pass to the
  1181. * function.
  1182. * @param {Function} [callback] - the final argument should be the callback,
  1183. * called when all functions have completed processing.
  1184. * @returns {Function} - If only the first argument is provided, it will return
  1185. * a function which lets you pass in the arguments as if it were a single
  1186. * function call.
  1187. */
  1188. var applyEachSeries = applyEach$1(mapSeries);
  1189. /**
  1190. * A specialized version of `_.forEach` for arrays without support for
  1191. * iteratee shorthands.
  1192. *
  1193. * @private
  1194. * @param {Array} [array] The array to iterate over.
  1195. * @param {Function} iteratee The function invoked per iteration.
  1196. * @returns {Array} Returns `array`.
  1197. */
  1198. function arrayEach(array, iteratee) {
  1199. var index = -1,
  1200. length = array == null ? 0 : array.length;
  1201. while (++index < length) {
  1202. if (iteratee(array[index], index, array) === false) {
  1203. break;
  1204. }
  1205. }
  1206. return array;
  1207. }
  1208. /**
  1209. * Creates a base function for methods like `_.forIn` and `_.forOwn`.
  1210. *
  1211. * @private
  1212. * @param {boolean} [fromRight] Specify iterating from right to left.
  1213. * @returns {Function} Returns the new base function.
  1214. */
  1215. function createBaseFor(fromRight) {
  1216. return function(object, iteratee, keysFunc) {
  1217. var index = -1,
  1218. iterable = Object(object),
  1219. props = keysFunc(object),
  1220. length = props.length;
  1221. while (length--) {
  1222. var key = props[fromRight ? length : ++index];
  1223. if (iteratee(iterable[key], key, iterable) === false) {
  1224. break;
  1225. }
  1226. }
  1227. return object;
  1228. };
  1229. }
  1230. /**
  1231. * The base implementation of `baseForOwn` which iterates over `object`
  1232. * properties returned by `keysFunc` and invokes `iteratee` for each property.
  1233. * Iteratee functions may exit iteration early by explicitly returning `false`.
  1234. *
  1235. * @private
  1236. * @param {Object} object The object to iterate over.
  1237. * @param {Function} iteratee The function invoked per iteration.
  1238. * @param {Function} keysFunc The function to get the keys of `object`.
  1239. * @returns {Object} Returns `object`.
  1240. */
  1241. var baseFor = createBaseFor();
  1242. /**
  1243. * The base implementation of `_.forOwn` without support for iteratee shorthands.
  1244. *
  1245. * @private
  1246. * @param {Object} object The object to iterate over.
  1247. * @param {Function} iteratee The function invoked per iteration.
  1248. * @returns {Object} Returns `object`.
  1249. */
  1250. function baseForOwn(object, iteratee) {
  1251. return object && baseFor(object, iteratee, keys);
  1252. }
  1253. /**
  1254. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  1255. * support for iteratee shorthands.
  1256. *
  1257. * @private
  1258. * @param {Array} array The array to inspect.
  1259. * @param {Function} predicate The function invoked per iteration.
  1260. * @param {number} fromIndex The index to search from.
  1261. * @param {boolean} [fromRight] Specify iterating from right to left.
  1262. * @returns {number} Returns the index of the matched value, else `-1`.
  1263. */
  1264. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  1265. var length = array.length,
  1266. index = fromIndex + (fromRight ? 1 : -1);
  1267. while ((fromRight ? index-- : ++index < length)) {
  1268. if (predicate(array[index], index, array)) {
  1269. return index;
  1270. }
  1271. }
  1272. return -1;
  1273. }
  1274. /**
  1275. * The base implementation of `_.isNaN` without support for number objects.
  1276. *
  1277. * @private
  1278. * @param {*} value The value to check.
  1279. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  1280. */
  1281. function baseIsNaN(value) {
  1282. return value !== value;
  1283. }
  1284. /**
  1285. * A specialized version of `_.indexOf` which performs strict equality
  1286. * comparisons of values, i.e. `===`.
  1287. *
  1288. * @private
  1289. * @param {Array} array The array to inspect.
  1290. * @param {*} value The value to search for.
  1291. * @param {number} fromIndex The index to search from.
  1292. * @returns {number} Returns the index of the matched value, else `-1`.
  1293. */
  1294. function strictIndexOf(array, value, fromIndex) {
  1295. var index = fromIndex - 1,
  1296. length = array.length;
  1297. while (++index < length) {
  1298. if (array[index] === value) {
  1299. return index;
  1300. }
  1301. }
  1302. return -1;
  1303. }
  1304. /**
  1305. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  1306. *
  1307. * @private
  1308. * @param {Array} array The array to inspect.
  1309. * @param {*} value The value to search for.
  1310. * @param {number} fromIndex The index to search from.
  1311. * @returns {number} Returns the index of the matched value, else `-1`.
  1312. */
  1313. function baseIndexOf(array, value, fromIndex) {
  1314. return value === value
  1315. ? strictIndexOf(array, value, fromIndex)
  1316. : baseFindIndex(array, baseIsNaN, fromIndex);
  1317. }
  1318. /**
  1319. * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on
  1320. * their requirements. Each function can optionally depend on other functions
  1321. * being completed first, and each function is run as soon as its requirements
  1322. * are satisfied.
  1323. *
  1324. * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence
  1325. * will stop. Further tasks will not execute (so any other functions depending
  1326. * on it will not run), and the main `callback` is immediately called with the
  1327. * error.
  1328. *
  1329. * {@link AsyncFunction}s also receive an object containing the results of functions which
  1330. * have completed so far as the first argument, if they have dependencies. If a
  1331. * task function has no dependencies, it will only be passed a callback.
  1332. *
  1333. * @name auto
  1334. * @static
  1335. * @memberOf module:ControlFlow
  1336. * @method
  1337. * @category Control Flow
  1338. * @param {Object} tasks - An object. Each of its properties is either a
  1339. * function or an array of requirements, with the {@link AsyncFunction} itself the last item
  1340. * in the array. The object's key of a property serves as the name of the task
  1341. * defined by that property, i.e. can be used when specifying requirements for
  1342. * other tasks. The function receives one or two arguments:
  1343. * * a `results` object, containing the results of the previously executed
  1344. * functions, only passed if the task has any dependencies,
  1345. * * a `callback(err, result)` function, which must be called when finished,
  1346. * passing an `error` (which can be `null`) and the result of the function's
  1347. * execution.
  1348. * @param {number} [concurrency=Infinity] - An optional `integer` for
  1349. * determining the maximum number of tasks that can be run in parallel. By
  1350. * default, as many as possible.
  1351. * @param {Function} [callback] - An optional callback which is called when all
  1352. * the tasks have been completed. It receives the `err` argument if any `tasks`
  1353. * pass an error to their callback. Results are always returned; however, if an
  1354. * error occurs, no further `tasks` will be performed, and the results object
  1355. * will only contain partial results. Invoked with (err, results).
  1356. * @returns undefined
  1357. * @example
  1358. *
  1359. * async.auto({
  1360. * // this function will just be passed a callback
  1361. * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
  1362. * showData: ['readData', function(results, cb) {
  1363. * // results.readData is the file's contents
  1364. * // ...
  1365. * }]
  1366. * }, callback);
  1367. *
  1368. * async.auto({
  1369. * get_data: function(callback) {
  1370. * console.log('in get_data');
  1371. * // async code to get some data
  1372. * callback(null, 'data', 'converted to array');
  1373. * },
  1374. * make_folder: function(callback) {
  1375. * console.log('in make_folder');
  1376. * // async code to create a directory to store a file in
  1377. * // this is run at the same time as getting the data
  1378. * callback(null, 'folder');
  1379. * },
  1380. * write_file: ['get_data', 'make_folder', function(results, callback) {
  1381. * console.log('in write_file', JSON.stringify(results));
  1382. * // once there is some data and the directory exists,
  1383. * // write the data to a file in the directory
  1384. * callback(null, 'filename');
  1385. * }],
  1386. * email_link: ['write_file', function(results, callback) {
  1387. * console.log('in email_link', JSON.stringify(results));
  1388. * // once the file is written let's email a link to it...
  1389. * // results.write_file contains the filename returned by write_file.
  1390. * callback(null, {'file':results.write_file, 'email':'user@example.com'});
  1391. * }]
  1392. * }, function(err, results) {
  1393. * console.log('err = ', err);
  1394. * console.log('results = ', results);
  1395. * });
  1396. */
  1397. var auto = function (tasks, concurrency, callback) {
  1398. if (typeof concurrency === 'function') {
  1399. // concurrency is optional, shift the args.
  1400. callback = concurrency;
  1401. concurrency = null;
  1402. }
  1403. callback = once(callback || noop);
  1404. var keys$$1 = keys(tasks);
  1405. var numTasks = keys$$1.length;
  1406. if (!numTasks) {
  1407. return callback(null);
  1408. }
  1409. if (!concurrency) {
  1410. concurrency = numTasks;
  1411. }
  1412. var results = {};
  1413. var runningTasks = 0;
  1414. var hasError = false;
  1415. var listeners = Object.create(null);
  1416. var readyTasks = [];
  1417. // for cycle detection:
  1418. var readyToCheck = []; // tasks that have been identified as reachable
  1419. // without the possibility of returning to an ancestor task
  1420. var uncheckedDependencies = {};
  1421. baseForOwn(tasks, function (task, key) {
  1422. if (!isArray(task)) {
  1423. // no dependencies
  1424. enqueueTask(key, [task]);
  1425. readyToCheck.push(key);
  1426. return;
  1427. }
  1428. var dependencies = task.slice(0, task.length - 1);
  1429. var remainingDependencies = dependencies.length;
  1430. if (remainingDependencies === 0) {
  1431. enqueueTask(key, task);
  1432. readyToCheck.push(key);
  1433. return;
  1434. }
  1435. uncheckedDependencies[key] = remainingDependencies;
  1436. arrayEach(dependencies, function (dependencyName) {
  1437. if (!tasks[dependencyName]) {
  1438. throw new Error('async.auto task `' + key +
  1439. '` has a non-existent dependency `' +
  1440. dependencyName + '` in ' +
  1441. dependencies.join(', '));
  1442. }
  1443. addListener(dependencyName, function () {
  1444. remainingDependencies--;
  1445. if (remainingDependencies === 0) {
  1446. enqueueTask(key, task);
  1447. }
  1448. });
  1449. });
  1450. });
  1451. checkForDeadlocks();
  1452. processQueue();
  1453. function enqueueTask(key, task) {
  1454. readyTasks.push(function () {
  1455. runTask(key, task);
  1456. });
  1457. }
  1458. function processQueue() {
  1459. if (readyTasks.length === 0 && runningTasks === 0) {
  1460. return callback(null, results);
  1461. }
  1462. while(readyTasks.length && runningTasks < concurrency) {
  1463. var run = readyTasks.shift();
  1464. run();
  1465. }
  1466. }
  1467. function addListener(taskName, fn) {
  1468. var taskListeners = listeners[taskName];
  1469. if (!taskListeners) {
  1470. taskListeners = listeners[taskName] = [];
  1471. }
  1472. taskListeners.push(fn);
  1473. }
  1474. function taskComplete(taskName) {
  1475. var taskListeners = listeners[taskName] || [];
  1476. arrayEach(taskListeners, function (fn) {
  1477. fn();
  1478. });
  1479. processQueue();
  1480. }
  1481. function runTask(key, task) {
  1482. if (hasError) return;
  1483. var taskCallback = onlyOnce(function(err, result) {
  1484. runningTasks--;
  1485. if (arguments.length > 2) {
  1486. result = slice(arguments, 1);
  1487. }
  1488. if (err) {
  1489. var safeResults = {};
  1490. baseForOwn(results, function(val, rkey) {
  1491. safeResults[rkey] = val;
  1492. });
  1493. safeResults[key] = result;
  1494. hasError = true;
  1495. listeners = Object.create(null);
  1496. callback(err, safeResults);
  1497. } else {
  1498. results[key] = result;
  1499. taskComplete(key);
  1500. }
  1501. });
  1502. runningTasks++;
  1503. var taskFn = wrapAsync(task[task.length - 1]);
  1504. if (task.length > 1) {
  1505. taskFn(results, taskCallback);
  1506. } else {
  1507. taskFn(taskCallback);
  1508. }
  1509. }
  1510. function checkForDeadlocks() {
  1511. // Kahn's algorithm
  1512. // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
  1513. // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
  1514. var currentTask;
  1515. var counter = 0;
  1516. while (readyToCheck.length) {
  1517. currentTask = readyToCheck.pop();
  1518. counter++;
  1519. arrayEach(getDependents(currentTask), function (dependent) {
  1520. if (--uncheckedDependencies[dependent] === 0) {
  1521. readyToCheck.push(dependent);
  1522. }
  1523. });
  1524. }
  1525. if (counter !== numTasks) {
  1526. throw new Error(
  1527. 'async.auto cannot execute tasks due to a recursive dependency'
  1528. );
  1529. }
  1530. }
  1531. function getDependents(taskName) {
  1532. var result = [];
  1533. baseForOwn(tasks, function (task, key) {
  1534. if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) {
  1535. result.push(key);
  1536. }
  1537. });
  1538. return result;
  1539. }
  1540. };
  1541. /**
  1542. * A specialized version of `_.map` for arrays without support for iteratee
  1543. * shorthands.
  1544. *
  1545. * @private
  1546. * @param {Array} [array] The array to iterate over.
  1547. * @param {Function} iteratee The function invoked per iteration.
  1548. * @returns {Array} Returns the new mapped array.
  1549. */
  1550. function arrayMap(array, iteratee) {
  1551. var index = -1,
  1552. length = array == null ? 0 : array.length,
  1553. result = Array(length);
  1554. while (++index < length) {
  1555. result[index] = iteratee(array[index], index, array);
  1556. }
  1557. return result;
  1558. }
  1559. /** `Object#toString` result references. */
  1560. var symbolTag = '[object Symbol]';
  1561. /**
  1562. * Checks if `value` is classified as a `Symbol` primitive or object.
  1563. *
  1564. * @static
  1565. * @memberOf _
  1566. * @since 4.0.0
  1567. * @category Lang
  1568. * @param {*} value The value to check.
  1569. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  1570. * @example
  1571. *
  1572. * _.isSymbol(Symbol.iterator);
  1573. * // => true
  1574. *
  1575. * _.isSymbol('abc');
  1576. * // => false
  1577. */
  1578. function isSymbol(value) {
  1579. return typeof value == 'symbol' ||
  1580. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  1581. }
  1582. /** Used as references for various `Number` constants. */
  1583. var INFINITY = 1 / 0;
  1584. /** Used to convert symbols to primitives and strings. */
  1585. var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined;
  1586. var symbolToString = symbolProto ? symbolProto.toString : undefined;
  1587. /**
  1588. * The base implementation of `_.toString` which doesn't convert nullish
  1589. * values to empty strings.
  1590. *
  1591. * @private
  1592. * @param {*} value The value to process.
  1593. * @returns {string} Returns the string.
  1594. */
  1595. function baseToString(value) {
  1596. // Exit early for strings to avoid a performance hit in some environments.
  1597. if (typeof value == 'string') {
  1598. return value;
  1599. }
  1600. if (isArray(value)) {
  1601. // Recursively convert values (susceptible to call stack limits).
  1602. return arrayMap(value, baseToString) + '';
  1603. }
  1604. if (isSymbol(value)) {
  1605. return symbolToString ? symbolToString.call(value) : '';
  1606. }
  1607. var result = (value + '');
  1608. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  1609. }
  1610. /**
  1611. * The base implementation of `_.slice` without an iteratee call guard.
  1612. *
  1613. * @private
  1614. * @param {Array} array The array to slice.
  1615. * @param {number} [start=0] The start position.
  1616. * @param {number} [end=array.length] The end position.
  1617. * @returns {Array} Returns the slice of `array`.
  1618. */
  1619. function baseSlice(array, start, end) {
  1620. var index = -1,
  1621. length = array.length;
  1622. if (start < 0) {
  1623. start = -start > length ? 0 : (length + start);
  1624. }
  1625. end = end > length ? length : end;
  1626. if (end < 0) {
  1627. end += length;
  1628. }
  1629. length = start > end ? 0 : ((end - start) >>> 0);
  1630. start >>>= 0;
  1631. var result = Array(length);
  1632. while (++index < length) {
  1633. result[index] = array[index + start];
  1634. }
  1635. return result;
  1636. }
  1637. /**
  1638. * Casts `array` to a slice if it's needed.
  1639. *
  1640. * @private
  1641. * @param {Array} array The array to inspect.
  1642. * @param {number} start The start position.
  1643. * @param {number} [end=array.length] The end position.
  1644. * @returns {Array} Returns the cast slice.
  1645. */
  1646. function castSlice(array, start, end) {
  1647. var length = array.length;
  1648. end = end === undefined ? length : end;
  1649. return (!start && end >= length) ? array : baseSlice(array, start, end);
  1650. }
  1651. /**
  1652. * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
  1653. * that is not found in the character symbols.
  1654. *
  1655. * @private
  1656. * @param {Array} strSymbols The string symbols to inspect.
  1657. * @param {Array} chrSymbols The character symbols to find.
  1658. * @returns {number} Returns the index of the last unmatched string symbol.
  1659. */
  1660. function charsEndIndex(strSymbols, chrSymbols) {
  1661. var index = strSymbols.length;
  1662. while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  1663. return index;
  1664. }
  1665. /**
  1666. * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
  1667. * that is not found in the character symbols.
  1668. *
  1669. * @private
  1670. * @param {Array} strSymbols The string symbols to inspect.
  1671. * @param {Array} chrSymbols The character symbols to find.
  1672. * @returns {number} Returns the index of the first unmatched string symbol.
  1673. */
  1674. function charsStartIndex(strSymbols, chrSymbols) {
  1675. var index = -1,
  1676. length = strSymbols.length;
  1677. while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
  1678. return index;
  1679. }
  1680. /**
  1681. * Converts an ASCII `string` to an array.
  1682. *
  1683. * @private
  1684. * @param {string} string The string to convert.
  1685. * @returns {Array} Returns the converted array.
  1686. */
  1687. function asciiToArray(string) {
  1688. return string.split('');
  1689. }
  1690. /** Used to compose unicode character classes. */
  1691. var rsAstralRange = '\\ud800-\\udfff';
  1692. var rsComboMarksRange = '\\u0300-\\u036f';
  1693. var reComboHalfMarksRange = '\\ufe20-\\ufe2f';
  1694. var rsComboSymbolsRange = '\\u20d0-\\u20ff';
  1695. var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
  1696. var rsVarRange = '\\ufe0e\\ufe0f';
  1697. /** Used to compose unicode capture groups. */
  1698. var rsZWJ = '\\u200d';
  1699. /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
  1700. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
  1701. /**
  1702. * Checks if `string` contains Unicode symbols.
  1703. *
  1704. * @private
  1705. * @param {string} string The string to inspect.
  1706. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  1707. */
  1708. function hasUnicode(string) {
  1709. return reHasUnicode.test(string);
  1710. }
  1711. /** Used to compose unicode character classes. */
  1712. var rsAstralRange$1 = '\\ud800-\\udfff';
  1713. var rsComboMarksRange$1 = '\\u0300-\\u036f';
  1714. var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f';
  1715. var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff';
  1716. var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1;
  1717. var rsVarRange$1 = '\\ufe0e\\ufe0f';
  1718. /** Used to compose unicode capture groups. */
  1719. var rsAstral = '[' + rsAstralRange$1 + ']';
  1720. var rsCombo = '[' + rsComboRange$1 + ']';
  1721. var rsFitz = '\\ud83c[\\udffb-\\udfff]';
  1722. var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')';
  1723. var rsNonAstral = '[^' + rsAstralRange$1 + ']';
  1724. var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}';
  1725. var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]';
  1726. var rsZWJ$1 = '\\u200d';
  1727. /** Used to compose unicode regexes. */
  1728. var reOptMod = rsModifier + '?';
  1729. var rsOptVar = '[' + rsVarRange$1 + ']?';
  1730. var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*';
  1731. var rsSeq = rsOptVar + reOptMod + rsOptJoin;
  1732. var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  1733. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  1734. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  1735. /**
  1736. * Converts a Unicode `string` to an array.
  1737. *
  1738. * @private
  1739. * @param {string} string The string to convert.
  1740. * @returns {Array} Returns the converted array.
  1741. */
  1742. function unicodeToArray(string) {
  1743. return string.match(reUnicode) || [];
  1744. }
  1745. /**
  1746. * Converts `string` to an array.
  1747. *
  1748. * @private
  1749. * @param {string} string The string to convert.
  1750. * @returns {Array} Returns the converted array.
  1751. */
  1752. function stringToArray(string) {
  1753. return hasUnicode(string)
  1754. ? unicodeToArray(string)
  1755. : asciiToArray(string);
  1756. }
  1757. /**
  1758. * Converts `value` to a string. An empty string is returned for `null`
  1759. * and `undefined` values. The sign of `-0` is preserved.
  1760. *
  1761. * @static
  1762. * @memberOf _
  1763. * @since 4.0.0
  1764. * @category Lang
  1765. * @param {*} value The value to convert.
  1766. * @returns {string} Returns the converted string.
  1767. * @example
  1768. *
  1769. * _.toString(null);
  1770. * // => ''
  1771. *
  1772. * _.toString(-0);
  1773. * // => '-0'
  1774. *
  1775. * _.toString([1, 2, 3]);
  1776. * // => '1,2,3'
  1777. */
  1778. function toString(value) {
  1779. return value == null ? '' : baseToString(value);
  1780. }
  1781. /** Used to match leading and trailing whitespace. */
  1782. var reTrim = /^\s+|\s+$/g;
  1783. /**
  1784. * Removes leading and trailing whitespace or specified characters from `string`.
  1785. *
  1786. * @static
  1787. * @memberOf _
  1788. * @since 3.0.0
  1789. * @category String
  1790. * @param {string} [string=''] The string to trim.
  1791. * @param {string} [chars=whitespace] The characters to trim.
  1792. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  1793. * @returns {string} Returns the trimmed string.
  1794. * @example
  1795. *
  1796. * _.trim(' abc ');
  1797. * // => 'abc'
  1798. *
  1799. * _.trim('-_-abc-_-', '_-');
  1800. * // => 'abc'
  1801. *
  1802. * _.map([' foo ', ' bar '], _.trim);
  1803. * // => ['foo', 'bar']
  1804. */
  1805. function trim(string, chars, guard) {
  1806. string = toString(string);
  1807. if (string && (guard || chars === undefined)) {
  1808. return string.replace(reTrim, '');
  1809. }
  1810. if (!string || !(chars = baseToString(chars))) {
  1811. return string;
  1812. }
  1813. var strSymbols = stringToArray(string),
  1814. chrSymbols = stringToArray(chars),
  1815. start = charsStartIndex(strSymbols, chrSymbols),
  1816. end = charsEndIndex(strSymbols, chrSymbols) + 1;
  1817. return castSlice(strSymbols, start, end).join('');
  1818. }
  1819. var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m;
  1820. var FN_ARG_SPLIT = /,/;
  1821. var FN_ARG = /(=.+)?(\s*)$/;
  1822. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  1823. function parseParams(func) {
  1824. func = func.toString().replace(STRIP_COMMENTS, '');
  1825. func = func.match(FN_ARGS)[2].replace(' ', '');
  1826. func = func ? func.split(FN_ARG_SPLIT) : [];
  1827. func = func.map(function (arg){
  1828. return trim(arg.replace(FN_ARG, ''));
  1829. });
  1830. return func;
  1831. }
  1832. /**
  1833. * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent
  1834. * tasks are specified as parameters to the function, after the usual callback
  1835. * parameter, with the parameter names matching the names of the tasks it
  1836. * depends on. This can provide even more readable task graphs which can be
  1837. * easier to maintain.
  1838. *
  1839. * If a final callback is specified, the task results are similarly injected,
  1840. * specified as named parameters after the initial error parameter.
  1841. *
  1842. * The autoInject function is purely syntactic sugar and its semantics are
  1843. * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.
  1844. *
  1845. * @name autoInject
  1846. * @static
  1847. * @memberOf module:ControlFlow
  1848. * @method
  1849. * @see [async.auto]{@link module:ControlFlow.auto}
  1850. * @category Control Flow
  1851. * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of
  1852. * the form 'func([dependencies...], callback). The object's key of a property
  1853. * serves as the name of the task defined by that property, i.e. can be used
  1854. * when specifying requirements for other tasks.
  1855. * * The `callback` parameter is a `callback(err, result)` which must be called
  1856. * when finished, passing an `error` (which can be `null`) and the result of
  1857. * the function's execution. The remaining parameters name other tasks on
  1858. * which the task is dependent, and the results from those tasks are the
  1859. * arguments of those parameters.
  1860. * @param {Function} [callback] - An optional callback which is called when all
  1861. * the tasks have been completed. It receives the `err` argument if any `tasks`
  1862. * pass an error to their callback, and a `results` object with any completed
  1863. * task results, similar to `auto`.
  1864. * @example
  1865. *
  1866. * // The example from `auto` can be rewritten as follows:
  1867. * async.autoInject({
  1868. * get_data: function(callback) {
  1869. * // async code to get some data
  1870. * callback(null, 'data', 'converted to array');
  1871. * },
  1872. * make_folder: function(callback) {
  1873. * // async code to create a directory to store a file in
  1874. * // this is run at the same time as getting the data
  1875. * callback(null, 'folder');
  1876. * },
  1877. * write_file: function(get_data, make_folder, callback) {
  1878. * // once there is some data and the directory exists,
  1879. * // write the data to a file in the directory
  1880. * callback(null, 'filename');
  1881. * },
  1882. * email_link: function(write_file, callback) {
  1883. * // once the file is written let's email a link to it...
  1884. * // write_file contains the filename returned by write_file.
  1885. * callback(null, {'file':write_file, 'email':'user@example.com'});
  1886. * }
  1887. * }, function(err, results) {
  1888. * console.log('err = ', err);
  1889. * console.log('email_link = ', results.email_link);
  1890. * });
  1891. *
  1892. * // If you are using a JS minifier that mangles parameter names, `autoInject`
  1893. * // will not work with plain functions, since the parameter names will be
  1894. * // collapsed to a single letter identifier. To work around this, you can
  1895. * // explicitly specify the names of the parameters your task function needs
  1896. * // in an array, similar to Angular.js dependency injection.
  1897. *
  1898. * // This still has an advantage over plain `auto`, since the results a task
  1899. * // depends on are still spread into arguments.
  1900. * async.autoInject({
  1901. * //...
  1902. * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
  1903. * callback(null, 'filename');
  1904. * }],
  1905. * email_link: ['write_file', function(write_file, callback) {
  1906. * callback(null, {'file':write_file, 'email':'user@example.com'});
  1907. * }]
  1908. * //...
  1909. * }, function(err, results) {
  1910. * console.log('err = ', err);
  1911. * console.log('email_link = ', results.email_link);
  1912. * });
  1913. */
  1914. function autoInject(tasks, callback) {
  1915. var newTasks = {};
  1916. baseForOwn(tasks, function (taskFn, key) {
  1917. var params;
  1918. var fnIsAsync = isAsync(taskFn);
  1919. var hasNoDeps =
  1920. (!fnIsAsync && taskFn.length === 1) ||
  1921. (fnIsAsync && taskFn.length === 0);
  1922. if (isArray(taskFn)) {
  1923. params = taskFn.slice(0, -1);
  1924. taskFn = taskFn[taskFn.length - 1];
  1925. newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
  1926. } else if (hasNoDeps) {
  1927. // no dependencies, use the function as-is
  1928. newTasks[key] = taskFn;
  1929. } else {
  1930. params = parseParams(taskFn);
  1931. if (taskFn.length === 0 && !fnIsAsync && params.length === 0) {
  1932. throw new Error("autoInject task functions require explicit parameters.");
  1933. }
  1934. // remove callback param
  1935. if (!fnIsAsync) params.pop();
  1936. newTasks[key] = params.concat(newTask);
  1937. }
  1938. function newTask(results, taskCb) {
  1939. var newArgs = arrayMap(params, function (name) {
  1940. return results[name];
  1941. });
  1942. newArgs.push(taskCb);
  1943. wrapAsync(taskFn).apply(null, newArgs);
  1944. }
  1945. });
  1946. auto(newTasks, callback);
  1947. }
  1948. // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
  1949. // used for queues. This implementation assumes that the node provided by the user can be modified
  1950. // to adjust the next and last properties. We implement only the minimal functionality
  1951. // for queue support.
  1952. function DLL() {
  1953. this.head = this.tail = null;
  1954. this.length = 0;
  1955. }
  1956. function setInitial(dll, node) {
  1957. dll.length = 1;
  1958. dll.head = dll.tail = node;
  1959. }
  1960. DLL.prototype.removeLink = function(node) {
  1961. if (node.prev) node.prev.next = node.next;
  1962. else this.head = node.next;
  1963. if (node.next) node.next.prev = node.prev;
  1964. else this.tail = node.prev;
  1965. node.prev = node.next = null;
  1966. this.length -= 1;
  1967. return node;
  1968. };
  1969. DLL.prototype.empty = function () {
  1970. while(this.head) this.shift();
  1971. return this;
  1972. };
  1973. DLL.prototype.insertAfter = function(node, newNode) {
  1974. newNode.prev = node;
  1975. newNode.next = node.next;
  1976. if (node.next) node.next.prev = newNode;
  1977. else this.tail = newNode;
  1978. node.next = newNode;
  1979. this.length += 1;
  1980. };
  1981. DLL.prototype.insertBefore = function(node, newNode) {
  1982. newNode.prev = node.prev;
  1983. newNode.next = node;
  1984. if (node.prev) node.prev.next = newNode;
  1985. else this.head = newNode;
  1986. node.prev = newNode;
  1987. this.length += 1;
  1988. };
  1989. DLL.prototype.unshift = function(node) {
  1990. if (this.head) this.insertBefore(this.head, node);
  1991. else setInitial(this, node);
  1992. };
  1993. DLL.prototype.push = function(node) {
  1994. if (this.tail) this.insertAfter(this.tail, node);
  1995. else setInitial(this, node);
  1996. };
  1997. DLL.prototype.shift = function() {
  1998. return this.head && this.removeLink(this.head);
  1999. };
  2000. DLL.prototype.pop = function() {
  2001. return this.tail && this.removeLink(this.tail);
  2002. };
  2003. DLL.prototype.toArray = function () {
  2004. var arr = Array(this.length);
  2005. var curr = this.head;
  2006. for(var idx = 0; idx < this.length; idx++) {
  2007. arr[idx] = curr.data;
  2008. curr = curr.next;
  2009. }
  2010. return arr;
  2011. };
  2012. DLL.prototype.remove = function (testFn) {
  2013. var curr = this.head;
  2014. while(!!curr) {
  2015. var next = curr.next;
  2016. if (testFn(curr)) {
  2017. this.removeLink(curr);
  2018. }
  2019. curr = next;
  2020. }
  2021. return this;
  2022. };
  2023. function queue(worker, concurrency, payload) {
  2024. if (concurrency == null) {
  2025. concurrency = 1;
  2026. }
  2027. else if(concurrency === 0) {
  2028. throw new Error('Concurrency must not be zero');
  2029. }
  2030. var _worker = wrapAsync(worker);
  2031. var numRunning = 0;
  2032. var workersList = [];
  2033. var processingScheduled = false;
  2034. function _insert(data, insertAtFront, callback) {
  2035. if (callback != null && typeof callback !== 'function') {
  2036. throw new Error('task callback must be a function');
  2037. }
  2038. q.started = true;
  2039. if (!isArray(data)) {
  2040. data = [data];
  2041. }
  2042. if (data.length === 0 && q.idle()) {
  2043. // call drain immediately if there are no tasks
  2044. return setImmediate$1(function() {
  2045. q.drain();
  2046. });
  2047. }
  2048. for (var i = 0, l = data.length; i < l; i++) {
  2049. var item = {
  2050. data: data[i],
  2051. callback: callback || noop
  2052. };
  2053. if (insertAtFront) {
  2054. q._tasks.unshift(item);
  2055. } else {
  2056. q._tasks.push(item);
  2057. }
  2058. }
  2059. if (!processingScheduled) {
  2060. processingScheduled = true;
  2061. setImmediate$1(function() {
  2062. processingScheduled = false;
  2063. q.process();
  2064. });
  2065. }
  2066. }
  2067. function _next(tasks) {
  2068. return function(err){
  2069. numRunning -= 1;
  2070. for (var i = 0, l = tasks.length; i < l; i++) {
  2071. var task = tasks[i];
  2072. var index = baseIndexOf(workersList, task, 0);
  2073. if (index === 0) {
  2074. workersList.shift();
  2075. } else if (index > 0) {
  2076. workersList.splice(index, 1);
  2077. }
  2078. task.callback.apply(task, arguments);
  2079. if (err != null) {
  2080. q.error(err, task.data);
  2081. }
  2082. }
  2083. if (numRunning <= (q.concurrency - q.buffer) ) {
  2084. q.unsaturated();
  2085. }
  2086. if (q.idle()) {
  2087. q.drain();
  2088. }
  2089. q.process();
  2090. };
  2091. }
  2092. var isProcessing = false;
  2093. var q = {
  2094. _tasks: new DLL(),
  2095. concurrency: concurrency,
  2096. payload: payload,
  2097. saturated: noop,
  2098. unsaturated:noop,
  2099. buffer: concurrency / 4,
  2100. empty: noop,
  2101. drain: noop,
  2102. error: noop,
  2103. started: false,
  2104. paused: false,
  2105. push: function (data, callback) {
  2106. _insert(data, false, callback);
  2107. },
  2108. kill: function () {
  2109. q.drain = noop;
  2110. q._tasks.empty();
  2111. },
  2112. unshift: function (data, callback) {
  2113. _insert(data, true, callback);
  2114. },
  2115. remove: function (testFn) {
  2116. q._tasks.remove(testFn);
  2117. },
  2118. process: function () {
  2119. // Avoid trying to start too many processing operations. This can occur
  2120. // when callbacks resolve synchronously (#1267).
  2121. if (isProcessing) {
  2122. return;
  2123. }
  2124. isProcessing = true;
  2125. while(!q.paused && numRunning < q.concurrency && q._tasks.length){
  2126. var tasks = [], data = [];
  2127. var l = q._tasks.length;
  2128. if (q.payload) l = Math.min(l, q.payload);
  2129. for (var i = 0; i < l; i++) {
  2130. var node = q._tasks.shift();
  2131. tasks.push(node);
  2132. workersList.push(node);
  2133. data.push(node.data);
  2134. }
  2135. numRunning += 1;
  2136. if (q._tasks.length === 0) {
  2137. q.empty();
  2138. }
  2139. if (numRunning === q.concurrency) {
  2140. q.saturated();
  2141. }
  2142. var cb = onlyOnce(_next(tasks));
  2143. _worker(data, cb);
  2144. }
  2145. isProcessing = false;
  2146. },
  2147. length: function () {
  2148. return q._tasks.length;
  2149. },
  2150. running: function () {
  2151. return numRunning;
  2152. },
  2153. workersList: function () {
  2154. return workersList;
  2155. },
  2156. idle: function() {
  2157. return q._tasks.length + numRunning === 0;
  2158. },
  2159. pause: function () {
  2160. q.paused = true;
  2161. },
  2162. resume: function () {
  2163. if (q.paused === false) { return; }
  2164. q.paused = false;
  2165. setImmediate$1(q.process);
  2166. }
  2167. };
  2168. return q;
  2169. }
  2170. /**
  2171. * A cargo of tasks for the worker function to complete. Cargo inherits all of
  2172. * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}.
  2173. * @typedef {Object} CargoObject
  2174. * @memberOf module:ControlFlow
  2175. * @property {Function} length - A function returning the number of items
  2176. * waiting to be processed. Invoke like `cargo.length()`.
  2177. * @property {number} payload - An `integer` for determining how many tasks
  2178. * should be process per round. This property can be changed after a `cargo` is
  2179. * created to alter the payload on-the-fly.
  2180. * @property {Function} push - Adds `task` to the `queue`. The callback is
  2181. * called once the `worker` has finished processing the task. Instead of a
  2182. * single task, an array of `tasks` can be submitted. The respective callback is
  2183. * used for every task in the list. Invoke like `cargo.push(task, [callback])`.
  2184. * @property {Function} saturated - A callback that is called when the
  2185. * `queue.length()` hits the concurrency and further tasks will be queued.
  2186. * @property {Function} empty - A callback that is called when the last item
  2187. * from the `queue` is given to a `worker`.
  2188. * @property {Function} drain - A callback that is called when the last item
  2189. * from the `queue` has returned from the `worker`.
  2190. * @property {Function} idle - a function returning false if there are items
  2191. * waiting or being processed, or true if not. Invoke like `cargo.idle()`.
  2192. * @property {Function} pause - a function that pauses the processing of tasks
  2193. * until `resume()` is called. Invoke like `cargo.pause()`.
  2194. * @property {Function} resume - a function that resumes the processing of
  2195. * queued tasks when the queue is paused. Invoke like `cargo.resume()`.
  2196. * @property {Function} kill - a function that removes the `drain` callback and
  2197. * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`.
  2198. */
  2199. /**
  2200. * Creates a `cargo` object with the specified payload. Tasks added to the
  2201. * cargo will be processed altogether (up to the `payload` limit). If the
  2202. * `worker` is in progress, the task is queued until it becomes available. Once
  2203. * the `worker` has completed some tasks, each callback of those tasks is
  2204. * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
  2205. * for how `cargo` and `queue` work.
  2206. *
  2207. * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
  2208. * at a time, cargo passes an array of tasks to a single worker, repeating
  2209. * when the worker is finished.
  2210. *
  2211. * @name cargo
  2212. * @static
  2213. * @memberOf module:ControlFlow
  2214. * @method
  2215. * @see [async.queue]{@link module:ControlFlow.queue}
  2216. * @category Control Flow
  2217. * @param {AsyncFunction} worker - An asynchronous function for processing an array
  2218. * of queued tasks. Invoked with `(tasks, callback)`.
  2219. * @param {number} [payload=Infinity] - An optional `integer` for determining
  2220. * how many tasks should be processed per round; if omitted, the default is
  2221. * unlimited.
  2222. * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can
  2223. * attached as certain properties to listen for specific events during the
  2224. * lifecycle of the cargo and inner queue.
  2225. * @example
  2226. *
  2227. * // create a cargo object with payload 2
  2228. * var cargo = async.cargo(function(tasks, callback) {
  2229. * for (var i=0; i<tasks.length; i++) {
  2230. * console.log('hello ' + tasks[i].name);
  2231. * }
  2232. * callback();
  2233. * }, 2);
  2234. *
  2235. * // add some items
  2236. * cargo.push({name: 'foo'}, function(err) {
  2237. * console.log('finished processing foo');
  2238. * });
  2239. * cargo.push({name: 'bar'}, function(err) {
  2240. * console.log('finished processing bar');
  2241. * });
  2242. * cargo.push({name: 'baz'}, function(err) {
  2243. * console.log('finished processing baz');
  2244. * });
  2245. */
  2246. function cargo(worker, payload) {
  2247. return queue(worker, 1, payload);
  2248. }
  2249. /**
  2250. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
  2251. *
  2252. * @name eachOfSeries
  2253. * @static
  2254. * @memberOf module:Collections
  2255. * @method
  2256. * @see [async.eachOf]{@link module:Collections.eachOf}
  2257. * @alias forEachOfSeries
  2258. * @category Collection
  2259. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2260. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  2261. * `coll`.
  2262. * Invoked with (item, key, callback).
  2263. * @param {Function} [callback] - A callback which is called when all `iteratee`
  2264. * functions have finished, or an error occurs. Invoked with (err).
  2265. */
  2266. var eachOfSeries = doLimit(eachOfLimit, 1);
  2267. /**
  2268. * Reduces `coll` into a single value using an async `iteratee` to return each
  2269. * successive step. `memo` is the initial state of the reduction. This function
  2270. * only operates in series.
  2271. *
  2272. * For performance reasons, it may make sense to split a call to this function
  2273. * into a parallel map, and then use the normal `Array.prototype.reduce` on the
  2274. * results. This function is for situations where each step in the reduction
  2275. * needs to be async; if you can get the data before reducing it, then it's
  2276. * probably a good idea to do so.
  2277. *
  2278. * @name reduce
  2279. * @static
  2280. * @memberOf module:Collections
  2281. * @method
  2282. * @alias inject
  2283. * @alias foldl
  2284. * @category Collection
  2285. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2286. * @param {*} memo - The initial state of the reduction.
  2287. * @param {AsyncFunction} iteratee - A function applied to each item in the
  2288. * array to produce the next step in the reduction.
  2289. * The `iteratee` should complete with the next state of the reduction.
  2290. * If the iteratee complete with an error, the reduction is stopped and the
  2291. * main `callback` is immediately called with the error.
  2292. * Invoked with (memo, item, callback).
  2293. * @param {Function} [callback] - A callback which is called after all the
  2294. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  2295. * (err, result).
  2296. * @example
  2297. *
  2298. * async.reduce([1,2,3], 0, function(memo, item, callback) {
  2299. * // pointless async:
  2300. * process.nextTick(function() {
  2301. * callback(null, memo + item)
  2302. * });
  2303. * }, function(err, result) {
  2304. * // result is now equal to the last value of memo, which is 6
  2305. * });
  2306. */
  2307. function reduce(coll, memo, iteratee, callback) {
  2308. callback = once(callback || noop);
  2309. var _iteratee = wrapAsync(iteratee);
  2310. eachOfSeries(coll, function(x, i, callback) {
  2311. _iteratee(memo, x, function(err, v) {
  2312. memo = v;
  2313. callback(err);
  2314. });
  2315. }, function(err) {
  2316. callback(err, memo);
  2317. });
  2318. }
  2319. /**
  2320. * Version of the compose function that is more natural to read. Each function
  2321. * consumes the return value of the previous function. It is the equivalent of
  2322. * [compose]{@link module:ControlFlow.compose} with the arguments reversed.
  2323. *
  2324. * Each function is executed with the `this` binding of the composed function.
  2325. *
  2326. * @name seq
  2327. * @static
  2328. * @memberOf module:ControlFlow
  2329. * @method
  2330. * @see [async.compose]{@link module:ControlFlow.compose}
  2331. * @category Control Flow
  2332. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  2333. * @returns {Function} a function that composes the `functions` in order
  2334. * @example
  2335. *
  2336. * // Requires lodash (or underscore), express3 and dresende's orm2.
  2337. * // Part of an app, that fetches cats of the logged user.
  2338. * // This example uses `seq` function to avoid overnesting and error
  2339. * // handling clutter.
  2340. * app.get('/cats', function(request, response) {
  2341. * var User = request.models.User;
  2342. * async.seq(
  2343. * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
  2344. * function(user, fn) {
  2345. * user.getCats(fn); // 'getCats' has signature (callback(err, data))
  2346. * }
  2347. * )(req.session.user_id, function (err, cats) {
  2348. * if (err) {
  2349. * console.error(err);
  2350. * response.json({ status: 'error', message: err.message });
  2351. * } else {
  2352. * response.json({ status: 'ok', message: 'Cats found', data: cats });
  2353. * }
  2354. * });
  2355. * });
  2356. */
  2357. function seq(/*...functions*/) {
  2358. var _functions = arrayMap(arguments, wrapAsync);
  2359. return function(/*...args*/) {
  2360. var args = slice(arguments);
  2361. var that = this;
  2362. var cb = args[args.length - 1];
  2363. if (typeof cb == 'function') {
  2364. args.pop();
  2365. } else {
  2366. cb = noop;
  2367. }
  2368. reduce(_functions, args, function(newargs, fn, cb) {
  2369. fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) {
  2370. var nextargs = slice(arguments, 1);
  2371. cb(err, nextargs);
  2372. }));
  2373. },
  2374. function(err, results) {
  2375. cb.apply(that, [err].concat(results));
  2376. });
  2377. };
  2378. }
  2379. /**
  2380. * Creates a function which is a composition of the passed asynchronous
  2381. * functions. Each function consumes the return value of the function that
  2382. * follows. Composing functions `f()`, `g()`, and `h()` would produce the result
  2383. * of `f(g(h()))`, only this version uses callbacks to obtain the return values.
  2384. *
  2385. * Each function is executed with the `this` binding of the composed function.
  2386. *
  2387. * @name compose
  2388. * @static
  2389. * @memberOf module:ControlFlow
  2390. * @method
  2391. * @category Control Flow
  2392. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  2393. * @returns {Function} an asynchronous function that is the composed
  2394. * asynchronous `functions`
  2395. * @example
  2396. *
  2397. * function add1(n, callback) {
  2398. * setTimeout(function () {
  2399. * callback(null, n + 1);
  2400. * }, 10);
  2401. * }
  2402. *
  2403. * function mul3(n, callback) {
  2404. * setTimeout(function () {
  2405. * callback(null, n * 3);
  2406. * }, 10);
  2407. * }
  2408. *
  2409. * var add1mul3 = async.compose(mul3, add1);
  2410. * add1mul3(4, function (err, result) {
  2411. * // result now equals 15
  2412. * });
  2413. */
  2414. var compose = function(/*...args*/) {
  2415. return seq.apply(null, slice(arguments).reverse());
  2416. };
  2417. var _concat = Array.prototype.concat;
  2418. /**
  2419. * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
  2420. *
  2421. * @name concatLimit
  2422. * @static
  2423. * @memberOf module:Collections
  2424. * @method
  2425. * @see [async.concat]{@link module:Collections.concat}
  2426. * @category Collection
  2427. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2428. * @param {number} limit - The maximum number of async operations at a time.
  2429. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  2430. * which should use an array as its result. Invoked with (item, callback).
  2431. * @param {Function} [callback] - A callback which is called after all the
  2432. * `iteratee` functions have finished, or an error occurs. Results is an array
  2433. * containing the concatenated results of the `iteratee` function. Invoked with
  2434. * (err, results).
  2435. */
  2436. var concatLimit = function(coll, limit, iteratee, callback) {
  2437. callback = callback || noop;
  2438. var _iteratee = wrapAsync(iteratee);
  2439. mapLimit(coll, limit, function(val, callback) {
  2440. _iteratee(val, function(err /*, ...args*/) {
  2441. if (err) return callback(err);
  2442. return callback(null, slice(arguments, 1));
  2443. });
  2444. }, function(err, mapResults) {
  2445. var result = [];
  2446. for (var i = 0; i < mapResults.length; i++) {
  2447. if (mapResults[i]) {
  2448. result = _concat.apply(result, mapResults[i]);
  2449. }
  2450. }
  2451. return callback(err, result);
  2452. });
  2453. };
  2454. /**
  2455. * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
  2456. * the concatenated list. The `iteratee`s are called in parallel, and the
  2457. * results are concatenated as they return. There is no guarantee that the
  2458. * results array will be returned in the original order of `coll` passed to the
  2459. * `iteratee` function.
  2460. *
  2461. * @name concat
  2462. * @static
  2463. * @memberOf module:Collections
  2464. * @method
  2465. * @category Collection
  2466. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2467. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  2468. * which should use an array as its result. Invoked with (item, callback).
  2469. * @param {Function} [callback(err)] - A callback which is called after all the
  2470. * `iteratee` functions have finished, or an error occurs. Results is an array
  2471. * containing the concatenated results of the `iteratee` function. Invoked with
  2472. * (err, results).
  2473. * @example
  2474. *
  2475. * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
  2476. * // files is now a list of filenames that exist in the 3 directories
  2477. * });
  2478. */
  2479. var concat = doLimit(concatLimit, Infinity);
  2480. /**
  2481. * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
  2482. *
  2483. * @name concatSeries
  2484. * @static
  2485. * @memberOf module:Collections
  2486. * @method
  2487. * @see [async.concat]{@link module:Collections.concat}
  2488. * @category Collection
  2489. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2490. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
  2491. * The iteratee should complete with an array an array of results.
  2492. * Invoked with (item, callback).
  2493. * @param {Function} [callback(err)] - A callback which is called after all the
  2494. * `iteratee` functions have finished, or an error occurs. Results is an array
  2495. * containing the concatenated results of the `iteratee` function. Invoked with
  2496. * (err, results).
  2497. */
  2498. var concatSeries = doLimit(concatLimit, 1);
  2499. /**
  2500. * Returns a function that when called, calls-back with the values provided.
  2501. * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
  2502. * [`auto`]{@link module:ControlFlow.auto}.
  2503. *
  2504. * @name constant
  2505. * @static
  2506. * @memberOf module:Utils
  2507. * @method
  2508. * @category Util
  2509. * @param {...*} arguments... - Any number of arguments to automatically invoke
  2510. * callback with.
  2511. * @returns {AsyncFunction} Returns a function that when invoked, automatically
  2512. * invokes the callback with the previous given arguments.
  2513. * @example
  2514. *
  2515. * async.waterfall([
  2516. * async.constant(42),
  2517. * function (value, next) {
  2518. * // value === 42
  2519. * },
  2520. * //...
  2521. * ], callback);
  2522. *
  2523. * async.waterfall([
  2524. * async.constant(filename, "utf8"),
  2525. * fs.readFile,
  2526. * function (fileData, next) {
  2527. * //...
  2528. * }
  2529. * //...
  2530. * ], callback);
  2531. *
  2532. * async.auto({
  2533. * hostname: async.constant("https://server.net/"),
  2534. * port: findFreePort,
  2535. * launchServer: ["hostname", "port", function (options, cb) {
  2536. * startServer(options, cb);
  2537. * }],
  2538. * //...
  2539. * }, callback);
  2540. */
  2541. var constant = function(/*...values*/) {
  2542. var values = slice(arguments);
  2543. var args = [null].concat(values);
  2544. return function (/*...ignoredArgs, callback*/) {
  2545. var callback = arguments[arguments.length - 1];
  2546. return callback.apply(this, args);
  2547. };
  2548. };
  2549. /**
  2550. * This method returns the first argument it receives.
  2551. *
  2552. * @static
  2553. * @since 0.1.0
  2554. * @memberOf _
  2555. * @category Util
  2556. * @param {*} value Any value.
  2557. * @returns {*} Returns `value`.
  2558. * @example
  2559. *
  2560. * var object = { 'a': 1 };
  2561. *
  2562. * console.log(_.identity(object) === object);
  2563. * // => true
  2564. */
  2565. function identity(value) {
  2566. return value;
  2567. }
  2568. function _createTester(check, getResult) {
  2569. return function(eachfn, arr, iteratee, cb) {
  2570. cb = cb || noop;
  2571. var testPassed = false;
  2572. var testResult;
  2573. eachfn(arr, function(value, _, callback) {
  2574. iteratee(value, function(err, result) {
  2575. if (err) {
  2576. callback(err);
  2577. } else if (check(result) && !testResult) {
  2578. testPassed = true;
  2579. testResult = getResult(true, value);
  2580. callback(null, breakLoop);
  2581. } else {
  2582. callback();
  2583. }
  2584. });
  2585. }, function(err) {
  2586. if (err) {
  2587. cb(err);
  2588. } else {
  2589. cb(null, testPassed ? testResult : getResult(false));
  2590. }
  2591. });
  2592. };
  2593. }
  2594. function _findGetResult(v, x) {
  2595. return x;
  2596. }
  2597. /**
  2598. * Returns the first value in `coll` that passes an async truth test. The
  2599. * `iteratee` is applied in parallel, meaning the first iteratee to return
  2600. * `true` will fire the detect `callback` with that result. That means the
  2601. * result might not be the first item in the original `coll` (in terms of order)
  2602. * that passes the test.
  2603. * If order within the original `coll` is important, then look at
  2604. * [`detectSeries`]{@link module:Collections.detectSeries}.
  2605. *
  2606. * @name detect
  2607. * @static
  2608. * @memberOf module:Collections
  2609. * @method
  2610. * @alias find
  2611. * @category Collections
  2612. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2613. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  2614. * The iteratee must complete with a boolean value as its result.
  2615. * Invoked with (item, callback).
  2616. * @param {Function} [callback] - A callback which is called as soon as any
  2617. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  2618. * Result will be the first item in the array that passes the truth test
  2619. * (iteratee) or the value `undefined` if none passed. Invoked with
  2620. * (err, result).
  2621. * @example
  2622. *
  2623. * async.detect(['file1','file2','file3'], function(filePath, callback) {
  2624. * fs.access(filePath, function(err) {
  2625. * callback(null, !err)
  2626. * });
  2627. * }, function(err, result) {
  2628. * // result now equals the first file in the list that exists
  2629. * });
  2630. */
  2631. var detect = doParallel(_createTester(identity, _findGetResult));
  2632. /**
  2633. * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
  2634. * time.
  2635. *
  2636. * @name detectLimit
  2637. * @static
  2638. * @memberOf module:Collections
  2639. * @method
  2640. * @see [async.detect]{@link module:Collections.detect}
  2641. * @alias findLimit
  2642. * @category Collections
  2643. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2644. * @param {number} limit - The maximum number of async operations at a time.
  2645. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  2646. * The iteratee must complete with a boolean value as its result.
  2647. * Invoked with (item, callback).
  2648. * @param {Function} [callback] - A callback which is called as soon as any
  2649. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  2650. * Result will be the first item in the array that passes the truth test
  2651. * (iteratee) or the value `undefined` if none passed. Invoked with
  2652. * (err, result).
  2653. */
  2654. var detectLimit = doParallelLimit(_createTester(identity, _findGetResult));
  2655. /**
  2656. * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
  2657. *
  2658. * @name detectSeries
  2659. * @static
  2660. * @memberOf module:Collections
  2661. * @method
  2662. * @see [async.detect]{@link module:Collections.detect}
  2663. * @alias findSeries
  2664. * @category Collections
  2665. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2666. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  2667. * The iteratee must complete with a boolean value as its result.
  2668. * Invoked with (item, callback).
  2669. * @param {Function} [callback] - A callback which is called as soon as any
  2670. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  2671. * Result will be the first item in the array that passes the truth test
  2672. * (iteratee) or the value `undefined` if none passed. Invoked with
  2673. * (err, result).
  2674. */
  2675. var detectSeries = doLimit(detectLimit, 1);
  2676. function consoleFunc(name) {
  2677. return function (fn/*, ...args*/) {
  2678. var args = slice(arguments, 1);
  2679. args.push(function (err/*, ...args*/) {
  2680. var args = slice(arguments, 1);
  2681. if (typeof console === 'object') {
  2682. if (err) {
  2683. if (console.error) {
  2684. console.error(err);
  2685. }
  2686. } else if (console[name]) {
  2687. arrayEach(args, function (x) {
  2688. console[name](x);
  2689. });
  2690. }
  2691. }
  2692. });
  2693. wrapAsync(fn).apply(null, args);
  2694. };
  2695. }
  2696. /**
  2697. * Logs the result of an [`async` function]{@link AsyncFunction} to the
  2698. * `console` using `console.dir` to display the properties of the resulting object.
  2699. * Only works in Node.js or in browsers that support `console.dir` and
  2700. * `console.error` (such as FF and Chrome).
  2701. * If multiple arguments are returned from the async function,
  2702. * `console.dir` is called on each argument in order.
  2703. *
  2704. * @name dir
  2705. * @static
  2706. * @memberOf module:Utils
  2707. * @method
  2708. * @category Util
  2709. * @param {AsyncFunction} function - The function you want to eventually apply
  2710. * all arguments to.
  2711. * @param {...*} arguments... - Any number of arguments to apply to the function.
  2712. * @example
  2713. *
  2714. * // in a module
  2715. * var hello = function(name, callback) {
  2716. * setTimeout(function() {
  2717. * callback(null, {hello: name});
  2718. * }, 1000);
  2719. * };
  2720. *
  2721. * // in the node repl
  2722. * node> async.dir(hello, 'world');
  2723. * {hello: 'world'}
  2724. */
  2725. var dir = consoleFunc('dir');
  2726. /**
  2727. * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in
  2728. * the order of operations, the arguments `test` and `fn` are switched.
  2729. *
  2730. * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function.
  2731. * @name doDuring
  2732. * @static
  2733. * @memberOf module:ControlFlow
  2734. * @method
  2735. * @see [async.during]{@link module:ControlFlow.during}
  2736. * @category Control Flow
  2737. * @param {AsyncFunction} fn - An async function which is called each time
  2738. * `test` passes. Invoked with (callback).
  2739. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  2740. * execution of `fn`. Invoked with (...args, callback), where `...args` are the
  2741. * non-error args from the previous callback of `fn`.
  2742. * @param {Function} [callback] - A callback which is called after the test
  2743. * function has failed and repeated execution of `fn` has stopped. `callback`
  2744. * will be passed an error if one occurred, otherwise `null`.
  2745. */
  2746. function doDuring(fn, test, callback) {
  2747. callback = onlyOnce(callback || noop);
  2748. var _fn = wrapAsync(fn);
  2749. var _test = wrapAsync(test);
  2750. function next(err/*, ...args*/) {
  2751. if (err) return callback(err);
  2752. var args = slice(arguments, 1);
  2753. args.push(check);
  2754. _test.apply(this, args);
  2755. }
  2756. function check(err, truth) {
  2757. if (err) return callback(err);
  2758. if (!truth) return callback(null);
  2759. _fn(next);
  2760. }
  2761. check(null, true);
  2762. }
  2763. /**
  2764. * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
  2765. * the order of operations, the arguments `test` and `iteratee` are switched.
  2766. *
  2767. * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
  2768. *
  2769. * @name doWhilst
  2770. * @static
  2771. * @memberOf module:ControlFlow
  2772. * @method
  2773. * @see [async.whilst]{@link module:ControlFlow.whilst}
  2774. * @category Control Flow
  2775. * @param {AsyncFunction} iteratee - A function which is called each time `test`
  2776. * passes. Invoked with (callback).
  2777. * @param {Function} test - synchronous truth test to perform after each
  2778. * execution of `iteratee`. Invoked with any non-error callback results of
  2779. * `iteratee`.
  2780. * @param {Function} [callback] - A callback which is called after the test
  2781. * function has failed and repeated execution of `iteratee` has stopped.
  2782. * `callback` will be passed an error and any arguments passed to the final
  2783. * `iteratee`'s callback. Invoked with (err, [results]);
  2784. */
  2785. function doWhilst(iteratee, test, callback) {
  2786. callback = onlyOnce(callback || noop);
  2787. var _iteratee = wrapAsync(iteratee);
  2788. var next = function(err/*, ...args*/) {
  2789. if (err) return callback(err);
  2790. var args = slice(arguments, 1);
  2791. if (test.apply(this, args)) return _iteratee(next);
  2792. callback.apply(null, [null].concat(args));
  2793. };
  2794. _iteratee(next);
  2795. }
  2796. /**
  2797. * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the
  2798. * argument ordering differs from `until`.
  2799. *
  2800. * @name doUntil
  2801. * @static
  2802. * @memberOf module:ControlFlow
  2803. * @method
  2804. * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}
  2805. * @category Control Flow
  2806. * @param {AsyncFunction} iteratee - An async function which is called each time
  2807. * `test` fails. Invoked with (callback).
  2808. * @param {Function} test - synchronous truth test to perform after each
  2809. * execution of `iteratee`. Invoked with any non-error callback results of
  2810. * `iteratee`.
  2811. * @param {Function} [callback] - A callback which is called after the test
  2812. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  2813. * will be passed an error and any arguments passed to the final `iteratee`'s
  2814. * callback. Invoked with (err, [results]);
  2815. */
  2816. function doUntil(iteratee, test, callback) {
  2817. doWhilst(iteratee, function() {
  2818. return !test.apply(this, arguments);
  2819. }, callback);
  2820. }
  2821. /**
  2822. * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that
  2823. * is passed a callback in the form of `function (err, truth)`. If error is
  2824. * passed to `test` or `fn`, the main callback is immediately called with the
  2825. * value of the error.
  2826. *
  2827. * @name during
  2828. * @static
  2829. * @memberOf module:ControlFlow
  2830. * @method
  2831. * @see [async.whilst]{@link module:ControlFlow.whilst}
  2832. * @category Control Flow
  2833. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  2834. * execution of `fn`. Invoked with (callback).
  2835. * @param {AsyncFunction} fn - An async function which is called each time
  2836. * `test` passes. Invoked with (callback).
  2837. * @param {Function} [callback] - A callback which is called after the test
  2838. * function has failed and repeated execution of `fn` has stopped. `callback`
  2839. * will be passed an error, if one occurred, otherwise `null`.
  2840. * @example
  2841. *
  2842. * var count = 0;
  2843. *
  2844. * async.during(
  2845. * function (callback) {
  2846. * return callback(null, count < 5);
  2847. * },
  2848. * function (callback) {
  2849. * count++;
  2850. * setTimeout(callback, 1000);
  2851. * },
  2852. * function (err) {
  2853. * // 5 seconds have passed
  2854. * }
  2855. * );
  2856. */
  2857. function during(test, fn, callback) {
  2858. callback = onlyOnce(callback || noop);
  2859. var _fn = wrapAsync(fn);
  2860. var _test = wrapAsync(test);
  2861. function next(err) {
  2862. if (err) return callback(err);
  2863. _test(check);
  2864. }
  2865. function check(err, truth) {
  2866. if (err) return callback(err);
  2867. if (!truth) return callback(null);
  2868. _fn(next);
  2869. }
  2870. _test(check);
  2871. }
  2872. function _withoutIndex(iteratee) {
  2873. return function (value, index, callback) {
  2874. return iteratee(value, callback);
  2875. };
  2876. }
  2877. /**
  2878. * Applies the function `iteratee` to each item in `coll`, in parallel.
  2879. * The `iteratee` is called with an item from the list, and a callback for when
  2880. * it has finished. If the `iteratee` passes an error to its `callback`, the
  2881. * main `callback` (for the `each` function) is immediately called with the
  2882. * error.
  2883. *
  2884. * Note, that since this function applies `iteratee` to each item in parallel,
  2885. * there is no guarantee that the iteratee functions will complete in order.
  2886. *
  2887. * @name each
  2888. * @static
  2889. * @memberOf module:Collections
  2890. * @method
  2891. * @alias forEach
  2892. * @category Collection
  2893. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2894. * @param {AsyncFunction} iteratee - An async function to apply to
  2895. * each item in `coll`. Invoked with (item, callback).
  2896. * The array index is not passed to the iteratee.
  2897. * If you need the index, use `eachOf`.
  2898. * @param {Function} [callback] - A callback which is called when all
  2899. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  2900. * @example
  2901. *
  2902. * // assuming openFiles is an array of file names and saveFile is a function
  2903. * // to save the modified contents of that file:
  2904. *
  2905. * async.each(openFiles, saveFile, function(err){
  2906. * // if any of the saves produced an error, err would equal that error
  2907. * });
  2908. *
  2909. * // assuming openFiles is an array of file names
  2910. * async.each(openFiles, function(file, callback) {
  2911. *
  2912. * // Perform operation on file here.
  2913. * console.log('Processing file ' + file);
  2914. *
  2915. * if( file.length > 32 ) {
  2916. * console.log('This file name is too long');
  2917. * callback('File name too long');
  2918. * } else {
  2919. * // Do work to process file here
  2920. * console.log('File processed');
  2921. * callback();
  2922. * }
  2923. * }, function(err) {
  2924. * // if any of the file processing produced an error, err would equal that error
  2925. * if( err ) {
  2926. * // One of the iterations produced an error.
  2927. * // All processing will now stop.
  2928. * console.log('A file failed to process');
  2929. * } else {
  2930. * console.log('All files have been processed successfully');
  2931. * }
  2932. * });
  2933. */
  2934. function eachLimit(coll, iteratee, callback) {
  2935. eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  2936. }
  2937. /**
  2938. * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
  2939. *
  2940. * @name eachLimit
  2941. * @static
  2942. * @memberOf module:Collections
  2943. * @method
  2944. * @see [async.each]{@link module:Collections.each}
  2945. * @alias forEachLimit
  2946. * @category Collection
  2947. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2948. * @param {number} limit - The maximum number of async operations at a time.
  2949. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  2950. * `coll`.
  2951. * The array index is not passed to the iteratee.
  2952. * If you need the index, use `eachOfLimit`.
  2953. * Invoked with (item, callback).
  2954. * @param {Function} [callback] - A callback which is called when all
  2955. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  2956. */
  2957. function eachLimit$1(coll, limit, iteratee, callback) {
  2958. _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  2959. }
  2960. /**
  2961. * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
  2962. *
  2963. * @name eachSeries
  2964. * @static
  2965. * @memberOf module:Collections
  2966. * @method
  2967. * @see [async.each]{@link module:Collections.each}
  2968. * @alias forEachSeries
  2969. * @category Collection
  2970. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  2971. * @param {AsyncFunction} iteratee - An async function to apply to each
  2972. * item in `coll`.
  2973. * The array index is not passed to the iteratee.
  2974. * If you need the index, use `eachOfSeries`.
  2975. * Invoked with (item, callback).
  2976. * @param {Function} [callback] - A callback which is called when all
  2977. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  2978. */
  2979. var eachSeries = doLimit(eachLimit$1, 1);
  2980. /**
  2981. * Wrap an async function and ensure it calls its callback on a later tick of
  2982. * the event loop. If the function already calls its callback on a next tick,
  2983. * no extra deferral is added. This is useful for preventing stack overflows
  2984. * (`RangeError: Maximum call stack size exceeded`) and generally keeping
  2985. * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
  2986. * contained. ES2017 `async` functions are returned as-is -- they are immune
  2987. * to Zalgo's corrupting influences, as they always resolve on a later tick.
  2988. *
  2989. * @name ensureAsync
  2990. * @static
  2991. * @memberOf module:Utils
  2992. * @method
  2993. * @category Util
  2994. * @param {AsyncFunction} fn - an async function, one that expects a node-style
  2995. * callback as its last argument.
  2996. * @returns {AsyncFunction} Returns a wrapped function with the exact same call
  2997. * signature as the function passed in.
  2998. * @example
  2999. *
  3000. * function sometimesAsync(arg, callback) {
  3001. * if (cache[arg]) {
  3002. * return callback(null, cache[arg]); // this would be synchronous!!
  3003. * } else {
  3004. * doSomeIO(arg, callback); // this IO would be asynchronous
  3005. * }
  3006. * }
  3007. *
  3008. * // this has a risk of stack overflows if many results are cached in a row
  3009. * async.mapSeries(args, sometimesAsync, done);
  3010. *
  3011. * // this will defer sometimesAsync's callback if necessary,
  3012. * // preventing stack overflows
  3013. * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
  3014. */
  3015. function ensureAsync(fn) {
  3016. if (isAsync(fn)) return fn;
  3017. return initialParams(function (args, callback) {
  3018. var sync = true;
  3019. args.push(function () {
  3020. var innerArgs = arguments;
  3021. if (sync) {
  3022. setImmediate$1(function () {
  3023. callback.apply(null, innerArgs);
  3024. });
  3025. } else {
  3026. callback.apply(null, innerArgs);
  3027. }
  3028. });
  3029. fn.apply(this, args);
  3030. sync = false;
  3031. });
  3032. }
  3033. function notId(v) {
  3034. return !v;
  3035. }
  3036. /**
  3037. * Returns `true` if every element in `coll` satisfies an async test. If any
  3038. * iteratee call returns `false`, the main `callback` is immediately called.
  3039. *
  3040. * @name every
  3041. * @static
  3042. * @memberOf module:Collections
  3043. * @method
  3044. * @alias all
  3045. * @category Collection
  3046. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3047. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  3048. * in the collection in parallel.
  3049. * The iteratee must complete with a boolean result value.
  3050. * Invoked with (item, callback).
  3051. * @param {Function} [callback] - A callback which is called after all the
  3052. * `iteratee` functions have finished. Result will be either `true` or `false`
  3053. * depending on the values of the async tests. Invoked with (err, result).
  3054. * @example
  3055. *
  3056. * async.every(['file1','file2','file3'], function(filePath, callback) {
  3057. * fs.access(filePath, function(err) {
  3058. * callback(null, !err)
  3059. * });
  3060. * }, function(err, result) {
  3061. * // if result is true then every file exists
  3062. * });
  3063. */
  3064. var every = doParallel(_createTester(notId, notId));
  3065. /**
  3066. * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
  3067. *
  3068. * @name everyLimit
  3069. * @static
  3070. * @memberOf module:Collections
  3071. * @method
  3072. * @see [async.every]{@link module:Collections.every}
  3073. * @alias allLimit
  3074. * @category Collection
  3075. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3076. * @param {number} limit - The maximum number of async operations at a time.
  3077. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  3078. * in the collection in parallel.
  3079. * The iteratee must complete with a boolean result value.
  3080. * Invoked with (item, callback).
  3081. * @param {Function} [callback] - A callback which is called after all the
  3082. * `iteratee` functions have finished. Result will be either `true` or `false`
  3083. * depending on the values of the async tests. Invoked with (err, result).
  3084. */
  3085. var everyLimit = doParallelLimit(_createTester(notId, notId));
  3086. /**
  3087. * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
  3088. *
  3089. * @name everySeries
  3090. * @static
  3091. * @memberOf module:Collections
  3092. * @method
  3093. * @see [async.every]{@link module:Collections.every}
  3094. * @alias allSeries
  3095. * @category Collection
  3096. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3097. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  3098. * in the collection in series.
  3099. * The iteratee must complete with a boolean result value.
  3100. * Invoked with (item, callback).
  3101. * @param {Function} [callback] - A callback which is called after all the
  3102. * `iteratee` functions have finished. Result will be either `true` or `false`
  3103. * depending on the values of the async tests. Invoked with (err, result).
  3104. */
  3105. var everySeries = doLimit(everyLimit, 1);
  3106. /**
  3107. * The base implementation of `_.property` without support for deep paths.
  3108. *
  3109. * @private
  3110. * @param {string} key The key of the property to get.
  3111. * @returns {Function} Returns the new accessor function.
  3112. */
  3113. function baseProperty(key) {
  3114. return function(object) {
  3115. return object == null ? undefined : object[key];
  3116. };
  3117. }
  3118. function filterArray(eachfn, arr, iteratee, callback) {
  3119. var truthValues = new Array(arr.length);
  3120. eachfn(arr, function (x, index, callback) {
  3121. iteratee(x, function (err, v) {
  3122. truthValues[index] = !!v;
  3123. callback(err);
  3124. });
  3125. }, function (err) {
  3126. if (err) return callback(err);
  3127. var results = [];
  3128. for (var i = 0; i < arr.length; i++) {
  3129. if (truthValues[i]) results.push(arr[i]);
  3130. }
  3131. callback(null, results);
  3132. });
  3133. }
  3134. function filterGeneric(eachfn, coll, iteratee, callback) {
  3135. var results = [];
  3136. eachfn(coll, function (x, index, callback) {
  3137. iteratee(x, function (err, v) {
  3138. if (err) {
  3139. callback(err);
  3140. } else {
  3141. if (v) {
  3142. results.push({index: index, value: x});
  3143. }
  3144. callback();
  3145. }
  3146. });
  3147. }, function (err) {
  3148. if (err) {
  3149. callback(err);
  3150. } else {
  3151. callback(null, arrayMap(results.sort(function (a, b) {
  3152. return a.index - b.index;
  3153. }), baseProperty('value')));
  3154. }
  3155. });
  3156. }
  3157. function _filter(eachfn, coll, iteratee, callback) {
  3158. var filter = isArrayLike(coll) ? filterArray : filterGeneric;
  3159. filter(eachfn, coll, wrapAsync(iteratee), callback || noop);
  3160. }
  3161. /**
  3162. * Returns a new array of all the values in `coll` which pass an async truth
  3163. * test. This operation is performed in parallel, but the results array will be
  3164. * in the same order as the original.
  3165. *
  3166. * @name filter
  3167. * @static
  3168. * @memberOf module:Collections
  3169. * @method
  3170. * @alias select
  3171. * @category Collection
  3172. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3173. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  3174. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  3175. * with a boolean argument once it has completed. Invoked with (item, callback).
  3176. * @param {Function} [callback] - A callback which is called after all the
  3177. * `iteratee` functions have finished. Invoked with (err, results).
  3178. * @example
  3179. *
  3180. * async.filter(['file1','file2','file3'], function(filePath, callback) {
  3181. * fs.access(filePath, function(err) {
  3182. * callback(null, !err)
  3183. * });
  3184. * }, function(err, results) {
  3185. * // results now equals an array of the existing files
  3186. * });
  3187. */
  3188. var filter = doParallel(_filter);
  3189. /**
  3190. * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
  3191. * time.
  3192. *
  3193. * @name filterLimit
  3194. * @static
  3195. * @memberOf module:Collections
  3196. * @method
  3197. * @see [async.filter]{@link module:Collections.filter}
  3198. * @alias selectLimit
  3199. * @category Collection
  3200. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3201. * @param {number} limit - The maximum number of async operations at a time.
  3202. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  3203. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  3204. * with a boolean argument once it has completed. Invoked with (item, callback).
  3205. * @param {Function} [callback] - A callback which is called after all the
  3206. * `iteratee` functions have finished. Invoked with (err, results).
  3207. */
  3208. var filterLimit = doParallelLimit(_filter);
  3209. /**
  3210. * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
  3211. *
  3212. * @name filterSeries
  3213. * @static
  3214. * @memberOf module:Collections
  3215. * @method
  3216. * @see [async.filter]{@link module:Collections.filter}
  3217. * @alias selectSeries
  3218. * @category Collection
  3219. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3220. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  3221. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  3222. * with a boolean argument once it has completed. Invoked with (item, callback).
  3223. * @param {Function} [callback] - A callback which is called after all the
  3224. * `iteratee` functions have finished. Invoked with (err, results)
  3225. */
  3226. var filterSeries = doLimit(filterLimit, 1);
  3227. /**
  3228. * Calls the asynchronous function `fn` with a callback parameter that allows it
  3229. * to call itself again, in series, indefinitely.
  3230. * If an error is passed to the callback then `errback` is called with the
  3231. * error, and execution stops, otherwise it will never be called.
  3232. *
  3233. * @name forever
  3234. * @static
  3235. * @memberOf module:ControlFlow
  3236. * @method
  3237. * @category Control Flow
  3238. * @param {AsyncFunction} fn - an async function to call repeatedly.
  3239. * Invoked with (next).
  3240. * @param {Function} [errback] - when `fn` passes an error to it's callback,
  3241. * this function will be called, and execution stops. Invoked with (err).
  3242. * @example
  3243. *
  3244. * async.forever(
  3245. * function(next) {
  3246. * // next is suitable for passing to things that need a callback(err [, whatever]);
  3247. * // it will result in this function being called again.
  3248. * },
  3249. * function(err) {
  3250. * // if next is called with a value in its first parameter, it will appear
  3251. * // in here as 'err', and execution will stop.
  3252. * }
  3253. * );
  3254. */
  3255. function forever(fn, errback) {
  3256. var done = onlyOnce(errback || noop);
  3257. var task = wrapAsync(ensureAsync(fn));
  3258. function next(err) {
  3259. if (err) return done(err);
  3260. task(next);
  3261. }
  3262. next();
  3263. }
  3264. /**
  3265. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
  3266. *
  3267. * @name groupByLimit
  3268. * @static
  3269. * @memberOf module:Collections
  3270. * @method
  3271. * @see [async.groupBy]{@link module:Collections.groupBy}
  3272. * @category Collection
  3273. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3274. * @param {number} limit - The maximum number of async operations at a time.
  3275. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  3276. * `coll`.
  3277. * The iteratee should complete with a `key` to group the value under.
  3278. * Invoked with (value, callback).
  3279. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3280. * functions have finished, or an error occurs. Result is an `Object` whoses
  3281. * properties are arrays of values which returned the corresponding key.
  3282. */
  3283. var groupByLimit = function(coll, limit, iteratee, callback) {
  3284. callback = callback || noop;
  3285. var _iteratee = wrapAsync(iteratee);
  3286. mapLimit(coll, limit, function(val, callback) {
  3287. _iteratee(val, function(err, key) {
  3288. if (err) return callback(err);
  3289. return callback(null, {key: key, val: val});
  3290. });
  3291. }, function(err, mapResults) {
  3292. var result = {};
  3293. // from MDN, handle object having an `hasOwnProperty` prop
  3294. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3295. for (var i = 0; i < mapResults.length; i++) {
  3296. if (mapResults[i]) {
  3297. var key = mapResults[i].key;
  3298. var val = mapResults[i].val;
  3299. if (hasOwnProperty.call(result, key)) {
  3300. result[key].push(val);
  3301. } else {
  3302. result[key] = [val];
  3303. }
  3304. }
  3305. }
  3306. return callback(err, result);
  3307. });
  3308. };
  3309. /**
  3310. * Returns a new object, where each value corresponds to an array of items, from
  3311. * `coll`, that returned the corresponding key. That is, the keys of the object
  3312. * correspond to the values passed to the `iteratee` callback.
  3313. *
  3314. * Note: Since this function applies the `iteratee` to each item in parallel,
  3315. * there is no guarantee that the `iteratee` functions will complete in order.
  3316. * However, the values for each key in the `result` will be in the same order as
  3317. * the original `coll`. For Objects, the values will roughly be in the order of
  3318. * the original Objects' keys (but this can vary across JavaScript engines).
  3319. *
  3320. * @name groupBy
  3321. * @static
  3322. * @memberOf module:Collections
  3323. * @method
  3324. * @category Collection
  3325. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3326. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  3327. * `coll`.
  3328. * The iteratee should complete with a `key` to group the value under.
  3329. * Invoked with (value, callback).
  3330. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3331. * functions have finished, or an error occurs. Result is an `Object` whoses
  3332. * properties are arrays of values which returned the corresponding key.
  3333. * @example
  3334. *
  3335. * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {
  3336. * db.findById(userId, function(err, user) {
  3337. * if (err) return callback(err);
  3338. * return callback(null, user.age);
  3339. * });
  3340. * }, function(err, result) {
  3341. * // result is object containing the userIds grouped by age
  3342. * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};
  3343. * });
  3344. */
  3345. var groupBy = doLimit(groupByLimit, Infinity);
  3346. /**
  3347. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.
  3348. *
  3349. * @name groupBySeries
  3350. * @static
  3351. * @memberOf module:Collections
  3352. * @method
  3353. * @see [async.groupBy]{@link module:Collections.groupBy}
  3354. * @category Collection
  3355. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  3356. * @param {number} limit - The maximum number of async operations at a time.
  3357. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  3358. * `coll`.
  3359. * The iteratee should complete with a `key` to group the value under.
  3360. * Invoked with (value, callback).
  3361. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3362. * functions have finished, or an error occurs. Result is an `Object` whoses
  3363. * properties are arrays of values which returned the corresponding key.
  3364. */
  3365. var groupBySeries = doLimit(groupByLimit, 1);
  3366. /**
  3367. * Logs the result of an `async` function to the `console`. Only works in
  3368. * Node.js or in browsers that support `console.log` and `console.error` (such
  3369. * as FF and Chrome). If multiple arguments are returned from the async
  3370. * function, `console.log` is called on each argument in order.
  3371. *
  3372. * @name log
  3373. * @static
  3374. * @memberOf module:Utils
  3375. * @method
  3376. * @category Util
  3377. * @param {AsyncFunction} function - The function you want to eventually apply
  3378. * all arguments to.
  3379. * @param {...*} arguments... - Any number of arguments to apply to the function.
  3380. * @example
  3381. *
  3382. * // in a module
  3383. * var hello = function(name, callback) {
  3384. * setTimeout(function() {
  3385. * callback(null, 'hello ' + name);
  3386. * }, 1000);
  3387. * };
  3388. *
  3389. * // in the node repl
  3390. * node> async.log(hello, 'world');
  3391. * 'hello world'
  3392. */
  3393. var log = consoleFunc('log');
  3394. /**
  3395. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
  3396. * time.
  3397. *
  3398. * @name mapValuesLimit
  3399. * @static
  3400. * @memberOf module:Collections
  3401. * @method
  3402. * @see [async.mapValues]{@link module:Collections.mapValues}
  3403. * @category Collection
  3404. * @param {Object} obj - A collection to iterate over.
  3405. * @param {number} limit - The maximum number of async operations at a time.
  3406. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  3407. * in `coll`.
  3408. * The iteratee should complete with the transformed value as its result.
  3409. * Invoked with (value, key, callback).
  3410. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3411. * functions have finished, or an error occurs. `result` is a new object consisting
  3412. * of each key from `obj`, with each transformed value on the right-hand side.
  3413. * Invoked with (err, result).
  3414. */
  3415. function mapValuesLimit(obj, limit, iteratee, callback) {
  3416. callback = once(callback || noop);
  3417. var newObj = {};
  3418. var _iteratee = wrapAsync(iteratee);
  3419. eachOfLimit(obj, limit, function(val, key, next) {
  3420. _iteratee(val, key, function (err, result) {
  3421. if (err) return next(err);
  3422. newObj[key] = result;
  3423. next();
  3424. });
  3425. }, function (err) {
  3426. callback(err, newObj);
  3427. });
  3428. }
  3429. /**
  3430. * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.
  3431. *
  3432. * Produces a new Object by mapping each value of `obj` through the `iteratee`
  3433. * function. The `iteratee` is called each `value` and `key` from `obj` and a
  3434. * callback for when it has finished processing. Each of these callbacks takes
  3435. * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`
  3436. * passes an error to its callback, the main `callback` (for the `mapValues`
  3437. * function) is immediately called with the error.
  3438. *
  3439. * Note, the order of the keys in the result is not guaranteed. The keys will
  3440. * be roughly in the order they complete, (but this is very engine-specific)
  3441. *
  3442. * @name mapValues
  3443. * @static
  3444. * @memberOf module:Collections
  3445. * @method
  3446. * @category Collection
  3447. * @param {Object} obj - A collection to iterate over.
  3448. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  3449. * in `coll`.
  3450. * The iteratee should complete with the transformed value as its result.
  3451. * Invoked with (value, key, callback).
  3452. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3453. * functions have finished, or an error occurs. `result` is a new object consisting
  3454. * of each key from `obj`, with each transformed value on the right-hand side.
  3455. * Invoked with (err, result).
  3456. * @example
  3457. *
  3458. * async.mapValues({
  3459. * f1: 'file1',
  3460. * f2: 'file2',
  3461. * f3: 'file3'
  3462. * }, function (file, key, callback) {
  3463. * fs.stat(file, callback);
  3464. * }, function(err, result) {
  3465. * // result is now a map of stats for each file, e.g.
  3466. * // {
  3467. * // f1: [stats for file1],
  3468. * // f2: [stats for file2],
  3469. * // f3: [stats for file3]
  3470. * // }
  3471. * });
  3472. */
  3473. var mapValues = doLimit(mapValuesLimit, Infinity);
  3474. /**
  3475. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.
  3476. *
  3477. * @name mapValuesSeries
  3478. * @static
  3479. * @memberOf module:Collections
  3480. * @method
  3481. * @see [async.mapValues]{@link module:Collections.mapValues}
  3482. * @category Collection
  3483. * @param {Object} obj - A collection to iterate over.
  3484. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  3485. * in `coll`.
  3486. * The iteratee should complete with the transformed value as its result.
  3487. * Invoked with (value, key, callback).
  3488. * @param {Function} [callback] - A callback which is called when all `iteratee`
  3489. * functions have finished, or an error occurs. `result` is a new object consisting
  3490. * of each key from `obj`, with each transformed value on the right-hand side.
  3491. * Invoked with (err, result).
  3492. */
  3493. var mapValuesSeries = doLimit(mapValuesLimit, 1);
  3494. function has(obj, key) {
  3495. return key in obj;
  3496. }
  3497. /**
  3498. * Caches the results of an async function. When creating a hash to store
  3499. * function results against, the callback is omitted from the hash and an
  3500. * optional hash function can be used.
  3501. *
  3502. * If no hash function is specified, the first argument is used as a hash key,
  3503. * which may work reasonably if it is a string or a data type that converts to a
  3504. * distinct string. Note that objects and arrays will not behave reasonably.
  3505. * Neither will cases where the other arguments are significant. In such cases,
  3506. * specify your own hash function.
  3507. *
  3508. * The cache of results is exposed as the `memo` property of the function
  3509. * returned by `memoize`.
  3510. *
  3511. * @name memoize
  3512. * @static
  3513. * @memberOf module:Utils
  3514. * @method
  3515. * @category Util
  3516. * @param {AsyncFunction} fn - The async function to proxy and cache results from.
  3517. * @param {Function} hasher - An optional function for generating a custom hash
  3518. * for storing results. It has all the arguments applied to it apart from the
  3519. * callback, and must be synchronous.
  3520. * @returns {AsyncFunction} a memoized version of `fn`
  3521. * @example
  3522. *
  3523. * var slow_fn = function(name, callback) {
  3524. * // do something
  3525. * callback(null, result);
  3526. * };
  3527. * var fn = async.memoize(slow_fn);
  3528. *
  3529. * // fn can now be used as if it were slow_fn
  3530. * fn('some name', function() {
  3531. * // callback
  3532. * });
  3533. */
  3534. function memoize(fn, hasher) {
  3535. var memo = Object.create(null);
  3536. var queues = Object.create(null);
  3537. hasher = hasher || identity;
  3538. var _fn = wrapAsync(fn);
  3539. var memoized = initialParams(function memoized(args, callback) {
  3540. var key = hasher.apply(null, args);
  3541. if (has(memo, key)) {
  3542. setImmediate$1(function() {
  3543. callback.apply(null, memo[key]);
  3544. });
  3545. } else if (has(queues, key)) {
  3546. queues[key].push(callback);
  3547. } else {
  3548. queues[key] = [callback];
  3549. _fn.apply(null, args.concat(function(/*args*/) {
  3550. var args = slice(arguments);
  3551. memo[key] = args;
  3552. var q = queues[key];
  3553. delete queues[key];
  3554. for (var i = 0, l = q.length; i < l; i++) {
  3555. q[i].apply(null, args);
  3556. }
  3557. }));
  3558. }
  3559. });
  3560. memoized.memo = memo;
  3561. memoized.unmemoized = fn;
  3562. return memoized;
  3563. }
  3564. /**
  3565. * Calls `callback` on a later loop around the event loop. In Node.js this just
  3566. * calls `process.nextTick`. In the browser it will use `setImmediate` if
  3567. * available, otherwise `setTimeout(callback, 0)`, which means other higher
  3568. * priority events may precede the execution of `callback`.
  3569. *
  3570. * This is used internally for browser-compatibility purposes.
  3571. *
  3572. * @name nextTick
  3573. * @static
  3574. * @memberOf module:Utils
  3575. * @method
  3576. * @see [async.setImmediate]{@link module:Utils.setImmediate}
  3577. * @category Util
  3578. * @param {Function} callback - The function to call on a later loop around
  3579. * the event loop. Invoked with (args...).
  3580. * @param {...*} args... - any number of additional arguments to pass to the
  3581. * callback on the next tick.
  3582. * @example
  3583. *
  3584. * var call_order = [];
  3585. * async.nextTick(function() {
  3586. * call_order.push('two');
  3587. * // call_order now equals ['one','two']
  3588. * });
  3589. * call_order.push('one');
  3590. *
  3591. * async.setImmediate(function (a, b, c) {
  3592. * // a, b, and c equal 1, 2, and 3
  3593. * }, 1, 2, 3);
  3594. */
  3595. var _defer$1;
  3596. if (hasNextTick) {
  3597. _defer$1 = process.nextTick;
  3598. } else if (hasSetImmediate) {
  3599. _defer$1 = setImmediate;
  3600. } else {
  3601. _defer$1 = fallback;
  3602. }
  3603. var nextTick = wrap(_defer$1);
  3604. function _parallel(eachfn, tasks, callback) {
  3605. callback = callback || noop;
  3606. var results = isArrayLike(tasks) ? [] : {};
  3607. eachfn(tasks, function (task, key, callback) {
  3608. wrapAsync(task)(function (err, result) {
  3609. if (arguments.length > 2) {
  3610. result = slice(arguments, 1);
  3611. }
  3612. results[key] = result;
  3613. callback(err);
  3614. });
  3615. }, function (err) {
  3616. callback(err, results);
  3617. });
  3618. }
  3619. /**
  3620. * Run the `tasks` collection of functions in parallel, without waiting until
  3621. * the previous function has completed. If any of the functions pass an error to
  3622. * its callback, the main `callback` is immediately called with the value of the
  3623. * error. Once the `tasks` have completed, the results are passed to the final
  3624. * `callback` as an array.
  3625. *
  3626. * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
  3627. * parallel execution of code. If your tasks do not use any timers or perform
  3628. * any I/O, they will actually be executed in series. Any synchronous setup
  3629. * sections for each task will happen one after the other. JavaScript remains
  3630. * single-threaded.
  3631. *
  3632. * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the
  3633. * execution of other tasks when a task fails.
  3634. *
  3635. * It is also possible to use an object instead of an array. Each property will
  3636. * be run as a function and the results will be passed to the final `callback`
  3637. * as an object instead of an array. This can be a more readable way of handling
  3638. * results from {@link async.parallel}.
  3639. *
  3640. * @name parallel
  3641. * @static
  3642. * @memberOf module:ControlFlow
  3643. * @method
  3644. * @category Control Flow
  3645. * @param {Array|Iterable|Object} tasks - A collection of
  3646. * [async functions]{@link AsyncFunction} to run.
  3647. * Each async function can complete with any number of optional `result` values.
  3648. * @param {Function} [callback] - An optional callback to run once all the
  3649. * functions have completed successfully. This function gets a results array
  3650. * (or object) containing all the result arguments passed to the task callbacks.
  3651. * Invoked with (err, results).
  3652. *
  3653. * @example
  3654. * async.parallel([
  3655. * function(callback) {
  3656. * setTimeout(function() {
  3657. * callback(null, 'one');
  3658. * }, 200);
  3659. * },
  3660. * function(callback) {
  3661. * setTimeout(function() {
  3662. * callback(null, 'two');
  3663. * }, 100);
  3664. * }
  3665. * ],
  3666. * // optional callback
  3667. * function(err, results) {
  3668. * // the results array will equal ['one','two'] even though
  3669. * // the second function had a shorter timeout.
  3670. * });
  3671. *
  3672. * // an example using an object instead of an array
  3673. * async.parallel({
  3674. * one: function(callback) {
  3675. * setTimeout(function() {
  3676. * callback(null, 1);
  3677. * }, 200);
  3678. * },
  3679. * two: function(callback) {
  3680. * setTimeout(function() {
  3681. * callback(null, 2);
  3682. * }, 100);
  3683. * }
  3684. * }, function(err, results) {
  3685. * // results is now equals to: {one: 1, two: 2}
  3686. * });
  3687. */
  3688. function parallelLimit(tasks, callback) {
  3689. _parallel(eachOf, tasks, callback);
  3690. }
  3691. /**
  3692. * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a
  3693. * time.
  3694. *
  3695. * @name parallelLimit
  3696. * @static
  3697. * @memberOf module:ControlFlow
  3698. * @method
  3699. * @see [async.parallel]{@link module:ControlFlow.parallel}
  3700. * @category Control Flow
  3701. * @param {Array|Iterable|Object} tasks - A collection of
  3702. * [async functions]{@link AsyncFunction} to run.
  3703. * Each async function can complete with any number of optional `result` values.
  3704. * @param {number} limit - The maximum number of async operations at a time.
  3705. * @param {Function} [callback] - An optional callback to run once all the
  3706. * functions have completed successfully. This function gets a results array
  3707. * (or object) containing all the result arguments passed to the task callbacks.
  3708. * Invoked with (err, results).
  3709. */
  3710. function parallelLimit$1(tasks, limit, callback) {
  3711. _parallel(_eachOfLimit(limit), tasks, callback);
  3712. }
  3713. /**
  3714. * A queue of tasks for the worker function to complete.
  3715. * @typedef {Object} QueueObject
  3716. * @memberOf module:ControlFlow
  3717. * @property {Function} length - a function returning the number of items
  3718. * waiting to be processed. Invoke with `queue.length()`.
  3719. * @property {boolean} started - a boolean indicating whether or not any
  3720. * items have been pushed and processed by the queue.
  3721. * @property {Function} running - a function returning the number of items
  3722. * currently being processed. Invoke with `queue.running()`.
  3723. * @property {Function} workersList - a function returning the array of items
  3724. * currently being processed. Invoke with `queue.workersList()`.
  3725. * @property {Function} idle - a function returning false if there are items
  3726. * waiting or being processed, or true if not. Invoke with `queue.idle()`.
  3727. * @property {number} concurrency - an integer for determining how many `worker`
  3728. * functions should be run in parallel. This property can be changed after a
  3729. * `queue` is created to alter the concurrency on-the-fly.
  3730. * @property {Function} push - add a new task to the `queue`. Calls `callback`
  3731. * once the `worker` has finished processing the task. Instead of a single task,
  3732. * a `tasks` array can be submitted. The respective callback is used for every
  3733. * task in the list. Invoke with `queue.push(task, [callback])`,
  3734. * @property {Function} unshift - add a new task to the front of the `queue`.
  3735. * Invoke with `queue.unshift(task, [callback])`.
  3736. * @property {Function} remove - remove items from the queue that match a test
  3737. * function. The test function will be passed an object with a `data` property,
  3738. * and a `priority` property, if this is a
  3739. * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
  3740. * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
  3741. * `function ({data, priority}) {}` and returns a Boolean.
  3742. * @property {Function} saturated - a callback that is called when the number of
  3743. * running workers hits the `concurrency` limit, and further tasks will be
  3744. * queued.
  3745. * @property {Function} unsaturated - a callback that is called when the number
  3746. * of running workers is less than the `concurrency` & `buffer` limits, and
  3747. * further tasks will not be queued.
  3748. * @property {number} buffer - A minimum threshold buffer in order to say that
  3749. * the `queue` is `unsaturated`.
  3750. * @property {Function} empty - a callback that is called when the last item
  3751. * from the `queue` is given to a `worker`.
  3752. * @property {Function} drain - a callback that is called when the last item
  3753. * from the `queue` has returned from the `worker`.
  3754. * @property {Function} error - a callback that is called when a task errors.
  3755. * Has the signature `function(error, task)`.
  3756. * @property {boolean} paused - a boolean for determining whether the queue is
  3757. * in a paused state.
  3758. * @property {Function} pause - a function that pauses the processing of tasks
  3759. * until `resume()` is called. Invoke with `queue.pause()`.
  3760. * @property {Function} resume - a function that resumes the processing of
  3761. * queued tasks when the queue is paused. Invoke with `queue.resume()`.
  3762. * @property {Function} kill - a function that removes the `drain` callback and
  3763. * empties remaining tasks from the queue forcing it to go idle. No more tasks
  3764. * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
  3765. */
  3766. /**
  3767. * Creates a `queue` object with the specified `concurrency`. Tasks added to the
  3768. * `queue` are processed in parallel (up to the `concurrency` limit). If all
  3769. * `worker`s are in progress, the task is queued until one becomes available.
  3770. * Once a `worker` completes a `task`, that `task`'s callback is called.
  3771. *
  3772. * @name queue
  3773. * @static
  3774. * @memberOf module:ControlFlow
  3775. * @method
  3776. * @category Control Flow
  3777. * @param {AsyncFunction} worker - An async function for processing a queued task.
  3778. * If you want to handle errors from an individual task, pass a callback to
  3779. * `q.push()`. Invoked with (task, callback).
  3780. * @param {number} [concurrency=1] - An `integer` for determining how many
  3781. * `worker` functions should be run in parallel. If omitted, the concurrency
  3782. * defaults to `1`. If the concurrency is `0`, an error is thrown.
  3783. * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can
  3784. * attached as certain properties to listen for specific events during the
  3785. * lifecycle of the queue.
  3786. * @example
  3787. *
  3788. * // create a queue object with concurrency 2
  3789. * var q = async.queue(function(task, callback) {
  3790. * console.log('hello ' + task.name);
  3791. * callback();
  3792. * }, 2);
  3793. *
  3794. * // assign a callback
  3795. * q.drain = function() {
  3796. * console.log('all items have been processed');
  3797. * };
  3798. *
  3799. * // add some items to the queue
  3800. * q.push({name: 'foo'}, function(err) {
  3801. * console.log('finished processing foo');
  3802. * });
  3803. * q.push({name: 'bar'}, function (err) {
  3804. * console.log('finished processing bar');
  3805. * });
  3806. *
  3807. * // add some items to the queue (batch-wise)
  3808. * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
  3809. * console.log('finished processing item');
  3810. * });
  3811. *
  3812. * // add some items to the front of the queue
  3813. * q.unshift({name: 'bar'}, function (err) {
  3814. * console.log('finished processing bar');
  3815. * });
  3816. */
  3817. var queue$1 = function (worker, concurrency) {
  3818. var _worker = wrapAsync(worker);
  3819. return queue(function (items, cb) {
  3820. _worker(items[0], cb);
  3821. }, concurrency, 1);
  3822. };
  3823. /**
  3824. * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and
  3825. * completed in ascending priority order.
  3826. *
  3827. * @name priorityQueue
  3828. * @static
  3829. * @memberOf module:ControlFlow
  3830. * @method
  3831. * @see [async.queue]{@link module:ControlFlow.queue}
  3832. * @category Control Flow
  3833. * @param {AsyncFunction} worker - An async function for processing a queued task.
  3834. * If you want to handle errors from an individual task, pass a callback to
  3835. * `q.push()`.
  3836. * Invoked with (task, callback).
  3837. * @param {number} concurrency - An `integer` for determining how many `worker`
  3838. * functions should be run in parallel. If omitted, the concurrency defaults to
  3839. * `1`. If the concurrency is `0`, an error is thrown.
  3840. * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two
  3841. * differences between `queue` and `priorityQueue` objects:
  3842. * * `push(task, priority, [callback])` - `priority` should be a number. If an
  3843. * array of `tasks` is given, all tasks will be assigned the same priority.
  3844. * * The `unshift` method was removed.
  3845. */
  3846. var priorityQueue = function(worker, concurrency) {
  3847. // Start with a normal queue
  3848. var q = queue$1(worker, concurrency);
  3849. // Override push to accept second parameter representing priority
  3850. q.push = function(data, priority, callback) {
  3851. if (callback == null) callback = noop;
  3852. if (typeof callback !== 'function') {
  3853. throw new Error('task callback must be a function');
  3854. }
  3855. q.started = true;
  3856. if (!isArray(data)) {
  3857. data = [data];
  3858. }
  3859. if (data.length === 0) {
  3860. // call drain immediately if there are no tasks
  3861. return setImmediate$1(function() {
  3862. q.drain();
  3863. });
  3864. }
  3865. priority = priority || 0;
  3866. var nextNode = q._tasks.head;
  3867. while (nextNode && priority >= nextNode.priority) {
  3868. nextNode = nextNode.next;
  3869. }
  3870. for (var i = 0, l = data.length; i < l; i++) {
  3871. var item = {
  3872. data: data[i],
  3873. priority: priority,
  3874. callback: callback
  3875. };
  3876. if (nextNode) {
  3877. q._tasks.insertBefore(nextNode, item);
  3878. } else {
  3879. q._tasks.push(item);
  3880. }
  3881. }
  3882. setImmediate$1(q.process);
  3883. };
  3884. // Remove unshift function
  3885. delete q.unshift;
  3886. return q;
  3887. };
  3888. /**
  3889. * Runs the `tasks` array of functions in parallel, without waiting until the
  3890. * previous function has completed. Once any of the `tasks` complete or pass an
  3891. * error to its callback, the main `callback` is immediately called. It's
  3892. * equivalent to `Promise.race()`.
  3893. *
  3894. * @name race
  3895. * @static
  3896. * @memberOf module:ControlFlow
  3897. * @method
  3898. * @category Control Flow
  3899. * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
  3900. * to run. Each function can complete with an optional `result` value.
  3901. * @param {Function} callback - A callback to run once any of the functions have
  3902. * completed. This function gets an error or result from the first function that
  3903. * completed. Invoked with (err, result).
  3904. * @returns undefined
  3905. * @example
  3906. *
  3907. * async.race([
  3908. * function(callback) {
  3909. * setTimeout(function() {
  3910. * callback(null, 'one');
  3911. * }, 200);
  3912. * },
  3913. * function(callback) {
  3914. * setTimeout(function() {
  3915. * callback(null, 'two');
  3916. * }, 100);
  3917. * }
  3918. * ],
  3919. * // main callback
  3920. * function(err, result) {
  3921. * // the result will be equal to 'two' as it finishes earlier
  3922. * });
  3923. */
  3924. function race(tasks, callback) {
  3925. callback = once(callback || noop);
  3926. if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
  3927. if (!tasks.length) return callback();
  3928. for (var i = 0, l = tasks.length; i < l; i++) {
  3929. wrapAsync(tasks[i])(callback);
  3930. }
  3931. }
  3932. /**
  3933. * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
  3934. *
  3935. * @name reduceRight
  3936. * @static
  3937. * @memberOf module:Collections
  3938. * @method
  3939. * @see [async.reduce]{@link module:Collections.reduce}
  3940. * @alias foldr
  3941. * @category Collection
  3942. * @param {Array} array - A collection to iterate over.
  3943. * @param {*} memo - The initial state of the reduction.
  3944. * @param {AsyncFunction} iteratee - A function applied to each item in the
  3945. * array to produce the next step in the reduction.
  3946. * The `iteratee` should complete with the next state of the reduction.
  3947. * If the iteratee complete with an error, the reduction is stopped and the
  3948. * main `callback` is immediately called with the error.
  3949. * Invoked with (memo, item, callback).
  3950. * @param {Function} [callback] - A callback which is called after all the
  3951. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  3952. * (err, result).
  3953. */
  3954. function reduceRight (array, memo, iteratee, callback) {
  3955. var reversed = slice(array).reverse();
  3956. reduce(reversed, memo, iteratee, callback);
  3957. }
  3958. /**
  3959. * Wraps the async function in another function that always completes with a
  3960. * result object, even when it errors.
  3961. *
  3962. * The result object has either the property `error` or `value`.
  3963. *
  3964. * @name reflect
  3965. * @static
  3966. * @memberOf module:Utils
  3967. * @method
  3968. * @category Util
  3969. * @param {AsyncFunction} fn - The async function you want to wrap
  3970. * @returns {Function} - A function that always passes null to it's callback as
  3971. * the error. The second argument to the callback will be an `object` with
  3972. * either an `error` or a `value` property.
  3973. * @example
  3974. *
  3975. * async.parallel([
  3976. * async.reflect(function(callback) {
  3977. * // do some stuff ...
  3978. * callback(null, 'one');
  3979. * }),
  3980. * async.reflect(function(callback) {
  3981. * // do some more stuff but error ...
  3982. * callback('bad stuff happened');
  3983. * }),
  3984. * async.reflect(function(callback) {
  3985. * // do some more stuff ...
  3986. * callback(null, 'two');
  3987. * })
  3988. * ],
  3989. * // optional callback
  3990. * function(err, results) {
  3991. * // values
  3992. * // results[0].value = 'one'
  3993. * // results[1].error = 'bad stuff happened'
  3994. * // results[2].value = 'two'
  3995. * });
  3996. */
  3997. function reflect(fn) {
  3998. var _fn = wrapAsync(fn);
  3999. return initialParams(function reflectOn(args, reflectCallback) {
  4000. args.push(function callback(error, cbArg) {
  4001. if (error) {
  4002. reflectCallback(null, { error: error });
  4003. } else {
  4004. var value;
  4005. if (arguments.length <= 2) {
  4006. value = cbArg;
  4007. } else {
  4008. value = slice(arguments, 1);
  4009. }
  4010. reflectCallback(null, { value: value });
  4011. }
  4012. });
  4013. return _fn.apply(this, args);
  4014. });
  4015. }
  4016. /**
  4017. * A helper function that wraps an array or an object of functions with `reflect`.
  4018. *
  4019. * @name reflectAll
  4020. * @static
  4021. * @memberOf module:Utils
  4022. * @method
  4023. * @see [async.reflect]{@link module:Utils.reflect}
  4024. * @category Util
  4025. * @param {Array|Object|Iterable} tasks - The collection of
  4026. * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.
  4027. * @returns {Array} Returns an array of async functions, each wrapped in
  4028. * `async.reflect`
  4029. * @example
  4030. *
  4031. * let tasks = [
  4032. * function(callback) {
  4033. * setTimeout(function() {
  4034. * callback(null, 'one');
  4035. * }, 200);
  4036. * },
  4037. * function(callback) {
  4038. * // do some more stuff but error ...
  4039. * callback(new Error('bad stuff happened'));
  4040. * },
  4041. * function(callback) {
  4042. * setTimeout(function() {
  4043. * callback(null, 'two');
  4044. * }, 100);
  4045. * }
  4046. * ];
  4047. *
  4048. * async.parallel(async.reflectAll(tasks),
  4049. * // optional callback
  4050. * function(err, results) {
  4051. * // values
  4052. * // results[0].value = 'one'
  4053. * // results[1].error = Error('bad stuff happened')
  4054. * // results[2].value = 'two'
  4055. * });
  4056. *
  4057. * // an example using an object instead of an array
  4058. * let tasks = {
  4059. * one: function(callback) {
  4060. * setTimeout(function() {
  4061. * callback(null, 'one');
  4062. * }, 200);
  4063. * },
  4064. * two: function(callback) {
  4065. * callback('two');
  4066. * },
  4067. * three: function(callback) {
  4068. * setTimeout(function() {
  4069. * callback(null, 'three');
  4070. * }, 100);
  4071. * }
  4072. * };
  4073. *
  4074. * async.parallel(async.reflectAll(tasks),
  4075. * // optional callback
  4076. * function(err, results) {
  4077. * // values
  4078. * // results.one.value = 'one'
  4079. * // results.two.error = 'two'
  4080. * // results.three.value = 'three'
  4081. * });
  4082. */
  4083. function reflectAll(tasks) {
  4084. var results;
  4085. if (isArray(tasks)) {
  4086. results = arrayMap(tasks, reflect);
  4087. } else {
  4088. results = {};
  4089. baseForOwn(tasks, function(task, key) {
  4090. results[key] = reflect.call(this, task);
  4091. });
  4092. }
  4093. return results;
  4094. }
  4095. function reject$1(eachfn, arr, iteratee, callback) {
  4096. _filter(eachfn, arr, function(value, cb) {
  4097. iteratee(value, function(err, v) {
  4098. cb(err, !v);
  4099. });
  4100. }, callback);
  4101. }
  4102. /**
  4103. * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
  4104. *
  4105. * @name reject
  4106. * @static
  4107. * @memberOf module:Collections
  4108. * @method
  4109. * @see [async.filter]{@link module:Collections.filter}
  4110. * @category Collection
  4111. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4112. * @param {Function} iteratee - An async truth test to apply to each item in
  4113. * `coll`.
  4114. * The should complete with a boolean value as its `result`.
  4115. * Invoked with (item, callback).
  4116. * @param {Function} [callback] - A callback which is called after all the
  4117. * `iteratee` functions have finished. Invoked with (err, results).
  4118. * @example
  4119. *
  4120. * async.reject(['file1','file2','file3'], function(filePath, callback) {
  4121. * fs.access(filePath, function(err) {
  4122. * callback(null, !err)
  4123. * });
  4124. * }, function(err, results) {
  4125. * // results now equals an array of missing files
  4126. * createFiles(results);
  4127. * });
  4128. */
  4129. var reject = doParallel(reject$1);
  4130. /**
  4131. * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
  4132. * time.
  4133. *
  4134. * @name rejectLimit
  4135. * @static
  4136. * @memberOf module:Collections
  4137. * @method
  4138. * @see [async.reject]{@link module:Collections.reject}
  4139. * @category Collection
  4140. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4141. * @param {number} limit - The maximum number of async operations at a time.
  4142. * @param {Function} iteratee - An async truth test to apply to each item in
  4143. * `coll`.
  4144. * The should complete with a boolean value as its `result`.
  4145. * Invoked with (item, callback).
  4146. * @param {Function} [callback] - A callback which is called after all the
  4147. * `iteratee` functions have finished. Invoked with (err, results).
  4148. */
  4149. var rejectLimit = doParallelLimit(reject$1);
  4150. /**
  4151. * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
  4152. *
  4153. * @name rejectSeries
  4154. * @static
  4155. * @memberOf module:Collections
  4156. * @method
  4157. * @see [async.reject]{@link module:Collections.reject}
  4158. * @category Collection
  4159. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4160. * @param {Function} iteratee - An async truth test to apply to each item in
  4161. * `coll`.
  4162. * The should complete with a boolean value as its `result`.
  4163. * Invoked with (item, callback).
  4164. * @param {Function} [callback] - A callback which is called after all the
  4165. * `iteratee` functions have finished. Invoked with (err, results).
  4166. */
  4167. var rejectSeries = doLimit(rejectLimit, 1);
  4168. /**
  4169. * Creates a function that returns `value`.
  4170. *
  4171. * @static
  4172. * @memberOf _
  4173. * @since 2.4.0
  4174. * @category Util
  4175. * @param {*} value The value to return from the new function.
  4176. * @returns {Function} Returns the new constant function.
  4177. * @example
  4178. *
  4179. * var objects = _.times(2, _.constant({ 'a': 1 }));
  4180. *
  4181. * console.log(objects);
  4182. * // => [{ 'a': 1 }, { 'a': 1 }]
  4183. *
  4184. * console.log(objects[0] === objects[1]);
  4185. * // => true
  4186. */
  4187. function constant$1(value) {
  4188. return function() {
  4189. return value;
  4190. };
  4191. }
  4192. /**
  4193. * Attempts to get a successful response from `task` no more than `times` times
  4194. * before returning an error. If the task is successful, the `callback` will be
  4195. * passed the result of the successful task. If all attempts fail, the callback
  4196. * will be passed the error and result (if any) of the final attempt.
  4197. *
  4198. * @name retry
  4199. * @static
  4200. * @memberOf module:ControlFlow
  4201. * @method
  4202. * @category Control Flow
  4203. * @see [async.retryable]{@link module:ControlFlow.retryable}
  4204. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
  4205. * object with `times` and `interval` or a number.
  4206. * * `times` - The number of attempts to make before giving up. The default
  4207. * is `5`.
  4208. * * `interval` - The time to wait between retries, in milliseconds. The
  4209. * default is `0`. The interval may also be specified as a function of the
  4210. * retry count (see example).
  4211. * * `errorFilter` - An optional synchronous function that is invoked on
  4212. * erroneous result. If it returns `true` the retry attempts will continue;
  4213. * if the function returns `false` the retry flow is aborted with the current
  4214. * attempt's error and result being returned to the final callback.
  4215. * Invoked with (err).
  4216. * * If `opts` is a number, the number specifies the number of times to retry,
  4217. * with the default interval of `0`.
  4218. * @param {AsyncFunction} task - An async function to retry.
  4219. * Invoked with (callback).
  4220. * @param {Function} [callback] - An optional callback which is called when the
  4221. * task has succeeded, or after the final failed attempt. It receives the `err`
  4222. * and `result` arguments of the last attempt at completing the `task`. Invoked
  4223. * with (err, results).
  4224. *
  4225. * @example
  4226. *
  4227. * // The `retry` function can be used as a stand-alone control flow by passing
  4228. * // a callback, as shown below:
  4229. *
  4230. * // try calling apiMethod 3 times
  4231. * async.retry(3, apiMethod, function(err, result) {
  4232. * // do something with the result
  4233. * });
  4234. *
  4235. * // try calling apiMethod 3 times, waiting 200 ms between each retry
  4236. * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
  4237. * // do something with the result
  4238. * });
  4239. *
  4240. * // try calling apiMethod 10 times with exponential backoff
  4241. * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
  4242. * async.retry({
  4243. * times: 10,
  4244. * interval: function(retryCount) {
  4245. * return 50 * Math.pow(2, retryCount);
  4246. * }
  4247. * }, apiMethod, function(err, result) {
  4248. * // do something with the result
  4249. * });
  4250. *
  4251. * // try calling apiMethod the default 5 times no delay between each retry
  4252. * async.retry(apiMethod, function(err, result) {
  4253. * // do something with the result
  4254. * });
  4255. *
  4256. * // try calling apiMethod only when error condition satisfies, all other
  4257. * // errors will abort the retry control flow and return to final callback
  4258. * async.retry({
  4259. * errorFilter: function(err) {
  4260. * return err.message === 'Temporary error'; // only retry on a specific error
  4261. * }
  4262. * }, apiMethod, function(err, result) {
  4263. * // do something with the result
  4264. * });
  4265. *
  4266. * // to retry individual methods that are not as reliable within other
  4267. * // control flow functions, use the `retryable` wrapper:
  4268. * async.auto({
  4269. * users: api.getUsers.bind(api),
  4270. * payments: async.retryable(3, api.getPayments.bind(api))
  4271. * }, function(err, results) {
  4272. * // do something with the results
  4273. * });
  4274. *
  4275. */
  4276. function retry(opts, task, callback) {
  4277. var DEFAULT_TIMES = 5;
  4278. var DEFAULT_INTERVAL = 0;
  4279. var options = {
  4280. times: DEFAULT_TIMES,
  4281. intervalFunc: constant$1(DEFAULT_INTERVAL)
  4282. };
  4283. function parseTimes(acc, t) {
  4284. if (typeof t === 'object') {
  4285. acc.times = +t.times || DEFAULT_TIMES;
  4286. acc.intervalFunc = typeof t.interval === 'function' ?
  4287. t.interval :
  4288. constant$1(+t.interval || DEFAULT_INTERVAL);
  4289. acc.errorFilter = t.errorFilter;
  4290. } else if (typeof t === 'number' || typeof t === 'string') {
  4291. acc.times = +t || DEFAULT_TIMES;
  4292. } else {
  4293. throw new Error("Invalid arguments for async.retry");
  4294. }
  4295. }
  4296. if (arguments.length < 3 && typeof opts === 'function') {
  4297. callback = task || noop;
  4298. task = opts;
  4299. } else {
  4300. parseTimes(options, opts);
  4301. callback = callback || noop;
  4302. }
  4303. if (typeof task !== 'function') {
  4304. throw new Error("Invalid arguments for async.retry");
  4305. }
  4306. var _task = wrapAsync(task);
  4307. var attempt = 1;
  4308. function retryAttempt() {
  4309. _task(function(err) {
  4310. if (err && attempt++ < options.times &&
  4311. (typeof options.errorFilter != 'function' ||
  4312. options.errorFilter(err))) {
  4313. setTimeout(retryAttempt, options.intervalFunc(attempt));
  4314. } else {
  4315. callback.apply(null, arguments);
  4316. }
  4317. });
  4318. }
  4319. retryAttempt();
  4320. }
  4321. /**
  4322. * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method
  4323. * wraps a task and makes it retryable, rather than immediately calling it
  4324. * with retries.
  4325. *
  4326. * @name retryable
  4327. * @static
  4328. * @memberOf module:ControlFlow
  4329. * @method
  4330. * @see [async.retry]{@link module:ControlFlow.retry}
  4331. * @category Control Flow
  4332. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
  4333. * options, exactly the same as from `retry`
  4334. * @param {AsyncFunction} task - the asynchronous function to wrap.
  4335. * This function will be passed any arguments passed to the returned wrapper.
  4336. * Invoked with (...args, callback).
  4337. * @returns {AsyncFunction} The wrapped function, which when invoked, will
  4338. * retry on an error, based on the parameters specified in `opts`.
  4339. * This function will accept the same parameters as `task`.
  4340. * @example
  4341. *
  4342. * async.auto({
  4343. * dep1: async.retryable(3, getFromFlakyService),
  4344. * process: ["dep1", async.retryable(3, function (results, cb) {
  4345. * maybeProcessData(results.dep1, cb);
  4346. * })]
  4347. * }, callback);
  4348. */
  4349. var retryable = function (opts, task) {
  4350. if (!task) {
  4351. task = opts;
  4352. opts = null;
  4353. }
  4354. var _task = wrapAsync(task);
  4355. return initialParams(function (args, callback) {
  4356. function taskFn(cb) {
  4357. _task.apply(null, args.concat(cb));
  4358. }
  4359. if (opts) retry(opts, taskFn, callback);
  4360. else retry(taskFn, callback);
  4361. });
  4362. };
  4363. /**
  4364. * Run the functions in the `tasks` collection in series, each one running once
  4365. * the previous function has completed. If any functions in the series pass an
  4366. * error to its callback, no more functions are run, and `callback` is
  4367. * immediately called with the value of the error. Otherwise, `callback`
  4368. * receives an array of results when `tasks` have completed.
  4369. *
  4370. * It is also possible to use an object instead of an array. Each property will
  4371. * be run as a function, and the results will be passed to the final `callback`
  4372. * as an object instead of an array. This can be a more readable way of handling
  4373. * results from {@link async.series}.
  4374. *
  4375. * **Note** that while many implementations preserve the order of object
  4376. * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
  4377. * explicitly states that
  4378. *
  4379. * > The mechanics and order of enumerating the properties is not specified.
  4380. *
  4381. * So if you rely on the order in which your series of functions are executed,
  4382. * and want this to work on all platforms, consider using an array.
  4383. *
  4384. * @name series
  4385. * @static
  4386. * @memberOf module:ControlFlow
  4387. * @method
  4388. * @category Control Flow
  4389. * @param {Array|Iterable|Object} tasks - A collection containing
  4390. * [async functions]{@link AsyncFunction} to run in series.
  4391. * Each function can complete with any number of optional `result` values.
  4392. * @param {Function} [callback] - An optional callback to run once all the
  4393. * functions have completed. This function gets a results array (or object)
  4394. * containing all the result arguments passed to the `task` callbacks. Invoked
  4395. * with (err, result).
  4396. * @example
  4397. * async.series([
  4398. * function(callback) {
  4399. * // do some stuff ...
  4400. * callback(null, 'one');
  4401. * },
  4402. * function(callback) {
  4403. * // do some more stuff ...
  4404. * callback(null, 'two');
  4405. * }
  4406. * ],
  4407. * // optional callback
  4408. * function(err, results) {
  4409. * // results is now equal to ['one', 'two']
  4410. * });
  4411. *
  4412. * async.series({
  4413. * one: function(callback) {
  4414. * setTimeout(function() {
  4415. * callback(null, 1);
  4416. * }, 200);
  4417. * },
  4418. * two: function(callback){
  4419. * setTimeout(function() {
  4420. * callback(null, 2);
  4421. * }, 100);
  4422. * }
  4423. * }, function(err, results) {
  4424. * // results is now equal to: {one: 1, two: 2}
  4425. * });
  4426. */
  4427. function series(tasks, callback) {
  4428. _parallel(eachOfSeries, tasks, callback);
  4429. }
  4430. /**
  4431. * Returns `true` if at least one element in the `coll` satisfies an async test.
  4432. * If any iteratee call returns `true`, the main `callback` is immediately
  4433. * called.
  4434. *
  4435. * @name some
  4436. * @static
  4437. * @memberOf module:Collections
  4438. * @method
  4439. * @alias any
  4440. * @category Collection
  4441. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4442. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  4443. * in the collections in parallel.
  4444. * The iteratee should complete with a boolean `result` value.
  4445. * Invoked with (item, callback).
  4446. * @param {Function} [callback] - A callback which is called as soon as any
  4447. * iteratee returns `true`, or after all the iteratee functions have finished.
  4448. * Result will be either `true` or `false` depending on the values of the async
  4449. * tests. Invoked with (err, result).
  4450. * @example
  4451. *
  4452. * async.some(['file1','file2','file3'], function(filePath, callback) {
  4453. * fs.access(filePath, function(err) {
  4454. * callback(null, !err)
  4455. * });
  4456. * }, function(err, result) {
  4457. * // if result is true then at least one of the files exists
  4458. * });
  4459. */
  4460. var some = doParallel(_createTester(Boolean, identity));
  4461. /**
  4462. * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
  4463. *
  4464. * @name someLimit
  4465. * @static
  4466. * @memberOf module:Collections
  4467. * @method
  4468. * @see [async.some]{@link module:Collections.some}
  4469. * @alias anyLimit
  4470. * @category Collection
  4471. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4472. * @param {number} limit - The maximum number of async operations at a time.
  4473. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  4474. * in the collections in parallel.
  4475. * The iteratee should complete with a boolean `result` value.
  4476. * Invoked with (item, callback).
  4477. * @param {Function} [callback] - A callback which is called as soon as any
  4478. * iteratee returns `true`, or after all the iteratee functions have finished.
  4479. * Result will be either `true` or `false` depending on the values of the async
  4480. * tests. Invoked with (err, result).
  4481. */
  4482. var someLimit = doParallelLimit(_createTester(Boolean, identity));
  4483. /**
  4484. * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
  4485. *
  4486. * @name someSeries
  4487. * @static
  4488. * @memberOf module:Collections
  4489. * @method
  4490. * @see [async.some]{@link module:Collections.some}
  4491. * @alias anySeries
  4492. * @category Collection
  4493. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4494. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  4495. * in the collections in series.
  4496. * The iteratee should complete with a boolean `result` value.
  4497. * Invoked with (item, callback).
  4498. * @param {Function} [callback] - A callback which is called as soon as any
  4499. * iteratee returns `true`, or after all the iteratee functions have finished.
  4500. * Result will be either `true` or `false` depending on the values of the async
  4501. * tests. Invoked with (err, result).
  4502. */
  4503. var someSeries = doLimit(someLimit, 1);
  4504. /**
  4505. * Sorts a list by the results of running each `coll` value through an async
  4506. * `iteratee`.
  4507. *
  4508. * @name sortBy
  4509. * @static
  4510. * @memberOf module:Collections
  4511. * @method
  4512. * @category Collection
  4513. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4514. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  4515. * `coll`.
  4516. * The iteratee should complete with a value to use as the sort criteria as
  4517. * its `result`.
  4518. * Invoked with (item, callback).
  4519. * @param {Function} callback - A callback which is called after all the
  4520. * `iteratee` functions have finished, or an error occurs. Results is the items
  4521. * from the original `coll` sorted by the values returned by the `iteratee`
  4522. * calls. Invoked with (err, results).
  4523. * @example
  4524. *
  4525. * async.sortBy(['file1','file2','file3'], function(file, callback) {
  4526. * fs.stat(file, function(err, stats) {
  4527. * callback(err, stats.mtime);
  4528. * });
  4529. * }, function(err, results) {
  4530. * // results is now the original array of files sorted by
  4531. * // modified date
  4532. * });
  4533. *
  4534. * // By modifying the callback parameter the
  4535. * // sorting order can be influenced:
  4536. *
  4537. * // ascending order
  4538. * async.sortBy([1,9,3,5], function(x, callback) {
  4539. * callback(null, x);
  4540. * }, function(err,result) {
  4541. * // result callback
  4542. * });
  4543. *
  4544. * // descending order
  4545. * async.sortBy([1,9,3,5], function(x, callback) {
  4546. * callback(null, x*-1); //<- x*-1 instead of x, turns the order around
  4547. * }, function(err,result) {
  4548. * // result callback
  4549. * });
  4550. */
  4551. function sortBy (coll, iteratee, callback) {
  4552. var _iteratee = wrapAsync(iteratee);
  4553. map(coll, function (x, callback) {
  4554. _iteratee(x, function (err, criteria) {
  4555. if (err) return callback(err);
  4556. callback(null, {value: x, criteria: criteria});
  4557. });
  4558. }, function (err, results) {
  4559. if (err) return callback(err);
  4560. callback(null, arrayMap(results.sort(comparator), baseProperty('value')));
  4561. });
  4562. function comparator(left, right) {
  4563. var a = left.criteria, b = right.criteria;
  4564. return a < b ? -1 : a > b ? 1 : 0;
  4565. }
  4566. }
  4567. /**
  4568. * Sets a time limit on an asynchronous function. If the function does not call
  4569. * its callback within the specified milliseconds, it will be called with a
  4570. * timeout error. The code property for the error object will be `'ETIMEDOUT'`.
  4571. *
  4572. * @name timeout
  4573. * @static
  4574. * @memberOf module:Utils
  4575. * @method
  4576. * @category Util
  4577. * @param {AsyncFunction} asyncFn - The async function to limit in time.
  4578. * @param {number} milliseconds - The specified time limit.
  4579. * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
  4580. * to timeout Error for more information..
  4581. * @returns {AsyncFunction} Returns a wrapped function that can be used with any
  4582. * of the control flow functions.
  4583. * Invoke this function with the same parameters as you would `asyncFunc`.
  4584. * @example
  4585. *
  4586. * function myFunction(foo, callback) {
  4587. * doAsyncTask(foo, function(err, data) {
  4588. * // handle errors
  4589. * if (err) return callback(err);
  4590. *
  4591. * // do some stuff ...
  4592. *
  4593. * // return processed data
  4594. * return callback(null, data);
  4595. * });
  4596. * }
  4597. *
  4598. * var wrapped = async.timeout(myFunction, 1000);
  4599. *
  4600. * // call `wrapped` as you would `myFunction`
  4601. * wrapped({ bar: 'bar' }, function(err, data) {
  4602. * // if `myFunction` takes < 1000 ms to execute, `err`
  4603. * // and `data` will have their expected values
  4604. *
  4605. * // else `err` will be an Error with the code 'ETIMEDOUT'
  4606. * });
  4607. */
  4608. function timeout(asyncFn, milliseconds, info) {
  4609. var fn = wrapAsync(asyncFn);
  4610. return initialParams(function (args, callback) {
  4611. var timedOut = false;
  4612. var timer;
  4613. function timeoutCallback() {
  4614. var name = asyncFn.name || 'anonymous';
  4615. var error = new Error('Callback function "' + name + '" timed out.');
  4616. error.code = 'ETIMEDOUT';
  4617. if (info) {
  4618. error.info = info;
  4619. }
  4620. timedOut = true;
  4621. callback(error);
  4622. }
  4623. args.push(function () {
  4624. if (!timedOut) {
  4625. callback.apply(null, arguments);
  4626. clearTimeout(timer);
  4627. }
  4628. });
  4629. // setup timer and call original function
  4630. timer = setTimeout(timeoutCallback, milliseconds);
  4631. fn.apply(null, args);
  4632. });
  4633. }
  4634. /* Built-in method references for those with the same name as other `lodash` methods. */
  4635. var nativeCeil = Math.ceil;
  4636. var nativeMax = Math.max;
  4637. /**
  4638. * The base implementation of `_.range` and `_.rangeRight` which doesn't
  4639. * coerce arguments.
  4640. *
  4641. * @private
  4642. * @param {number} start The start of the range.
  4643. * @param {number} end The end of the range.
  4644. * @param {number} step The value to increment or decrement by.
  4645. * @param {boolean} [fromRight] Specify iterating from right to left.
  4646. * @returns {Array} Returns the range of numbers.
  4647. */
  4648. function baseRange(start, end, step, fromRight) {
  4649. var index = -1,
  4650. length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
  4651. result = Array(length);
  4652. while (length--) {
  4653. result[fromRight ? length : ++index] = start;
  4654. start += step;
  4655. }
  4656. return result;
  4657. }
  4658. /**
  4659. * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a
  4660. * time.
  4661. *
  4662. * @name timesLimit
  4663. * @static
  4664. * @memberOf module:ControlFlow
  4665. * @method
  4666. * @see [async.times]{@link module:ControlFlow.times}
  4667. * @category Control Flow
  4668. * @param {number} count - The number of times to run the function.
  4669. * @param {number} limit - The maximum number of async operations at a time.
  4670. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  4671. * Invoked with the iteration index and a callback: (n, next).
  4672. * @param {Function} callback - see [async.map]{@link module:Collections.map}.
  4673. */
  4674. function timeLimit(count, limit, iteratee, callback) {
  4675. var _iteratee = wrapAsync(iteratee);
  4676. mapLimit(baseRange(0, count, 1), limit, _iteratee, callback);
  4677. }
  4678. /**
  4679. * Calls the `iteratee` function `n` times, and accumulates results in the same
  4680. * manner you would use with [map]{@link module:Collections.map}.
  4681. *
  4682. * @name times
  4683. * @static
  4684. * @memberOf module:ControlFlow
  4685. * @method
  4686. * @see [async.map]{@link module:Collections.map}
  4687. * @category Control Flow
  4688. * @param {number} n - The number of times to run the function.
  4689. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  4690. * Invoked with the iteration index and a callback: (n, next).
  4691. * @param {Function} callback - see {@link module:Collections.map}.
  4692. * @example
  4693. *
  4694. * // Pretend this is some complicated async factory
  4695. * var createUser = function(id, callback) {
  4696. * callback(null, {
  4697. * id: 'user' + id
  4698. * });
  4699. * };
  4700. *
  4701. * // generate 5 users
  4702. * async.times(5, function(n, next) {
  4703. * createUser(n, function(err, user) {
  4704. * next(err, user);
  4705. * });
  4706. * }, function(err, users) {
  4707. * // we should now have 5 users
  4708. * });
  4709. */
  4710. var times = doLimit(timeLimit, Infinity);
  4711. /**
  4712. * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.
  4713. *
  4714. * @name timesSeries
  4715. * @static
  4716. * @memberOf module:ControlFlow
  4717. * @method
  4718. * @see [async.times]{@link module:ControlFlow.times}
  4719. * @category Control Flow
  4720. * @param {number} n - The number of times to run the function.
  4721. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  4722. * Invoked with the iteration index and a callback: (n, next).
  4723. * @param {Function} callback - see {@link module:Collections.map}.
  4724. */
  4725. var timesSeries = doLimit(timeLimit, 1);
  4726. /**
  4727. * A relative of `reduce`. Takes an Object or Array, and iterates over each
  4728. * element in series, each step potentially mutating an `accumulator` value.
  4729. * The type of the accumulator defaults to the type of collection passed in.
  4730. *
  4731. * @name transform
  4732. * @static
  4733. * @memberOf module:Collections
  4734. * @method
  4735. * @category Collection
  4736. * @param {Array|Iterable|Object} coll - A collection to iterate over.
  4737. * @param {*} [accumulator] - The initial state of the transform. If omitted,
  4738. * it will default to an empty Object or Array, depending on the type of `coll`
  4739. * @param {AsyncFunction} iteratee - A function applied to each item in the
  4740. * collection that potentially modifies the accumulator.
  4741. * Invoked with (accumulator, item, key, callback).
  4742. * @param {Function} [callback] - A callback which is called after all the
  4743. * `iteratee` functions have finished. Result is the transformed accumulator.
  4744. * Invoked with (err, result).
  4745. * @example
  4746. *
  4747. * async.transform([1,2,3], function(acc, item, index, callback) {
  4748. * // pointless async:
  4749. * process.nextTick(function() {
  4750. * acc.push(item * 2)
  4751. * callback(null)
  4752. * });
  4753. * }, function(err, result) {
  4754. * // result is now equal to [2, 4, 6]
  4755. * });
  4756. *
  4757. * @example
  4758. *
  4759. * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
  4760. * setImmediate(function () {
  4761. * obj[key] = val * 2;
  4762. * callback();
  4763. * })
  4764. * }, function (err, result) {
  4765. * // result is equal to {a: 2, b: 4, c: 6}
  4766. * })
  4767. */
  4768. function transform (coll, accumulator, iteratee, callback) {
  4769. if (arguments.length <= 3) {
  4770. callback = iteratee;
  4771. iteratee = accumulator;
  4772. accumulator = isArray(coll) ? [] : {};
  4773. }
  4774. callback = once(callback || noop);
  4775. var _iteratee = wrapAsync(iteratee);
  4776. eachOf(coll, function(v, k, cb) {
  4777. _iteratee(accumulator, v, k, cb);
  4778. }, function(err) {
  4779. callback(err, accumulator);
  4780. });
  4781. }
  4782. /**
  4783. * It runs each task in series but stops whenever any of the functions were
  4784. * successful. If one of the tasks were successful, the `callback` will be
  4785. * passed the result of the successful task. If all tasks fail, the callback
  4786. * will be passed the error and result (if any) of the final attempt.
  4787. *
  4788. * @name tryEach
  4789. * @static
  4790. * @memberOf module:ControlFlow
  4791. * @method
  4792. * @category Control Flow
  4793. * @param {Array|Iterable|Object} tasks - A collection containing functions to
  4794. * run, each function is passed a `callback(err, result)` it must call on
  4795. * completion with an error `err` (which can be `null`) and an optional `result`
  4796. * value.
  4797. * @param {Function} [callback] - An optional callback which is called when one
  4798. * of the tasks has succeeded, or all have failed. It receives the `err` and
  4799. * `result` arguments of the last attempt at completing the `task`. Invoked with
  4800. * (err, results).
  4801. * @example
  4802. * async.tryEach([
  4803. * function getDataFromFirstWebsite(callback) {
  4804. * // Try getting the data from the first website
  4805. * callback(err, data);
  4806. * },
  4807. * function getDataFromSecondWebsite(callback) {
  4808. * // First website failed,
  4809. * // Try getting the data from the backup website
  4810. * callback(err, data);
  4811. * }
  4812. * ],
  4813. * // optional callback
  4814. * function(err, results) {
  4815. * Now do something with the data.
  4816. * });
  4817. *
  4818. */
  4819. function tryEach(tasks, callback) {
  4820. var error = null;
  4821. var result;
  4822. callback = callback || noop;
  4823. eachSeries(tasks, function(task, callback) {
  4824. wrapAsync(task)(function (err, res/*, ...args*/) {
  4825. if (arguments.length > 2) {
  4826. result = slice(arguments, 1);
  4827. } else {
  4828. result = res;
  4829. }
  4830. error = err;
  4831. callback(!err);
  4832. });
  4833. }, function () {
  4834. callback(error, result);
  4835. });
  4836. }
  4837. /**
  4838. * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,
  4839. * unmemoized form. Handy for testing.
  4840. *
  4841. * @name unmemoize
  4842. * @static
  4843. * @memberOf module:Utils
  4844. * @method
  4845. * @see [async.memoize]{@link module:Utils.memoize}
  4846. * @category Util
  4847. * @param {AsyncFunction} fn - the memoized function
  4848. * @returns {AsyncFunction} a function that calls the original unmemoized function
  4849. */
  4850. function unmemoize(fn) {
  4851. return function () {
  4852. return (fn.unmemoized || fn).apply(null, arguments);
  4853. };
  4854. }
  4855. /**
  4856. * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
  4857. * stopped, or an error occurs.
  4858. *
  4859. * @name whilst
  4860. * @static
  4861. * @memberOf module:ControlFlow
  4862. * @method
  4863. * @category Control Flow
  4864. * @param {Function} test - synchronous truth test to perform before each
  4865. * execution of `iteratee`. Invoked with ().
  4866. * @param {AsyncFunction} iteratee - An async function which is called each time
  4867. * `test` passes. Invoked with (callback).
  4868. * @param {Function} [callback] - A callback which is called after the test
  4869. * function has failed and repeated execution of `iteratee` has stopped. `callback`
  4870. * will be passed an error and any arguments passed to the final `iteratee`'s
  4871. * callback. Invoked with (err, [results]);
  4872. * @returns undefined
  4873. * @example
  4874. *
  4875. * var count = 0;
  4876. * async.whilst(
  4877. * function() { return count < 5; },
  4878. * function(callback) {
  4879. * count++;
  4880. * setTimeout(function() {
  4881. * callback(null, count);
  4882. * }, 1000);
  4883. * },
  4884. * function (err, n) {
  4885. * // 5 seconds have passed, n = 5
  4886. * }
  4887. * );
  4888. */
  4889. function whilst(test, iteratee, callback) {
  4890. callback = onlyOnce(callback || noop);
  4891. var _iteratee = wrapAsync(iteratee);
  4892. if (!test()) return callback(null);
  4893. var next = function(err/*, ...args*/) {
  4894. if (err) return callback(err);
  4895. if (test()) return _iteratee(next);
  4896. var args = slice(arguments, 1);
  4897. callback.apply(null, [null].concat(args));
  4898. };
  4899. _iteratee(next);
  4900. }
  4901. /**
  4902. * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when
  4903. * stopped, or an error occurs. `callback` will be passed an error and any
  4904. * arguments passed to the final `iteratee`'s callback.
  4905. *
  4906. * The inverse of [whilst]{@link module:ControlFlow.whilst}.
  4907. *
  4908. * @name until
  4909. * @static
  4910. * @memberOf module:ControlFlow
  4911. * @method
  4912. * @see [async.whilst]{@link module:ControlFlow.whilst}
  4913. * @category Control Flow
  4914. * @param {Function} test - synchronous truth test to perform before each
  4915. * execution of `iteratee`. Invoked with ().
  4916. * @param {AsyncFunction} iteratee - An async function which is called each time
  4917. * `test` fails. Invoked with (callback).
  4918. * @param {Function} [callback] - A callback which is called after the test
  4919. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  4920. * will be passed an error and any arguments passed to the final `iteratee`'s
  4921. * callback. Invoked with (err, [results]);
  4922. */
  4923. function until(test, iteratee, callback) {
  4924. whilst(function() {
  4925. return !test.apply(this, arguments);
  4926. }, iteratee, callback);
  4927. }
  4928. /**
  4929. * Runs the `tasks` array of functions in series, each passing their results to
  4930. * the next in the array. However, if any of the `tasks` pass an error to their
  4931. * own callback, the next function is not executed, and the main `callback` is
  4932. * immediately called with the error.
  4933. *
  4934. * @name waterfall
  4935. * @static
  4936. * @memberOf module:ControlFlow
  4937. * @method
  4938. * @category Control Flow
  4939. * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
  4940. * to run.
  4941. * Each function should complete with any number of `result` values.
  4942. * The `result` values will be passed as arguments, in order, to the next task.
  4943. * @param {Function} [callback] - An optional callback to run once all the
  4944. * functions have completed. This will be passed the results of the last task's
  4945. * callback. Invoked with (err, [results]).
  4946. * @returns undefined
  4947. * @example
  4948. *
  4949. * async.waterfall([
  4950. * function(callback) {
  4951. * callback(null, 'one', 'two');
  4952. * },
  4953. * function(arg1, arg2, callback) {
  4954. * // arg1 now equals 'one' and arg2 now equals 'two'
  4955. * callback(null, 'three');
  4956. * },
  4957. * function(arg1, callback) {
  4958. * // arg1 now equals 'three'
  4959. * callback(null, 'done');
  4960. * }
  4961. * ], function (err, result) {
  4962. * // result now equals 'done'
  4963. * });
  4964. *
  4965. * // Or, with named functions:
  4966. * async.waterfall([
  4967. * myFirstFunction,
  4968. * mySecondFunction,
  4969. * myLastFunction,
  4970. * ], function (err, result) {
  4971. * // result now equals 'done'
  4972. * });
  4973. * function myFirstFunction(callback) {
  4974. * callback(null, 'one', 'two');
  4975. * }
  4976. * function mySecondFunction(arg1, arg2, callback) {
  4977. * // arg1 now equals 'one' and arg2 now equals 'two'
  4978. * callback(null, 'three');
  4979. * }
  4980. * function myLastFunction(arg1, callback) {
  4981. * // arg1 now equals 'three'
  4982. * callback(null, 'done');
  4983. * }
  4984. */
  4985. var waterfall = function(tasks, callback) {
  4986. callback = once(callback || noop);
  4987. if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
  4988. if (!tasks.length) return callback();
  4989. var taskIndex = 0;
  4990. function nextTask(args) {
  4991. var task = wrapAsync(tasks[taskIndex++]);
  4992. args.push(onlyOnce(next));
  4993. task.apply(null, args);
  4994. }
  4995. function next(err/*, ...args*/) {
  4996. if (err || taskIndex === tasks.length) {
  4997. return callback.apply(null, arguments);
  4998. }
  4999. nextTask(slice(arguments, 1));
  5000. }
  5001. nextTask([]);
  5002. };
  5003. /**
  5004. * An "async function" in the context of Async is an asynchronous function with
  5005. * a variable number of parameters, with the final parameter being a callback.
  5006. * (`function (arg1, arg2, ..., callback) {}`)
  5007. * The final callback is of the form `callback(err, results...)`, which must be
  5008. * called once the function is completed. The callback should be called with a
  5009. * Error as its first argument to signal that an error occurred.
  5010. * Otherwise, if no error occurred, it should be called with `null` as the first
  5011. * argument, and any additional `result` arguments that may apply, to signal
  5012. * successful completion.
  5013. * The callback must be called exactly once, ideally on a later tick of the
  5014. * JavaScript event loop.
  5015. *
  5016. * This type of function is also referred to as a "Node-style async function",
  5017. * or a "continuation passing-style function" (CPS). Most of the methods of this
  5018. * library are themselves CPS/Node-style async functions, or functions that
  5019. * return CPS/Node-style async functions.
  5020. *
  5021. * Wherever we accept a Node-style async function, we also directly accept an
  5022. * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.
  5023. * In this case, the `async` function will not be passed a final callback
  5024. * argument, and any thrown error will be used as the `err` argument of the
  5025. * implicit callback, and the return value will be used as the `result` value.
  5026. * (i.e. a `rejected` of the returned Promise becomes the `err` callback
  5027. * argument, and a `resolved` value becomes the `result`.)
  5028. *
  5029. * Note, due to JavaScript limitations, we can only detect native `async`
  5030. * functions and not transpilied implementations.
  5031. * Your environment must have `async`/`await` support for this to work.
  5032. * (e.g. Node > v7.6, or a recent version of a modern browser).
  5033. * If you are using `async` functions through a transpiler (e.g. Babel), you
  5034. * must still wrap the function with [asyncify]{@link module:Utils.asyncify},
  5035. * because the `async function` will be compiled to an ordinary function that
  5036. * returns a promise.
  5037. *
  5038. * @typedef {Function} AsyncFunction
  5039. * @static
  5040. */
  5041. /**
  5042. * Async is a utility module which provides straight-forward, powerful functions
  5043. * for working with asynchronous JavaScript. Although originally designed for
  5044. * use with [Node.js](http://nodejs.org) and installable via
  5045. * `npm install --save async`, it can also be used directly in the browser.
  5046. * @module async
  5047. * @see AsyncFunction
  5048. */
  5049. /**
  5050. * A collection of `async` functions for manipulating collections, such as
  5051. * arrays and objects.
  5052. * @module Collections
  5053. */
  5054. /**
  5055. * A collection of `async` functions for controlling the flow through a script.
  5056. * @module ControlFlow
  5057. */
  5058. /**
  5059. * A collection of `async` utility functions.
  5060. * @module Utils
  5061. */
  5062. var index = {
  5063. apply: apply,
  5064. applyEach: applyEach,
  5065. applyEachSeries: applyEachSeries,
  5066. asyncify: asyncify,
  5067. auto: auto,
  5068. autoInject: autoInject,
  5069. cargo: cargo,
  5070. compose: compose,
  5071. concat: concat,
  5072. concatLimit: concatLimit,
  5073. concatSeries: concatSeries,
  5074. constant: constant,
  5075. detect: detect,
  5076. detectLimit: detectLimit,
  5077. detectSeries: detectSeries,
  5078. dir: dir,
  5079. doDuring: doDuring,
  5080. doUntil: doUntil,
  5081. doWhilst: doWhilst,
  5082. during: during,
  5083. each: eachLimit,
  5084. eachLimit: eachLimit$1,
  5085. eachOf: eachOf,
  5086. eachOfLimit: eachOfLimit,
  5087. eachOfSeries: eachOfSeries,
  5088. eachSeries: eachSeries,
  5089. ensureAsync: ensureAsync,
  5090. every: every,
  5091. everyLimit: everyLimit,
  5092. everySeries: everySeries,
  5093. filter: filter,
  5094. filterLimit: filterLimit,
  5095. filterSeries: filterSeries,
  5096. forever: forever,
  5097. groupBy: groupBy,
  5098. groupByLimit: groupByLimit,
  5099. groupBySeries: groupBySeries,
  5100. log: log,
  5101. map: map,
  5102. mapLimit: mapLimit,
  5103. mapSeries: mapSeries,
  5104. mapValues: mapValues,
  5105. mapValuesLimit: mapValuesLimit,
  5106. mapValuesSeries: mapValuesSeries,
  5107. memoize: memoize,
  5108. nextTick: nextTick,
  5109. parallel: parallelLimit,
  5110. parallelLimit: parallelLimit$1,
  5111. priorityQueue: priorityQueue,
  5112. queue: queue$1,
  5113. race: race,
  5114. reduce: reduce,
  5115. reduceRight: reduceRight,
  5116. reflect: reflect,
  5117. reflectAll: reflectAll,
  5118. reject: reject,
  5119. rejectLimit: rejectLimit,
  5120. rejectSeries: rejectSeries,
  5121. retry: retry,
  5122. retryable: retryable,
  5123. seq: seq,
  5124. series: series,
  5125. setImmediate: setImmediate$1,
  5126. some: some,
  5127. someLimit: someLimit,
  5128. someSeries: someSeries,
  5129. sortBy: sortBy,
  5130. timeout: timeout,
  5131. times: times,
  5132. timesLimit: timeLimit,
  5133. timesSeries: timesSeries,
  5134. transform: transform,
  5135. tryEach: tryEach,
  5136. unmemoize: unmemoize,
  5137. until: until,
  5138. waterfall: waterfall,
  5139. whilst: whilst,
  5140. // aliases
  5141. all: every,
  5142. allLimit: everyLimit,
  5143. allSeries: everySeries,
  5144. any: some,
  5145. anyLimit: someLimit,
  5146. anySeries: someSeries,
  5147. find: detect,
  5148. findLimit: detectLimit,
  5149. findSeries: detectSeries,
  5150. forEach: eachLimit,
  5151. forEachSeries: eachSeries,
  5152. forEachLimit: eachLimit$1,
  5153. forEachOf: eachOf,
  5154. forEachOfSeries: eachOfSeries,
  5155. forEachOfLimit: eachOfLimit,
  5156. inject: reduce,
  5157. foldl: reduce,
  5158. foldr: reduceRight,
  5159. select: filter,
  5160. selectLimit: filterLimit,
  5161. selectSeries: filterSeries,
  5162. wrapSync: asyncify
  5163. };
  5164. exports['default'] = index;
  5165. exports.apply = apply;
  5166. exports.applyEach = applyEach;
  5167. exports.applyEachSeries = applyEachSeries;
  5168. exports.asyncify = asyncify;
  5169. exports.auto = auto;
  5170. exports.autoInject = autoInject;
  5171. exports.cargo = cargo;
  5172. exports.compose = compose;
  5173. exports.concat = concat;
  5174. exports.concatLimit = concatLimit;
  5175. exports.concatSeries = concatSeries;
  5176. exports.constant = constant;
  5177. exports.detect = detect;
  5178. exports.detectLimit = detectLimit;
  5179. exports.detectSeries = detectSeries;
  5180. exports.dir = dir;
  5181. exports.doDuring = doDuring;
  5182. exports.doUntil = doUntil;
  5183. exports.doWhilst = doWhilst;
  5184. exports.during = during;
  5185. exports.each = eachLimit;
  5186. exports.eachLimit = eachLimit$1;
  5187. exports.eachOf = eachOf;
  5188. exports.eachOfLimit = eachOfLimit;
  5189. exports.eachOfSeries = eachOfSeries;
  5190. exports.eachSeries = eachSeries;
  5191. exports.ensureAsync = ensureAsync;
  5192. exports.every = every;
  5193. exports.everyLimit = everyLimit;
  5194. exports.everySeries = everySeries;
  5195. exports.filter = filter;
  5196. exports.filterLimit = filterLimit;
  5197. exports.filterSeries = filterSeries;
  5198. exports.forever = forever;
  5199. exports.groupBy = groupBy;
  5200. exports.groupByLimit = groupByLimit;
  5201. exports.groupBySeries = groupBySeries;
  5202. exports.log = log;
  5203. exports.map = map;
  5204. exports.mapLimit = mapLimit;
  5205. exports.mapSeries = mapSeries;
  5206. exports.mapValues = mapValues;
  5207. exports.mapValuesLimit = mapValuesLimit;
  5208. exports.mapValuesSeries = mapValuesSeries;
  5209. exports.memoize = memoize;
  5210. exports.nextTick = nextTick;
  5211. exports.parallel = parallelLimit;
  5212. exports.parallelLimit = parallelLimit$1;
  5213. exports.priorityQueue = priorityQueue;
  5214. exports.queue = queue$1;
  5215. exports.race = race;
  5216. exports.reduce = reduce;
  5217. exports.reduceRight = reduceRight;
  5218. exports.reflect = reflect;
  5219. exports.reflectAll = reflectAll;
  5220. exports.reject = reject;
  5221. exports.rejectLimit = rejectLimit;
  5222. exports.rejectSeries = rejectSeries;
  5223. exports.retry = retry;
  5224. exports.retryable = retryable;
  5225. exports.seq = seq;
  5226. exports.series = series;
  5227. exports.setImmediate = setImmediate$1;
  5228. exports.some = some;
  5229. exports.someLimit = someLimit;
  5230. exports.someSeries = someSeries;
  5231. exports.sortBy = sortBy;
  5232. exports.timeout = timeout;
  5233. exports.times = times;
  5234. exports.timesLimit = timeLimit;
  5235. exports.timesSeries = timesSeries;
  5236. exports.transform = transform;
  5237. exports.tryEach = tryEach;
  5238. exports.unmemoize = unmemoize;
  5239. exports.until = until;
  5240. exports.waterfall = waterfall;
  5241. exports.whilst = whilst;
  5242. exports.all = every;
  5243. exports.allLimit = everyLimit;
  5244. exports.allSeries = everySeries;
  5245. exports.any = some;
  5246. exports.anyLimit = someLimit;
  5247. exports.anySeries = someSeries;
  5248. exports.find = detect;
  5249. exports.findLimit = detectLimit;
  5250. exports.findSeries = detectSeries;
  5251. exports.forEach = eachLimit;
  5252. exports.forEachSeries = eachSeries;
  5253. exports.forEachLimit = eachLimit$1;
  5254. exports.forEachOf = eachOf;
  5255. exports.forEachOfSeries = eachOfSeries;
  5256. exports.forEachOfLimit = eachOfLimit;
  5257. exports.inject = reduce;
  5258. exports.foldl = reduce;
  5259. exports.foldr = reduceRight;
  5260. exports.select = filter;
  5261. exports.selectLimit = filterLimit;
  5262. exports.selectSeries = filterSeries;
  5263. exports.wrapSync = asyncify;
  5264. Object.defineProperty(exports, '__esModule', { value: true });
  5265. })));
  5266. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  5267. },{"_process":35,"timers":36}],3:[function(require,module,exports){
  5268. module.exports = require('./lib/axios');
  5269. },{"./lib/axios":5}],4:[function(require,module,exports){
  5270. 'use strict';
  5271. var utils = require('./../utils');
  5272. var settle = require('./../core/settle');
  5273. var cookies = require('./../helpers/cookies');
  5274. var buildURL = require('./../helpers/buildURL');
  5275. var buildFullPath = require('../core/buildFullPath');
  5276. var parseHeaders = require('./../helpers/parseHeaders');
  5277. var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
  5278. var createError = require('../core/createError');
  5279. module.exports = function xhrAdapter(config) {
  5280. return new Promise(function dispatchXhrRequest(resolve, reject) {
  5281. var requestData = config.data;
  5282. var requestHeaders = config.headers;
  5283. if (utils.isFormData(requestData)) {
  5284. delete requestHeaders['Content-Type']; // Let the browser set it
  5285. }
  5286. var request = new XMLHttpRequest();
  5287. // HTTP basic authentication
  5288. if (config.auth) {
  5289. var username = config.auth.username || '';
  5290. var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
  5291. requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
  5292. }
  5293. var fullPath = buildFullPath(config.baseURL, config.url);
  5294. request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
  5295. // Set the request timeout in MS
  5296. request.timeout = config.timeout;
  5297. // Listen for ready state
  5298. request.onreadystatechange = function handleLoad() {
  5299. if (!request || request.readyState !== 4) {
  5300. return;
  5301. }
  5302. // The request errored out and we didn't get a response, this will be
  5303. // handled by onerror instead
  5304. // With one exception: request that using file: protocol, most browsers
  5305. // will return status as 0 even though it's a successful request
  5306. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
  5307. return;
  5308. }
  5309. // Prepare the response
  5310. var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
  5311. var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
  5312. var response = {
  5313. data: responseData,
  5314. status: request.status,
  5315. statusText: request.statusText,
  5316. headers: responseHeaders,
  5317. config: config,
  5318. request: request
  5319. };
  5320. settle(resolve, reject, response);
  5321. // Clean up request
  5322. request = null;
  5323. };
  5324. // Handle browser request cancellation (as opposed to a manual cancellation)
  5325. request.onabort = function handleAbort() {
  5326. if (!request) {
  5327. return;
  5328. }
  5329. reject(createError('Request aborted', config, 'ECONNABORTED', request));
  5330. // Clean up request
  5331. request = null;
  5332. };
  5333. // Handle low level network errors
  5334. request.onerror = function handleError() {
  5335. // Real errors are hidden from us by the browser
  5336. // onerror should only fire if it's a network error
  5337. reject(createError('Network Error', config, null, request));
  5338. // Clean up request
  5339. request = null;
  5340. };
  5341. // Handle timeout
  5342. request.ontimeout = function handleTimeout() {
  5343. var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
  5344. if (config.timeoutErrorMessage) {
  5345. timeoutErrorMessage = config.timeoutErrorMessage;
  5346. }
  5347. reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
  5348. request));
  5349. // Clean up request
  5350. request = null;
  5351. };
  5352. // Add xsrf header
  5353. // This is only done if running in a standard browser environment.
  5354. // Specifically not if we're in a web worker, or react-native.
  5355. if (utils.isStandardBrowserEnv()) {
  5356. // Add xsrf header
  5357. var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
  5358. cookies.read(config.xsrfCookieName) :
  5359. undefined;
  5360. if (xsrfValue) {
  5361. requestHeaders[config.xsrfHeaderName] = xsrfValue;
  5362. }
  5363. }
  5364. // Add headers to the request
  5365. if ('setRequestHeader' in request) {
  5366. utils.forEach(requestHeaders, function setRequestHeader(val, key) {
  5367. if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
  5368. // Remove Content-Type if data is undefined
  5369. delete requestHeaders[key];
  5370. } else {
  5371. // Otherwise add header to the request
  5372. request.setRequestHeader(key, val);
  5373. }
  5374. });
  5375. }
  5376. // Add withCredentials to request if needed
  5377. if (!utils.isUndefined(config.withCredentials)) {
  5378. request.withCredentials = !!config.withCredentials;
  5379. }
  5380. // Add responseType to request if needed
  5381. if (config.responseType) {
  5382. try {
  5383. request.responseType = config.responseType;
  5384. } catch (e) {
  5385. // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
  5386. // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
  5387. if (config.responseType !== 'json') {
  5388. throw e;
  5389. }
  5390. }
  5391. }
  5392. // Handle progress if needed
  5393. if (typeof config.onDownloadProgress === 'function') {
  5394. request.addEventListener('progress', config.onDownloadProgress);
  5395. }
  5396. // Not all browsers support upload events
  5397. if (typeof config.onUploadProgress === 'function' && request.upload) {
  5398. request.upload.addEventListener('progress', config.onUploadProgress);
  5399. }
  5400. if (config.cancelToken) {
  5401. // Handle cancellation
  5402. config.cancelToken.promise.then(function onCanceled(cancel) {
  5403. if (!request) {
  5404. return;
  5405. }
  5406. request.abort();
  5407. reject(cancel);
  5408. // Clean up request
  5409. request = null;
  5410. });
  5411. }
  5412. if (!requestData) {
  5413. requestData = null;
  5414. }
  5415. // Send the request
  5416. request.send(requestData);
  5417. });
  5418. };
  5419. },{"../core/buildFullPath":11,"../core/createError":12,"./../core/settle":16,"./../helpers/buildURL":20,"./../helpers/cookies":22,"./../helpers/isURLSameOrigin":25,"./../helpers/parseHeaders":27,"./../utils":29}],5:[function(require,module,exports){
  5420. 'use strict';
  5421. var utils = require('./utils');
  5422. var bind = require('./helpers/bind');
  5423. var Axios = require('./core/Axios');
  5424. var mergeConfig = require('./core/mergeConfig');
  5425. var defaults = require('./defaults');
  5426. /**
  5427. * Create an instance of Axios
  5428. *
  5429. * @param {Object} defaultConfig The default config for the instance
  5430. * @return {Axios} A new instance of Axios
  5431. */
  5432. function createInstance(defaultConfig) {
  5433. var context = new Axios(defaultConfig);
  5434. var instance = bind(Axios.prototype.request, context);
  5435. // Copy axios.prototype to instance
  5436. utils.extend(instance, Axios.prototype, context);
  5437. // Copy context to instance
  5438. utils.extend(instance, context);
  5439. return instance;
  5440. }
  5441. // Create the default instance to be exported
  5442. var axios = createInstance(defaults);
  5443. // Expose Axios class to allow class inheritance
  5444. axios.Axios = Axios;
  5445. // Factory for creating new instances
  5446. axios.create = function create(instanceConfig) {
  5447. return createInstance(mergeConfig(axios.defaults, instanceConfig));
  5448. };
  5449. // Expose Cancel & CancelToken
  5450. axios.Cancel = require('./cancel/Cancel');
  5451. axios.CancelToken = require('./cancel/CancelToken');
  5452. axios.isCancel = require('./cancel/isCancel');
  5453. // Expose all/spread
  5454. axios.all = function all(promises) {
  5455. return Promise.all(promises);
  5456. };
  5457. axios.spread = require('./helpers/spread');
  5458. // Expose isAxiosError
  5459. axios.isAxiosError = require('./helpers/isAxiosError');
  5460. module.exports = axios;
  5461. // Allow use of default import syntax in TypeScript
  5462. module.exports.default = axios;
  5463. },{"./cancel/Cancel":6,"./cancel/CancelToken":7,"./cancel/isCancel":8,"./core/Axios":9,"./core/mergeConfig":15,"./defaults":18,"./helpers/bind":19,"./helpers/isAxiosError":24,"./helpers/spread":28,"./utils":29}],6:[function(require,module,exports){
  5464. 'use strict';
  5465. /**
  5466. * A `Cancel` is an object that is thrown when an operation is canceled.
  5467. *
  5468. * @class
  5469. * @param {string=} message The message.
  5470. */
  5471. function Cancel(message) {
  5472. this.message = message;
  5473. }
  5474. Cancel.prototype.toString = function toString() {
  5475. return 'Cancel' + (this.message ? ': ' + this.message : '');
  5476. };
  5477. Cancel.prototype.__CANCEL__ = true;
  5478. module.exports = Cancel;
  5479. },{}],7:[function(require,module,exports){
  5480. 'use strict';
  5481. var Cancel = require('./Cancel');
  5482. /**
  5483. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  5484. *
  5485. * @class
  5486. * @param {Function} executor The executor function.
  5487. */
  5488. function CancelToken(executor) {
  5489. if (typeof executor !== 'function') {
  5490. throw new TypeError('executor must be a function.');
  5491. }
  5492. var resolvePromise;
  5493. this.promise = new Promise(function promiseExecutor(resolve) {
  5494. resolvePromise = resolve;
  5495. });
  5496. var token = this;
  5497. executor(function cancel(message) {
  5498. if (token.reason) {
  5499. // Cancellation has already been requested
  5500. return;
  5501. }
  5502. token.reason = new Cancel(message);
  5503. resolvePromise(token.reason);
  5504. });
  5505. }
  5506. /**
  5507. * Throws a `Cancel` if cancellation has been requested.
  5508. */
  5509. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  5510. if (this.reason) {
  5511. throw this.reason;
  5512. }
  5513. };
  5514. /**
  5515. * Returns an object that contains a new `CancelToken` and a function that, when called,
  5516. * cancels the `CancelToken`.
  5517. */
  5518. CancelToken.source = function source() {
  5519. var cancel;
  5520. var token = new CancelToken(function executor(c) {
  5521. cancel = c;
  5522. });
  5523. return {
  5524. token: token,
  5525. cancel: cancel
  5526. };
  5527. };
  5528. module.exports = CancelToken;
  5529. },{"./Cancel":6}],8:[function(require,module,exports){
  5530. 'use strict';
  5531. module.exports = function isCancel(value) {
  5532. return !!(value && value.__CANCEL__);
  5533. };
  5534. },{}],9:[function(require,module,exports){
  5535. 'use strict';
  5536. var utils = require('./../utils');
  5537. var buildURL = require('../helpers/buildURL');
  5538. var InterceptorManager = require('./InterceptorManager');
  5539. var dispatchRequest = require('./dispatchRequest');
  5540. var mergeConfig = require('./mergeConfig');
  5541. /**
  5542. * Create a new instance of Axios
  5543. *
  5544. * @param {Object} instanceConfig The default config for the instance
  5545. */
  5546. function Axios(instanceConfig) {
  5547. this.defaults = instanceConfig;
  5548. this.interceptors = {
  5549. request: new InterceptorManager(),
  5550. response: new InterceptorManager()
  5551. };
  5552. }
  5553. /**
  5554. * Dispatch a request
  5555. *
  5556. * @param {Object} config The config specific for this request (merged with this.defaults)
  5557. */
  5558. Axios.prototype.request = function request(config) {
  5559. /*eslint no-param-reassign:0*/
  5560. // Allow for axios('example/url'[, config]) a la fetch API
  5561. if (typeof config === 'string') {
  5562. config = arguments[1] || {};
  5563. config.url = arguments[0];
  5564. } else {
  5565. config = config || {};
  5566. }
  5567. config = mergeConfig(this.defaults, config);
  5568. // Set config.method
  5569. if (config.method) {
  5570. config.method = config.method.toLowerCase();
  5571. } else if (this.defaults.method) {
  5572. config.method = this.defaults.method.toLowerCase();
  5573. } else {
  5574. config.method = 'get';
  5575. }
  5576. // Hook up interceptors middleware
  5577. var chain = [dispatchRequest, undefined];
  5578. var promise = Promise.resolve(config);
  5579. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  5580. chain.unshift(interceptor.fulfilled, interceptor.rejected);
  5581. });
  5582. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  5583. chain.push(interceptor.fulfilled, interceptor.rejected);
  5584. });
  5585. while (chain.length) {
  5586. promise = promise.then(chain.shift(), chain.shift());
  5587. }
  5588. return promise;
  5589. };
  5590. Axios.prototype.getUri = function getUri(config) {
  5591. config = mergeConfig(this.defaults, config);
  5592. return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
  5593. };
  5594. // Provide aliases for supported request methods
  5595. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  5596. /*eslint func-names:0*/
  5597. Axios.prototype[method] = function(url, config) {
  5598. return this.request(mergeConfig(config || {}, {
  5599. method: method,
  5600. url: url,
  5601. data: (config || {}).data
  5602. }));
  5603. };
  5604. });
  5605. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  5606. /*eslint func-names:0*/
  5607. Axios.prototype[method] = function(url, data, config) {
  5608. return this.request(mergeConfig(config || {}, {
  5609. method: method,
  5610. url: url,
  5611. data: data
  5612. }));
  5613. };
  5614. });
  5615. module.exports = Axios;
  5616. },{"../helpers/buildURL":20,"./../utils":29,"./InterceptorManager":10,"./dispatchRequest":13,"./mergeConfig":15}],10:[function(require,module,exports){
  5617. 'use strict';
  5618. var utils = require('./../utils');
  5619. function InterceptorManager() {
  5620. this.handlers = [];
  5621. }
  5622. /**
  5623. * Add a new interceptor to the stack
  5624. *
  5625. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  5626. * @param {Function} rejected The function to handle `reject` for a `Promise`
  5627. *
  5628. * @return {Number} An ID used to remove interceptor later
  5629. */
  5630. InterceptorManager.prototype.use = function use(fulfilled, rejected) {
  5631. this.handlers.push({
  5632. fulfilled: fulfilled,
  5633. rejected: rejected
  5634. });
  5635. return this.handlers.length - 1;
  5636. };
  5637. /**
  5638. * Remove an interceptor from the stack
  5639. *
  5640. * @param {Number} id The ID that was returned by `use`
  5641. */
  5642. InterceptorManager.prototype.eject = function eject(id) {
  5643. if (this.handlers[id]) {
  5644. this.handlers[id] = null;
  5645. }
  5646. };
  5647. /**
  5648. * Iterate over all the registered interceptors
  5649. *
  5650. * This method is particularly useful for skipping over any
  5651. * interceptors that may have become `null` calling `eject`.
  5652. *
  5653. * @param {Function} fn The function to call for each interceptor
  5654. */
  5655. InterceptorManager.prototype.forEach = function forEach(fn) {
  5656. utils.forEach(this.handlers, function forEachHandler(h) {
  5657. if (h !== null) {
  5658. fn(h);
  5659. }
  5660. });
  5661. };
  5662. module.exports = InterceptorManager;
  5663. },{"./../utils":29}],11:[function(require,module,exports){
  5664. 'use strict';
  5665. var isAbsoluteURL = require('../helpers/isAbsoluteURL');
  5666. var combineURLs = require('../helpers/combineURLs');
  5667. /**
  5668. * Creates a new URL by combining the baseURL with the requestedURL,
  5669. * only when the requestedURL is not already an absolute URL.
  5670. * If the requestURL is absolute, this function returns the requestedURL untouched.
  5671. *
  5672. * @param {string} baseURL The base URL
  5673. * @param {string} requestedURL Absolute or relative URL to combine
  5674. * @returns {string} The combined full path
  5675. */
  5676. module.exports = function buildFullPath(baseURL, requestedURL) {
  5677. if (baseURL && !isAbsoluteURL(requestedURL)) {
  5678. return combineURLs(baseURL, requestedURL);
  5679. }
  5680. return requestedURL;
  5681. };
  5682. },{"../helpers/combineURLs":21,"../helpers/isAbsoluteURL":23}],12:[function(require,module,exports){
  5683. 'use strict';
  5684. var enhanceError = require('./enhanceError');
  5685. /**
  5686. * Create an Error with the specified message, config, error code, request and response.
  5687. *
  5688. * @param {string} message The error message.
  5689. * @param {Object} config The config.
  5690. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  5691. * @param {Object} [request] The request.
  5692. * @param {Object} [response] The response.
  5693. * @returns {Error} The created error.
  5694. */
  5695. module.exports = function createError(message, config, code, request, response) {
  5696. var error = new Error(message);
  5697. return enhanceError(error, config, code, request, response);
  5698. };
  5699. },{"./enhanceError":14}],13:[function(require,module,exports){
  5700. 'use strict';
  5701. var utils = require('./../utils');
  5702. var transformData = require('./transformData');
  5703. var isCancel = require('../cancel/isCancel');
  5704. var defaults = require('../defaults');
  5705. /**
  5706. * Throws a `Cancel` if cancellation has been requested.
  5707. */
  5708. function throwIfCancellationRequested(config) {
  5709. if (config.cancelToken) {
  5710. config.cancelToken.throwIfRequested();
  5711. }
  5712. }
  5713. /**
  5714. * Dispatch a request to the server using the configured adapter.
  5715. *
  5716. * @param {object} config The config that is to be used for the request
  5717. * @returns {Promise} The Promise to be fulfilled
  5718. */
  5719. module.exports = function dispatchRequest(config) {
  5720. throwIfCancellationRequested(config);
  5721. // Ensure headers exist
  5722. config.headers = config.headers || {};
  5723. // Transform request data
  5724. config.data = transformData(
  5725. config.data,
  5726. config.headers,
  5727. config.transformRequest
  5728. );
  5729. // Flatten headers
  5730. config.headers = utils.merge(
  5731. config.headers.common || {},
  5732. config.headers[config.method] || {},
  5733. config.headers
  5734. );
  5735. utils.forEach(
  5736. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  5737. function cleanHeaderConfig(method) {
  5738. delete config.headers[method];
  5739. }
  5740. );
  5741. var adapter = config.adapter || defaults.adapter;
  5742. return adapter(config).then(function onAdapterResolution(response) {
  5743. throwIfCancellationRequested(config);
  5744. // Transform response data
  5745. response.data = transformData(
  5746. response.data,
  5747. response.headers,
  5748. config.transformResponse
  5749. );
  5750. return response;
  5751. }, function onAdapterRejection(reason) {
  5752. if (!isCancel(reason)) {
  5753. throwIfCancellationRequested(config);
  5754. // Transform response data
  5755. if (reason && reason.response) {
  5756. reason.response.data = transformData(
  5757. reason.response.data,
  5758. reason.response.headers,
  5759. config.transformResponse
  5760. );
  5761. }
  5762. }
  5763. return Promise.reject(reason);
  5764. });
  5765. };
  5766. },{"../cancel/isCancel":8,"../defaults":18,"./../utils":29,"./transformData":17}],14:[function(require,module,exports){
  5767. 'use strict';
  5768. /**
  5769. * Update an Error with the specified config, error code, and response.
  5770. *
  5771. * @param {Error} error The error to update.
  5772. * @param {Object} config The config.
  5773. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  5774. * @param {Object} [request] The request.
  5775. * @param {Object} [response] The response.
  5776. * @returns {Error} The error.
  5777. */
  5778. module.exports = function enhanceError(error, config, code, request, response) {
  5779. error.config = config;
  5780. if (code) {
  5781. error.code = code;
  5782. }
  5783. error.request = request;
  5784. error.response = response;
  5785. error.isAxiosError = true;
  5786. error.toJSON = function toJSON() {
  5787. return {
  5788. // Standard
  5789. message: this.message,
  5790. name: this.name,
  5791. // Microsoft
  5792. description: this.description,
  5793. number: this.number,
  5794. // Mozilla
  5795. fileName: this.fileName,
  5796. lineNumber: this.lineNumber,
  5797. columnNumber: this.columnNumber,
  5798. stack: this.stack,
  5799. // Axios
  5800. config: this.config,
  5801. code: this.code
  5802. };
  5803. };
  5804. return error;
  5805. };
  5806. },{}],15:[function(require,module,exports){
  5807. 'use strict';
  5808. var utils = require('../utils');
  5809. /**
  5810. * Config-specific merge-function which creates a new config-object
  5811. * by merging two configuration objects together.
  5812. *
  5813. * @param {Object} config1
  5814. * @param {Object} config2
  5815. * @returns {Object} New object resulting from merging config2 to config1
  5816. */
  5817. module.exports = function mergeConfig(config1, config2) {
  5818. // eslint-disable-next-line no-param-reassign
  5819. config2 = config2 || {};
  5820. var config = {};
  5821. var valueFromConfig2Keys = ['url', 'method', 'data'];
  5822. var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];
  5823. var defaultToConfig2Keys = [
  5824. 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
  5825. 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
  5826. 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',
  5827. 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',
  5828. 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'
  5829. ];
  5830. var directMergeKeys = ['validateStatus'];
  5831. function getMergedValue(target, source) {
  5832. if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
  5833. return utils.merge(target, source);
  5834. } else if (utils.isPlainObject(source)) {
  5835. return utils.merge({}, source);
  5836. } else if (utils.isArray(source)) {
  5837. return source.slice();
  5838. }
  5839. return source;
  5840. }
  5841. function mergeDeepProperties(prop) {
  5842. if (!utils.isUndefined(config2[prop])) {
  5843. config[prop] = getMergedValue(config1[prop], config2[prop]);
  5844. } else if (!utils.isUndefined(config1[prop])) {
  5845. config[prop] = getMergedValue(undefined, config1[prop]);
  5846. }
  5847. }
  5848. utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
  5849. if (!utils.isUndefined(config2[prop])) {
  5850. config[prop] = getMergedValue(undefined, config2[prop]);
  5851. }
  5852. });
  5853. utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
  5854. utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
  5855. if (!utils.isUndefined(config2[prop])) {
  5856. config[prop] = getMergedValue(undefined, config2[prop]);
  5857. } else if (!utils.isUndefined(config1[prop])) {
  5858. config[prop] = getMergedValue(undefined, config1[prop]);
  5859. }
  5860. });
  5861. utils.forEach(directMergeKeys, function merge(prop) {
  5862. if (prop in config2) {
  5863. config[prop] = getMergedValue(config1[prop], config2[prop]);
  5864. } else if (prop in config1) {
  5865. config[prop] = getMergedValue(undefined, config1[prop]);
  5866. }
  5867. });
  5868. var axiosKeys = valueFromConfig2Keys
  5869. .concat(mergeDeepPropertiesKeys)
  5870. .concat(defaultToConfig2Keys)
  5871. .concat(directMergeKeys);
  5872. var otherKeys = Object
  5873. .keys(config1)
  5874. .concat(Object.keys(config2))
  5875. .filter(function filterAxiosKeys(key) {
  5876. return axiosKeys.indexOf(key) === -1;
  5877. });
  5878. utils.forEach(otherKeys, mergeDeepProperties);
  5879. return config;
  5880. };
  5881. },{"../utils":29}],16:[function(require,module,exports){
  5882. 'use strict';
  5883. var createError = require('./createError');
  5884. /**
  5885. * Resolve or reject a Promise based on response status.
  5886. *
  5887. * @param {Function} resolve A function that resolves the promise.
  5888. * @param {Function} reject A function that rejects the promise.
  5889. * @param {object} response The response.
  5890. */
  5891. module.exports = function settle(resolve, reject, response) {
  5892. var validateStatus = response.config.validateStatus;
  5893. if (!response.status || !validateStatus || validateStatus(response.status)) {
  5894. resolve(response);
  5895. } else {
  5896. reject(createError(
  5897. 'Request failed with status code ' + response.status,
  5898. response.config,
  5899. null,
  5900. response.request,
  5901. response
  5902. ));
  5903. }
  5904. };
  5905. },{"./createError":12}],17:[function(require,module,exports){
  5906. 'use strict';
  5907. var utils = require('./../utils');
  5908. /**
  5909. * Transform the data for a request or a response
  5910. *
  5911. * @param {Object|String} data The data to be transformed
  5912. * @param {Array} headers The headers for the request or response
  5913. * @param {Array|Function} fns A single function or Array of functions
  5914. * @returns {*} The resulting transformed data
  5915. */
  5916. module.exports = function transformData(data, headers, fns) {
  5917. /*eslint no-param-reassign:0*/
  5918. utils.forEach(fns, function transform(fn) {
  5919. data = fn(data, headers);
  5920. });
  5921. return data;
  5922. };
  5923. },{"./../utils":29}],18:[function(require,module,exports){
  5924. (function (process){(function (){
  5925. 'use strict';
  5926. var utils = require('./utils');
  5927. var normalizeHeaderName = require('./helpers/normalizeHeaderName');
  5928. var DEFAULT_CONTENT_TYPE = {
  5929. 'Content-Type': 'application/x-www-form-urlencoded'
  5930. };
  5931. function setContentTypeIfUnset(headers, value) {
  5932. if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
  5933. headers['Content-Type'] = value;
  5934. }
  5935. }
  5936. function getDefaultAdapter() {
  5937. var adapter;
  5938. if (typeof XMLHttpRequest !== 'undefined') {
  5939. // For browsers use XHR adapter
  5940. adapter = require('./adapters/xhr');
  5941. } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
  5942. // For node use HTTP adapter
  5943. adapter = require('./adapters/http');
  5944. }
  5945. return adapter;
  5946. }
  5947. var defaults = {
  5948. adapter: getDefaultAdapter(),
  5949. transformRequest: [function transformRequest(data, headers) {
  5950. normalizeHeaderName(headers, 'Accept');
  5951. normalizeHeaderName(headers, 'Content-Type');
  5952. if (utils.isFormData(data) ||
  5953. utils.isArrayBuffer(data) ||
  5954. utils.isBuffer(data) ||
  5955. utils.isStream(data) ||
  5956. utils.isFile(data) ||
  5957. utils.isBlob(data)
  5958. ) {
  5959. return data;
  5960. }
  5961. if (utils.isArrayBufferView(data)) {
  5962. return data.buffer;
  5963. }
  5964. if (utils.isURLSearchParams(data)) {
  5965. setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
  5966. return data.toString();
  5967. }
  5968. if (utils.isObject(data)) {
  5969. setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
  5970. return JSON.stringify(data);
  5971. }
  5972. return data;
  5973. }],
  5974. transformResponse: [function transformResponse(data) {
  5975. /*eslint no-param-reassign:0*/
  5976. if (typeof data === 'string') {
  5977. try {
  5978. data = JSON.parse(data);
  5979. } catch (e) { /* Ignore */ }
  5980. }
  5981. return data;
  5982. }],
  5983. /**
  5984. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  5985. * timeout is not created.
  5986. */
  5987. timeout: 0,
  5988. xsrfCookieName: 'XSRF-TOKEN',
  5989. xsrfHeaderName: 'X-XSRF-TOKEN',
  5990. maxContentLength: -1,
  5991. maxBodyLength: -1,
  5992. validateStatus: function validateStatus(status) {
  5993. return status >= 200 && status < 300;
  5994. }
  5995. };
  5996. defaults.headers = {
  5997. common: {
  5998. 'Accept': 'application/json, text/plain, */*'
  5999. }
  6000. };
  6001. utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
  6002. defaults.headers[method] = {};
  6003. });
  6004. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  6005. defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  6006. });
  6007. module.exports = defaults;
  6008. }).call(this)}).call(this,require('_process'))
  6009. },{"./adapters/http":4,"./adapters/xhr":4,"./helpers/normalizeHeaderName":26,"./utils":29,"_process":35}],19:[function(require,module,exports){
  6010. 'use strict';
  6011. module.exports = function bind(fn, thisArg) {
  6012. return function wrap() {
  6013. var args = new Array(arguments.length);
  6014. for (var i = 0; i < args.length; i++) {
  6015. args[i] = arguments[i];
  6016. }
  6017. return fn.apply(thisArg, args);
  6018. };
  6019. };
  6020. },{}],20:[function(require,module,exports){
  6021. 'use strict';
  6022. var utils = require('./../utils');
  6023. function encode(val) {
  6024. return encodeURIComponent(val).
  6025. replace(/%3A/gi, ':').
  6026. replace(/%24/g, '$').
  6027. replace(/%2C/gi, ',').
  6028. replace(/%20/g, '+').
  6029. replace(/%5B/gi, '[').
  6030. replace(/%5D/gi, ']');
  6031. }
  6032. /**
  6033. * Build a URL by appending params to the end
  6034. *
  6035. * @param {string} url The base of the url (e.g., http://www.google.com)
  6036. * @param {object} [params] The params to be appended
  6037. * @returns {string} The formatted url
  6038. */
  6039. module.exports = function buildURL(url, params, paramsSerializer) {
  6040. /*eslint no-param-reassign:0*/
  6041. if (!params) {
  6042. return url;
  6043. }
  6044. var serializedParams;
  6045. if (paramsSerializer) {
  6046. serializedParams = paramsSerializer(params);
  6047. } else if (utils.isURLSearchParams(params)) {
  6048. serializedParams = params.toString();
  6049. } else {
  6050. var parts = [];
  6051. utils.forEach(params, function serialize(val, key) {
  6052. if (val === null || typeof val === 'undefined') {
  6053. return;
  6054. }
  6055. if (utils.isArray(val)) {
  6056. key = key + '[]';
  6057. } else {
  6058. val = [val];
  6059. }
  6060. utils.forEach(val, function parseValue(v) {
  6061. if (utils.isDate(v)) {
  6062. v = v.toISOString();
  6063. } else if (utils.isObject(v)) {
  6064. v = JSON.stringify(v);
  6065. }
  6066. parts.push(encode(key) + '=' + encode(v));
  6067. });
  6068. });
  6069. serializedParams = parts.join('&');
  6070. }
  6071. if (serializedParams) {
  6072. var hashmarkIndex = url.indexOf('#');
  6073. if (hashmarkIndex !== -1) {
  6074. url = url.slice(0, hashmarkIndex);
  6075. }
  6076. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  6077. }
  6078. return url;
  6079. };
  6080. },{"./../utils":29}],21:[function(require,module,exports){
  6081. 'use strict';
  6082. /**
  6083. * Creates a new URL by combining the specified URLs
  6084. *
  6085. * @param {string} baseURL The base URL
  6086. * @param {string} relativeURL The relative URL
  6087. * @returns {string} The combined URL
  6088. */
  6089. module.exports = function combineURLs(baseURL, relativeURL) {
  6090. return relativeURL
  6091. ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
  6092. : baseURL;
  6093. };
  6094. },{}],22:[function(require,module,exports){
  6095. 'use strict';
  6096. var utils = require('./../utils');
  6097. module.exports = (
  6098. utils.isStandardBrowserEnv() ?
  6099. // Standard browser envs support document.cookie
  6100. (function standardBrowserEnv() {
  6101. return {
  6102. write: function write(name, value, expires, path, domain, secure) {
  6103. var cookie = [];
  6104. cookie.push(name + '=' + encodeURIComponent(value));
  6105. if (utils.isNumber(expires)) {
  6106. cookie.push('expires=' + new Date(expires).toGMTString());
  6107. }
  6108. if (utils.isString(path)) {
  6109. cookie.push('path=' + path);
  6110. }
  6111. if (utils.isString(domain)) {
  6112. cookie.push('domain=' + domain);
  6113. }
  6114. if (secure === true) {
  6115. cookie.push('secure');
  6116. }
  6117. document.cookie = cookie.join('; ');
  6118. },
  6119. read: function read(name) {
  6120. var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  6121. return (match ? decodeURIComponent(match[3]) : null);
  6122. },
  6123. remove: function remove(name) {
  6124. this.write(name, '', Date.now() - 86400000);
  6125. }
  6126. };
  6127. })() :
  6128. // Non standard browser env (web workers, react-native) lack needed support.
  6129. (function nonStandardBrowserEnv() {
  6130. return {
  6131. write: function write() {},
  6132. read: function read() { return null; },
  6133. remove: function remove() {}
  6134. };
  6135. })()
  6136. );
  6137. },{"./../utils":29}],23:[function(require,module,exports){
  6138. 'use strict';
  6139. /**
  6140. * Determines whether the specified URL is absolute
  6141. *
  6142. * @param {string} url The URL to test
  6143. * @returns {boolean} True if the specified URL is absolute, otherwise false
  6144. */
  6145. module.exports = function isAbsoluteURL(url) {
  6146. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  6147. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  6148. // by any combination of letters, digits, plus, period, or hyphen.
  6149. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
  6150. };
  6151. },{}],24:[function(require,module,exports){
  6152. 'use strict';
  6153. /**
  6154. * Determines whether the payload is an error thrown by Axios
  6155. *
  6156. * @param {*} payload The value to test
  6157. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  6158. */
  6159. module.exports = function isAxiosError(payload) {
  6160. return (typeof payload === 'object') && (payload.isAxiosError === true);
  6161. };
  6162. },{}],25:[function(require,module,exports){
  6163. 'use strict';
  6164. var utils = require('./../utils');
  6165. module.exports = (
  6166. utils.isStandardBrowserEnv() ?
  6167. // Standard browser envs have full support of the APIs needed to test
  6168. // whether the request URL is of the same origin as current location.
  6169. (function standardBrowserEnv() {
  6170. var msie = /(msie|trident)/i.test(navigator.userAgent);
  6171. var urlParsingNode = document.createElement('a');
  6172. var originURL;
  6173. /**
  6174. * Parse a URL to discover it's components
  6175. *
  6176. * @param {String} url The URL to be parsed
  6177. * @returns {Object}
  6178. */
  6179. function resolveURL(url) {
  6180. var href = url;
  6181. if (msie) {
  6182. // IE needs attribute set twice to normalize properties
  6183. urlParsingNode.setAttribute('href', href);
  6184. href = urlParsingNode.href;
  6185. }
  6186. urlParsingNode.setAttribute('href', href);
  6187. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  6188. return {
  6189. href: urlParsingNode.href,
  6190. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  6191. host: urlParsingNode.host,
  6192. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  6193. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  6194. hostname: urlParsingNode.hostname,
  6195. port: urlParsingNode.port,
  6196. pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
  6197. urlParsingNode.pathname :
  6198. '/' + urlParsingNode.pathname
  6199. };
  6200. }
  6201. originURL = resolveURL(window.location.href);
  6202. /**
  6203. * Determine if a URL shares the same origin as the current location
  6204. *
  6205. * @param {String} requestURL The URL to test
  6206. * @returns {boolean} True if URL shares the same origin, otherwise false
  6207. */
  6208. return function isURLSameOrigin(requestURL) {
  6209. var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
  6210. return (parsed.protocol === originURL.protocol &&
  6211. parsed.host === originURL.host);
  6212. };
  6213. })() :
  6214. // Non standard browser envs (web workers, react-native) lack needed support.
  6215. (function nonStandardBrowserEnv() {
  6216. return function isURLSameOrigin() {
  6217. return true;
  6218. };
  6219. })()
  6220. );
  6221. },{"./../utils":29}],26:[function(require,module,exports){
  6222. 'use strict';
  6223. var utils = require('../utils');
  6224. module.exports = function normalizeHeaderName(headers, normalizedName) {
  6225. utils.forEach(headers, function processHeader(value, name) {
  6226. if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
  6227. headers[normalizedName] = value;
  6228. delete headers[name];
  6229. }
  6230. });
  6231. };
  6232. },{"../utils":29}],27:[function(require,module,exports){
  6233. 'use strict';
  6234. var utils = require('./../utils');
  6235. // Headers whose duplicates are ignored by node
  6236. // c.f. https://nodejs.org/api/http.html#http_message_headers
  6237. var ignoreDuplicateOf = [
  6238. 'age', 'authorization', 'content-length', 'content-type', 'etag',
  6239. 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  6240. 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  6241. 'referer', 'retry-after', 'user-agent'
  6242. ];
  6243. /**
  6244. * Parse headers into an object
  6245. *
  6246. * ```
  6247. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  6248. * Content-Type: application/json
  6249. * Connection: keep-alive
  6250. * Transfer-Encoding: chunked
  6251. * ```
  6252. *
  6253. * @param {String} headers Headers needing to be parsed
  6254. * @returns {Object} Headers parsed into an object
  6255. */
  6256. module.exports = function parseHeaders(headers) {
  6257. var parsed = {};
  6258. var key;
  6259. var val;
  6260. var i;
  6261. if (!headers) { return parsed; }
  6262. utils.forEach(headers.split('\n'), function parser(line) {
  6263. i = line.indexOf(':');
  6264. key = utils.trim(line.substr(0, i)).toLowerCase();
  6265. val = utils.trim(line.substr(i + 1));
  6266. if (key) {
  6267. if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
  6268. return;
  6269. }
  6270. if (key === 'set-cookie') {
  6271. parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
  6272. } else {
  6273. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  6274. }
  6275. }
  6276. });
  6277. return parsed;
  6278. };
  6279. },{"./../utils":29}],28:[function(require,module,exports){
  6280. 'use strict';
  6281. /**
  6282. * Syntactic sugar for invoking a function and expanding an array for arguments.
  6283. *
  6284. * Common use case would be to use `Function.prototype.apply`.
  6285. *
  6286. * ```js
  6287. * function f(x, y, z) {}
  6288. * var args = [1, 2, 3];
  6289. * f.apply(null, args);
  6290. * ```
  6291. *
  6292. * With `spread` this example can be re-written.
  6293. *
  6294. * ```js
  6295. * spread(function(x, y, z) {})([1, 2, 3]);
  6296. * ```
  6297. *
  6298. * @param {Function} callback
  6299. * @returns {Function}
  6300. */
  6301. module.exports = function spread(callback) {
  6302. return function wrap(arr) {
  6303. return callback.apply(null, arr);
  6304. };
  6305. };
  6306. },{}],29:[function(require,module,exports){
  6307. 'use strict';
  6308. var bind = require('./helpers/bind');
  6309. /*global toString:true*/
  6310. // utils is a library of generic helper functions non-specific to axios
  6311. var toString = Object.prototype.toString;
  6312. /**
  6313. * Determine if a value is an Array
  6314. *
  6315. * @param {Object} val The value to test
  6316. * @returns {boolean} True if value is an Array, otherwise false
  6317. */
  6318. function isArray(val) {
  6319. return toString.call(val) === '[object Array]';
  6320. }
  6321. /**
  6322. * Determine if a value is undefined
  6323. *
  6324. * @param {Object} val The value to test
  6325. * @returns {boolean} True if the value is undefined, otherwise false
  6326. */
  6327. function isUndefined(val) {
  6328. return typeof val === 'undefined';
  6329. }
  6330. /**
  6331. * Determine if a value is a Buffer
  6332. *
  6333. * @param {Object} val The value to test
  6334. * @returns {boolean} True if value is a Buffer, otherwise false
  6335. */
  6336. function isBuffer(val) {
  6337. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
  6338. && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
  6339. }
  6340. /**
  6341. * Determine if a value is an ArrayBuffer
  6342. *
  6343. * @param {Object} val The value to test
  6344. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  6345. */
  6346. function isArrayBuffer(val) {
  6347. return toString.call(val) === '[object ArrayBuffer]';
  6348. }
  6349. /**
  6350. * Determine if a value is a FormData
  6351. *
  6352. * @param {Object} val The value to test
  6353. * @returns {boolean} True if value is an FormData, otherwise false
  6354. */
  6355. function isFormData(val) {
  6356. return (typeof FormData !== 'undefined') && (val instanceof FormData);
  6357. }
  6358. /**
  6359. * Determine if a value is a view on an ArrayBuffer
  6360. *
  6361. * @param {Object} val The value to test
  6362. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  6363. */
  6364. function isArrayBufferView(val) {
  6365. var result;
  6366. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  6367. result = ArrayBuffer.isView(val);
  6368. } else {
  6369. result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
  6370. }
  6371. return result;
  6372. }
  6373. /**
  6374. * Determine if a value is a String
  6375. *
  6376. * @param {Object} val The value to test
  6377. * @returns {boolean} True if value is a String, otherwise false
  6378. */
  6379. function isString(val) {
  6380. return typeof val === 'string';
  6381. }
  6382. /**
  6383. * Determine if a value is a Number
  6384. *
  6385. * @param {Object} val The value to test
  6386. * @returns {boolean} True if value is a Number, otherwise false
  6387. */
  6388. function isNumber(val) {
  6389. return typeof val === 'number';
  6390. }
  6391. /**
  6392. * Determine if a value is an Object
  6393. *
  6394. * @param {Object} val The value to test
  6395. * @returns {boolean} True if value is an Object, otherwise false
  6396. */
  6397. function isObject(val) {
  6398. return val !== null && typeof val === 'object';
  6399. }
  6400. /**
  6401. * Determine if a value is a plain Object
  6402. *
  6403. * @param {Object} val The value to test
  6404. * @return {boolean} True if value is a plain Object, otherwise false
  6405. */
  6406. function isPlainObject(val) {
  6407. if (toString.call(val) !== '[object Object]') {
  6408. return false;
  6409. }
  6410. var prototype = Object.getPrototypeOf(val);
  6411. return prototype === null || prototype === Object.prototype;
  6412. }
  6413. /**
  6414. * Determine if a value is a Date
  6415. *
  6416. * @param {Object} val The value to test
  6417. * @returns {boolean} True if value is a Date, otherwise false
  6418. */
  6419. function isDate(val) {
  6420. return toString.call(val) === '[object Date]';
  6421. }
  6422. /**
  6423. * Determine if a value is a File
  6424. *
  6425. * @param {Object} val The value to test
  6426. * @returns {boolean} True if value is a File, otherwise false
  6427. */
  6428. function isFile(val) {
  6429. return toString.call(val) === '[object File]';
  6430. }
  6431. /**
  6432. * Determine if a value is a Blob
  6433. *
  6434. * @param {Object} val The value to test
  6435. * @returns {boolean} True if value is a Blob, otherwise false
  6436. */
  6437. function isBlob(val) {
  6438. return toString.call(val) === '[object Blob]';
  6439. }
  6440. /**
  6441. * Determine if a value is a Function
  6442. *
  6443. * @param {Object} val The value to test
  6444. * @returns {boolean} True if value is a Function, otherwise false
  6445. */
  6446. function isFunction(val) {
  6447. return toString.call(val) === '[object Function]';
  6448. }
  6449. /**
  6450. * Determine if a value is a Stream
  6451. *
  6452. * @param {Object} val The value to test
  6453. * @returns {boolean} True if value is a Stream, otherwise false
  6454. */
  6455. function isStream(val) {
  6456. return isObject(val) && isFunction(val.pipe);
  6457. }
  6458. /**
  6459. * Determine if a value is a URLSearchParams object
  6460. *
  6461. * @param {Object} val The value to test
  6462. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  6463. */
  6464. function isURLSearchParams(val) {
  6465. return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
  6466. }
  6467. /**
  6468. * Trim excess whitespace off the beginning and end of a string
  6469. *
  6470. * @param {String} str The String to trim
  6471. * @returns {String} The String freed of excess whitespace
  6472. */
  6473. function trim(str) {
  6474. return str.replace(/^\s*/, '').replace(/\s*$/, '');
  6475. }
  6476. /**
  6477. * Determine if we're running in a standard browser environment
  6478. *
  6479. * This allows axios to run in a web worker, and react-native.
  6480. * Both environments support XMLHttpRequest, but not fully standard globals.
  6481. *
  6482. * web workers:
  6483. * typeof window -> undefined
  6484. * typeof document -> undefined
  6485. *
  6486. * react-native:
  6487. * navigator.product -> 'ReactNative'
  6488. * nativescript
  6489. * navigator.product -> 'NativeScript' or 'NS'
  6490. */
  6491. function isStandardBrowserEnv() {
  6492. if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
  6493. navigator.product === 'NativeScript' ||
  6494. navigator.product === 'NS')) {
  6495. return false;
  6496. }
  6497. return (
  6498. typeof window !== 'undefined' &&
  6499. typeof document !== 'undefined'
  6500. );
  6501. }
  6502. /**
  6503. * Iterate over an Array or an Object invoking a function for each item.
  6504. *
  6505. * If `obj` is an Array callback will be called passing
  6506. * the value, index, and complete array for each item.
  6507. *
  6508. * If 'obj' is an Object callback will be called passing
  6509. * the value, key, and complete object for each property.
  6510. *
  6511. * @param {Object|Array} obj The object to iterate
  6512. * @param {Function} fn The callback to invoke for each item
  6513. */
  6514. function forEach(obj, fn) {
  6515. // Don't bother if no value provided
  6516. if (obj === null || typeof obj === 'undefined') {
  6517. return;
  6518. }
  6519. // Force an array if not already something iterable
  6520. if (typeof obj !== 'object') {
  6521. /*eslint no-param-reassign:0*/
  6522. obj = [obj];
  6523. }
  6524. if (isArray(obj)) {
  6525. // Iterate over array values
  6526. for (var i = 0, l = obj.length; i < l; i++) {
  6527. fn.call(null, obj[i], i, obj);
  6528. }
  6529. } else {
  6530. // Iterate over object keys
  6531. for (var key in obj) {
  6532. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  6533. fn.call(null, obj[key], key, obj);
  6534. }
  6535. }
  6536. }
  6537. }
  6538. /**
  6539. * Accepts varargs expecting each argument to be an object, then
  6540. * immutably merges the properties of each object and returns result.
  6541. *
  6542. * When multiple objects contain the same key the later object in
  6543. * the arguments list will take precedence.
  6544. *
  6545. * Example:
  6546. *
  6547. * ```js
  6548. * var result = merge({foo: 123}, {foo: 456});
  6549. * console.log(result.foo); // outputs 456
  6550. * ```
  6551. *
  6552. * @param {Object} obj1 Object to merge
  6553. * @returns {Object} Result of all merge properties
  6554. */
  6555. function merge(/* obj1, obj2, obj3, ... */) {
  6556. var result = {};
  6557. function assignValue(val, key) {
  6558. if (isPlainObject(result[key]) && isPlainObject(val)) {
  6559. result[key] = merge(result[key], val);
  6560. } else if (isPlainObject(val)) {
  6561. result[key] = merge({}, val);
  6562. } else if (isArray(val)) {
  6563. result[key] = val.slice();
  6564. } else {
  6565. result[key] = val;
  6566. }
  6567. }
  6568. for (var i = 0, l = arguments.length; i < l; i++) {
  6569. forEach(arguments[i], assignValue);
  6570. }
  6571. return result;
  6572. }
  6573. /**
  6574. * Extends object a by mutably adding to it the properties of object b.
  6575. *
  6576. * @param {Object} a The object to be extended
  6577. * @param {Object} b The object to copy properties from
  6578. * @param {Object} thisArg The object to bind function to
  6579. * @return {Object} The resulting value of object a
  6580. */
  6581. function extend(a, b, thisArg) {
  6582. forEach(b, function assignValue(val, key) {
  6583. if (thisArg && typeof val === 'function') {
  6584. a[key] = bind(val, thisArg);
  6585. } else {
  6586. a[key] = val;
  6587. }
  6588. });
  6589. return a;
  6590. }
  6591. /**
  6592. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  6593. *
  6594. * @param {string} content with BOM
  6595. * @return {string} content value without BOM
  6596. */
  6597. function stripBOM(content) {
  6598. if (content.charCodeAt(0) === 0xFEFF) {
  6599. content = content.slice(1);
  6600. }
  6601. return content;
  6602. }
  6603. module.exports = {
  6604. isArray: isArray,
  6605. isArrayBuffer: isArrayBuffer,
  6606. isBuffer: isBuffer,
  6607. isFormData: isFormData,
  6608. isArrayBufferView: isArrayBufferView,
  6609. isString: isString,
  6610. isNumber: isNumber,
  6611. isObject: isObject,
  6612. isPlainObject: isPlainObject,
  6613. isUndefined: isUndefined,
  6614. isDate: isDate,
  6615. isFile: isFile,
  6616. isBlob: isBlob,
  6617. isFunction: isFunction,
  6618. isStream: isStream,
  6619. isURLSearchParams: isURLSearchParams,
  6620. isStandardBrowserEnv: isStandardBrowserEnv,
  6621. forEach: forEach,
  6622. merge: merge,
  6623. extend: extend,
  6624. trim: trim,
  6625. stripBOM: stripBOM
  6626. };
  6627. },{"./helpers/bind":19}],30:[function(require,module,exports){
  6628. },{}],31:[function(require,module,exports){
  6629. (function (process){(function (){
  6630. /* eslint-env browser */
  6631. /**
  6632. * This is the web browser implementation of `debug()`.
  6633. */
  6634. exports.formatArgs = formatArgs;
  6635. exports.save = save;
  6636. exports.load = load;
  6637. exports.useColors = useColors;
  6638. exports.storage = localstorage();
  6639. exports.destroy = (() => {
  6640. let warned = false;
  6641. return () => {
  6642. if (!warned) {
  6643. warned = true;
  6644. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  6645. }
  6646. };
  6647. })();
  6648. /**
  6649. * Colors.
  6650. */
  6651. exports.colors = [
  6652. '#0000CC',
  6653. '#0000FF',
  6654. '#0033CC',
  6655. '#0033FF',
  6656. '#0066CC',
  6657. '#0066FF',
  6658. '#0099CC',
  6659. '#0099FF',
  6660. '#00CC00',
  6661. '#00CC33',
  6662. '#00CC66',
  6663. '#00CC99',
  6664. '#00CCCC',
  6665. '#00CCFF',
  6666. '#3300CC',
  6667. '#3300FF',
  6668. '#3333CC',
  6669. '#3333FF',
  6670. '#3366CC',
  6671. '#3366FF',
  6672. '#3399CC',
  6673. '#3399FF',
  6674. '#33CC00',
  6675. '#33CC33',
  6676. '#33CC66',
  6677. '#33CC99',
  6678. '#33CCCC',
  6679. '#33CCFF',
  6680. '#6600CC',
  6681. '#6600FF',
  6682. '#6633CC',
  6683. '#6633FF',
  6684. '#66CC00',
  6685. '#66CC33',
  6686. '#9900CC',
  6687. '#9900FF',
  6688. '#9933CC',
  6689. '#9933FF',
  6690. '#99CC00',
  6691. '#99CC33',
  6692. '#CC0000',
  6693. '#CC0033',
  6694. '#CC0066',
  6695. '#CC0099',
  6696. '#CC00CC',
  6697. '#CC00FF',
  6698. '#CC3300',
  6699. '#CC3333',
  6700. '#CC3366',
  6701. '#CC3399',
  6702. '#CC33CC',
  6703. '#CC33FF',
  6704. '#CC6600',
  6705. '#CC6633',
  6706. '#CC9900',
  6707. '#CC9933',
  6708. '#CCCC00',
  6709. '#CCCC33',
  6710. '#FF0000',
  6711. '#FF0033',
  6712. '#FF0066',
  6713. '#FF0099',
  6714. '#FF00CC',
  6715. '#FF00FF',
  6716. '#FF3300',
  6717. '#FF3333',
  6718. '#FF3366',
  6719. '#FF3399',
  6720. '#FF33CC',
  6721. '#FF33FF',
  6722. '#FF6600',
  6723. '#FF6633',
  6724. '#FF9900',
  6725. '#FF9933',
  6726. '#FFCC00',
  6727. '#FFCC33'
  6728. ];
  6729. /**
  6730. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  6731. * and the Firebug extension (any Firefox version) are known
  6732. * to support "%c" CSS customizations.
  6733. *
  6734. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  6735. */
  6736. // eslint-disable-next-line complexity
  6737. function useColors() {
  6738. // NB: In an Electron preload script, document will be defined but not fully
  6739. // initialized. Since we know we're in Chrome, we'll just detect this case
  6740. // explicitly
  6741. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  6742. return true;
  6743. }
  6744. // Internet Explorer and Edge do not support colors.
  6745. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  6746. return false;
  6747. }
  6748. // Is webkit? http://stackoverflow.com/a/16459606/376773
  6749. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  6750. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  6751. // Is firebug? http://stackoverflow.com/a/398120/376773
  6752. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  6753. // Is firefox >= v31?
  6754. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  6755. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  6756. // Double check webkit in userAgent just in case we are in a worker
  6757. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  6758. }
  6759. /**
  6760. * Colorize log arguments if enabled.
  6761. *
  6762. * @api public
  6763. */
  6764. function formatArgs(args) {
  6765. args[0] = (this.useColors ? '%c' : '') +
  6766. this.namespace +
  6767. (this.useColors ? ' %c' : ' ') +
  6768. args[0] +
  6769. (this.useColors ? '%c ' : ' ') +
  6770. '+' + module.exports.humanize(this.diff);
  6771. if (!this.useColors) {
  6772. return;
  6773. }
  6774. const c = 'color: ' + this.color;
  6775. args.splice(1, 0, c, 'color: inherit');
  6776. // The final "%c" is somewhat tricky, because there could be other
  6777. // arguments passed either before or after the %c, so we need to
  6778. // figure out the correct index to insert the CSS into
  6779. let index = 0;
  6780. let lastC = 0;
  6781. args[0].replace(/%[a-zA-Z%]/g, match => {
  6782. if (match === '%%') {
  6783. return;
  6784. }
  6785. index++;
  6786. if (match === '%c') {
  6787. // We only are interested in the *last* %c
  6788. // (the user may have provided their own)
  6789. lastC = index;
  6790. }
  6791. });
  6792. args.splice(lastC, 0, c);
  6793. }
  6794. /**
  6795. * Invokes `console.debug()` when available.
  6796. * No-op when `console.debug` is not a "function".
  6797. * If `console.debug` is not available, falls back
  6798. * to `console.log`.
  6799. *
  6800. * @api public
  6801. */
  6802. exports.log = console.debug || console.log || (() => {});
  6803. /**
  6804. * Save `namespaces`.
  6805. *
  6806. * @param {String} namespaces
  6807. * @api private
  6808. */
  6809. function save(namespaces) {
  6810. try {
  6811. if (namespaces) {
  6812. exports.storage.setItem('debug', namespaces);
  6813. } else {
  6814. exports.storage.removeItem('debug');
  6815. }
  6816. } catch (error) {
  6817. // Swallow
  6818. // XXX (@Qix-) should we be logging these?
  6819. }
  6820. }
  6821. /**
  6822. * Load `namespaces`.
  6823. *
  6824. * @return {String} returns the previously persisted debug modes
  6825. * @api private
  6826. */
  6827. function load() {
  6828. let r;
  6829. try {
  6830. r = exports.storage.getItem('debug');
  6831. } catch (error) {
  6832. // Swallow
  6833. // XXX (@Qix-) should we be logging these?
  6834. }
  6835. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  6836. if (!r && typeof process !== 'undefined' && 'env' in process) {
  6837. r = process.env.DEBUG;
  6838. }
  6839. return r;
  6840. }
  6841. /**
  6842. * Localstorage attempts to return the localstorage.
  6843. *
  6844. * This is necessary because safari throws
  6845. * when a user disables cookies/localstorage
  6846. * and you attempt to access it.
  6847. *
  6848. * @return {LocalStorage}
  6849. * @api private
  6850. */
  6851. function localstorage() {
  6852. try {
  6853. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  6854. // The Browser also has localStorage in the global context.
  6855. return localStorage;
  6856. } catch (error) {
  6857. // Swallow
  6858. // XXX (@Qix-) should we be logging these?
  6859. }
  6860. }
  6861. module.exports = require('./common')(exports);
  6862. const {formatters} = module.exports;
  6863. /**
  6864. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  6865. */
  6866. formatters.j = function (v) {
  6867. try {
  6868. return JSON.stringify(v);
  6869. } catch (error) {
  6870. return '[UnexpectedJSONParseError]: ' + error.message;
  6871. }
  6872. };
  6873. }).call(this)}).call(this,require('_process'))
  6874. },{"./common":32,"_process":35}],32:[function(require,module,exports){
  6875. /**
  6876. * This is the common logic for both the Node.js and web browser
  6877. * implementations of `debug()`.
  6878. */
  6879. function setup(env) {
  6880. createDebug.debug = createDebug;
  6881. createDebug.default = createDebug;
  6882. createDebug.coerce = coerce;
  6883. createDebug.disable = disable;
  6884. createDebug.enable = enable;
  6885. createDebug.enabled = enabled;
  6886. createDebug.humanize = require('ms');
  6887. createDebug.destroy = destroy;
  6888. Object.keys(env).forEach(key => {
  6889. createDebug[key] = env[key];
  6890. });
  6891. /**
  6892. * The currently active debug mode names, and names to skip.
  6893. */
  6894. createDebug.names = [];
  6895. createDebug.skips = [];
  6896. /**
  6897. * Map of special "%n" handling functions, for the debug "format" argument.
  6898. *
  6899. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  6900. */
  6901. createDebug.formatters = {};
  6902. /**
  6903. * Selects a color for a debug namespace
  6904. * @param {String} namespace The namespace string for the for the debug instance to be colored
  6905. * @return {Number|String} An ANSI color code for the given namespace
  6906. * @api private
  6907. */
  6908. function selectColor(namespace) {
  6909. let hash = 0;
  6910. for (let i = 0; i < namespace.length; i++) {
  6911. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  6912. hash |= 0; // Convert to 32bit integer
  6913. }
  6914. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  6915. }
  6916. createDebug.selectColor = selectColor;
  6917. /**
  6918. * Create a debugger with the given `namespace`.
  6919. *
  6920. * @param {String} namespace
  6921. * @return {Function}
  6922. * @api public
  6923. */
  6924. function createDebug(namespace) {
  6925. let prevTime;
  6926. let enableOverride = null;
  6927. function debug(...args) {
  6928. // Disabled?
  6929. if (!debug.enabled) {
  6930. return;
  6931. }
  6932. const self = debug;
  6933. // Set `diff` timestamp
  6934. const curr = Number(new Date());
  6935. const ms = curr - (prevTime || curr);
  6936. self.diff = ms;
  6937. self.prev = prevTime;
  6938. self.curr = curr;
  6939. prevTime = curr;
  6940. args[0] = createDebug.coerce(args[0]);
  6941. if (typeof args[0] !== 'string') {
  6942. // Anything else let's inspect with %O
  6943. args.unshift('%O');
  6944. }
  6945. // Apply any `formatters` transformations
  6946. let index = 0;
  6947. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  6948. // If we encounter an escaped % then don't increase the array index
  6949. if (match === '%%') {
  6950. return '%';
  6951. }
  6952. index++;
  6953. const formatter = createDebug.formatters[format];
  6954. if (typeof formatter === 'function') {
  6955. const val = args[index];
  6956. match = formatter.call(self, val);
  6957. // Now we need to remove `args[index]` since it's inlined in the `format`
  6958. args.splice(index, 1);
  6959. index--;
  6960. }
  6961. return match;
  6962. });
  6963. // Apply env-specific formatting (colors, etc.)
  6964. createDebug.formatArgs.call(self, args);
  6965. const logFn = self.log || createDebug.log;
  6966. logFn.apply(self, args);
  6967. }
  6968. debug.namespace = namespace;
  6969. debug.useColors = createDebug.useColors();
  6970. debug.color = createDebug.selectColor(namespace);
  6971. debug.extend = extend;
  6972. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  6973. Object.defineProperty(debug, 'enabled', {
  6974. enumerable: true,
  6975. configurable: false,
  6976. get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,
  6977. set: v => {
  6978. enableOverride = v;
  6979. }
  6980. });
  6981. // Env-specific initialization logic for debug instances
  6982. if (typeof createDebug.init === 'function') {
  6983. createDebug.init(debug);
  6984. }
  6985. return debug;
  6986. }
  6987. function extend(namespace, delimiter) {
  6988. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  6989. newDebug.log = this.log;
  6990. return newDebug;
  6991. }
  6992. /**
  6993. * Enables a debug mode by namespaces. This can include modes
  6994. * separated by a colon and wildcards.
  6995. *
  6996. * @param {String} namespaces
  6997. * @api public
  6998. */
  6999. function enable(namespaces) {
  7000. createDebug.save(namespaces);
  7001. createDebug.names = [];
  7002. createDebug.skips = [];
  7003. let i;
  7004. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  7005. const len = split.length;
  7006. for (i = 0; i < len; i++) {
  7007. if (!split[i]) {
  7008. // ignore empty strings
  7009. continue;
  7010. }
  7011. namespaces = split[i].replace(/\*/g, '.*?');
  7012. if (namespaces[0] === '-') {
  7013. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  7014. } else {
  7015. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  7016. }
  7017. }
  7018. }
  7019. /**
  7020. * Disable debug output.
  7021. *
  7022. * @return {String} namespaces
  7023. * @api public
  7024. */
  7025. function disable() {
  7026. const namespaces = [
  7027. ...createDebug.names.map(toNamespace),
  7028. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  7029. ].join(',');
  7030. createDebug.enable('');
  7031. return namespaces;
  7032. }
  7033. /**
  7034. * Returns true if the given mode name is enabled, false otherwise.
  7035. *
  7036. * @param {String} name
  7037. * @return {Boolean}
  7038. * @api public
  7039. */
  7040. function enabled(name) {
  7041. if (name[name.length - 1] === '*') {
  7042. return true;
  7043. }
  7044. let i;
  7045. let len;
  7046. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  7047. if (createDebug.skips[i].test(name)) {
  7048. return false;
  7049. }
  7050. }
  7051. for (i = 0, len = createDebug.names.length; i < len; i++) {
  7052. if (createDebug.names[i].test(name)) {
  7053. return true;
  7054. }
  7055. }
  7056. return false;
  7057. }
  7058. /**
  7059. * Convert regexp to namespace
  7060. *
  7061. * @param {RegExp} regxep
  7062. * @return {String} namespace
  7063. * @api private
  7064. */
  7065. function toNamespace(regexp) {
  7066. return regexp.toString()
  7067. .substring(2, regexp.toString().length - 2)
  7068. .replace(/\.\*\?$/, '*');
  7069. }
  7070. /**
  7071. * Coerce `val`.
  7072. *
  7073. * @param {Mixed} val
  7074. * @return {Mixed}
  7075. * @api private
  7076. */
  7077. function coerce(val) {
  7078. if (val instanceof Error) {
  7079. return val.stack || val.message;
  7080. }
  7081. return val;
  7082. }
  7083. /**
  7084. * XXX DO NOT USE. This is a temporary stub function.
  7085. * XXX It WILL be removed in the next major release.
  7086. */
  7087. function destroy() {
  7088. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  7089. }
  7090. createDebug.enable(createDebug.load());
  7091. return createDebug;
  7092. }
  7093. module.exports = setup;
  7094. },{"ms":34}],33:[function(require,module,exports){
  7095. (function (process,setImmediate){(function (){
  7096. /*!
  7097. * EventEmitter2
  7098. * https://github.com/hij1nx/EventEmitter2
  7099. *
  7100. * Copyright (c) 2013 hij1nx
  7101. * Licensed under the MIT license.
  7102. */
  7103. ;!function(undefined) {
  7104. var hasOwnProperty= Object.hasOwnProperty;
  7105. var isArray = Array.isArray ? Array.isArray : function _isArray(obj) {
  7106. return Object.prototype.toString.call(obj) === "[object Array]";
  7107. };
  7108. var defaultMaxListeners = 10;
  7109. var nextTickSupported= typeof process=='object' && typeof process.nextTick=='function';
  7110. var symbolsSupported= typeof Symbol==='function';
  7111. var reflectSupported= typeof Reflect === 'object';
  7112. var setImmediateSupported= typeof setImmediate === 'function';
  7113. var _setImmediate= setImmediateSupported ? setImmediate : setTimeout;
  7114. var ownKeys= symbolsSupported? (reflectSupported && typeof Reflect.ownKeys==='function'? Reflect.ownKeys : function(obj){
  7115. var arr= Object.getOwnPropertyNames(obj);
  7116. arr.push.apply(arr, Object.getOwnPropertySymbols(obj));
  7117. return arr;
  7118. }) : Object.keys;
  7119. function init() {
  7120. this._events = {};
  7121. if (this._conf) {
  7122. configure.call(this, this._conf);
  7123. }
  7124. }
  7125. function configure(conf) {
  7126. if (conf) {
  7127. this._conf = conf;
  7128. conf.delimiter && (this.delimiter = conf.delimiter);
  7129. if(conf.maxListeners!==undefined){
  7130. this._maxListeners= conf.maxListeners;
  7131. }
  7132. conf.wildcard && (this.wildcard = conf.wildcard);
  7133. conf.newListener && (this._newListener = conf.newListener);
  7134. conf.removeListener && (this._removeListener = conf.removeListener);
  7135. conf.verboseMemoryLeak && (this.verboseMemoryLeak = conf.verboseMemoryLeak);
  7136. conf.ignoreErrors && (this.ignoreErrors = conf.ignoreErrors);
  7137. if (this.wildcard) {
  7138. this.listenerTree = {};
  7139. }
  7140. }
  7141. }
  7142. function logPossibleMemoryLeak(count, eventName) {
  7143. var errorMsg = '(node) warning: possible EventEmitter memory ' +
  7144. 'leak detected. ' + count + ' listeners added. ' +
  7145. 'Use emitter.setMaxListeners() to increase limit.';
  7146. if(this.verboseMemoryLeak){
  7147. errorMsg += ' Event name: ' + eventName + '.';
  7148. }
  7149. if(typeof process !== 'undefined' && process.emitWarning){
  7150. var e = new Error(errorMsg);
  7151. e.name = 'MaxListenersExceededWarning';
  7152. e.emitter = this;
  7153. e.count = count;
  7154. process.emitWarning(e);
  7155. } else {
  7156. console.error(errorMsg);
  7157. if (console.trace){
  7158. console.trace();
  7159. }
  7160. }
  7161. }
  7162. var toArray = function (a, b, c) {
  7163. var n = arguments.length;
  7164. switch (n) {
  7165. case 0:
  7166. return [];
  7167. case 1:
  7168. return [a];
  7169. case 2:
  7170. return [a, b];
  7171. case 3:
  7172. return [a, b, c];
  7173. default:
  7174. var arr = new Array(n);
  7175. while (n--) {
  7176. arr[n] = arguments[n];
  7177. }
  7178. return arr;
  7179. }
  7180. };
  7181. function toObject(keys, values) {
  7182. var obj = {};
  7183. var key;
  7184. var len = keys.length;
  7185. var valuesCount = values ? value.length : 0;
  7186. for (var i = 0; i < len; i++) {
  7187. key = keys[i];
  7188. obj[key] = i < valuesCount ? values[i] : undefined;
  7189. }
  7190. return obj;
  7191. }
  7192. function TargetObserver(emitter, target, options) {
  7193. this._emitter = emitter;
  7194. this._target = target;
  7195. this._listeners = {};
  7196. this._listenersCount = 0;
  7197. var on, off;
  7198. if (options.on || options.off) {
  7199. on = options.on;
  7200. off = options.off;
  7201. }
  7202. if (target.addEventListener) {
  7203. on = target.addEventListener;
  7204. off = target.removeEventListener;
  7205. } else if (target.addListener) {
  7206. on = target.addListener;
  7207. off = target.removeListener;
  7208. } else if (target.on) {
  7209. on = target.on;
  7210. off = target.off;
  7211. }
  7212. if (!on && !off) {
  7213. throw Error('target does not implement any known event API');
  7214. }
  7215. if (typeof on !== 'function') {
  7216. throw TypeError('on method must be a function');
  7217. }
  7218. if (typeof off !== 'function') {
  7219. throw TypeError('off method must be a function');
  7220. }
  7221. this._on = on;
  7222. this._off = off;
  7223. var _observers= emitter._observers;
  7224. if(_observers){
  7225. _observers.push(this);
  7226. }else{
  7227. emitter._observers= [this];
  7228. }
  7229. }
  7230. Object.assign(TargetObserver.prototype, {
  7231. subscribe: function(event, localEvent, reducer){
  7232. var observer= this;
  7233. var target= this._target;
  7234. var emitter= this._emitter;
  7235. var listeners= this._listeners;
  7236. var handler= function(){
  7237. var args= toArray.apply(null, arguments);
  7238. var eventObj= {
  7239. data: args,
  7240. name: localEvent,
  7241. original: event
  7242. };
  7243. if(reducer){
  7244. var result= reducer.call(target, eventObj);
  7245. if(result!==false){
  7246. emitter.emit.apply(emitter, [eventObj.name].concat(args))
  7247. }
  7248. return;
  7249. }
  7250. emitter.emit.apply(emitter, [localEvent].concat(args));
  7251. };
  7252. if(listeners[event]){
  7253. throw Error('Event \'' + event + '\' is already listening');
  7254. }
  7255. this._listenersCount++;
  7256. if(emitter._newListener && emitter._removeListener && !observer._onNewListener){
  7257. this._onNewListener = function (_event) {
  7258. if (_event === localEvent && listeners[event] === null) {
  7259. listeners[event] = handler;
  7260. observer._on.call(target, event, handler);
  7261. }
  7262. };
  7263. emitter.on('newListener', this._onNewListener);
  7264. this._onRemoveListener= function(_event){
  7265. if(_event === localEvent && !emitter.hasListeners(_event) && listeners[event]){
  7266. listeners[event]= null;
  7267. observer._off.call(target, event, handler);
  7268. }
  7269. };
  7270. listeners[event]= null;
  7271. emitter.on('removeListener', this._onRemoveListener);
  7272. }else{
  7273. listeners[event]= handler;
  7274. observer._on.call(target, event, handler);
  7275. }
  7276. },
  7277. unsubscribe: function(event){
  7278. var observer= this;
  7279. var listeners= this._listeners;
  7280. var emitter= this._emitter;
  7281. var handler;
  7282. var events;
  7283. var off= this._off;
  7284. var target= this._target;
  7285. var i;
  7286. if(event && typeof event!=='string'){
  7287. throw TypeError('event must be a string');
  7288. }
  7289. function clearRefs(){
  7290. if(observer._onNewListener){
  7291. emitter.off('newListener', observer._onNewListener);
  7292. emitter.off('removeListener', observer._onRemoveListener);
  7293. observer._onNewListener= null;
  7294. observer._onRemoveListener= null;
  7295. }
  7296. var index= findTargetIndex.call(emitter, observer);
  7297. emitter._observers.splice(index, 1);
  7298. }
  7299. if(event){
  7300. handler= listeners[event];
  7301. if(!handler) return;
  7302. off.call(target, event, handler);
  7303. delete listeners[event];
  7304. if(!--this._listenersCount){
  7305. clearRefs();
  7306. }
  7307. }else{
  7308. events= ownKeys(listeners);
  7309. i= events.length;
  7310. while(i-->0){
  7311. event= events[i];
  7312. off.call(target, event, listeners[event]);
  7313. }
  7314. this._listeners= {};
  7315. this._listenersCount= 0;
  7316. clearRefs();
  7317. }
  7318. }
  7319. });
  7320. function resolveOptions(options, schema, reducers, allowUnknown) {
  7321. var computedOptions = Object.assign({}, schema);
  7322. if (!options) return computedOptions;
  7323. if (typeof options !== 'object') {
  7324. throw TypeError('options must be an object')
  7325. }
  7326. var keys = Object.keys(options);
  7327. var length = keys.length;
  7328. var option, value;
  7329. var reducer;
  7330. function reject(reason) {
  7331. throw Error('Invalid "' + option + '" option value' + (reason ? '. Reason: ' + reason : ''))
  7332. }
  7333. for (var i = 0; i < length; i++) {
  7334. option = keys[i];
  7335. if (!allowUnknown && !hasOwnProperty.call(schema, option)) {
  7336. throw Error('Unknown "' + option + '" option');
  7337. }
  7338. value = options[option];
  7339. if (value !== undefined) {
  7340. reducer = reducers[option];
  7341. computedOptions[option] = reducer ? reducer(value, reject) : value;
  7342. }
  7343. }
  7344. return computedOptions;
  7345. }
  7346. function constructorReducer(value, reject) {
  7347. if (typeof value !== 'function' || !value.hasOwnProperty('prototype')) {
  7348. reject('value must be a constructor');
  7349. }
  7350. return value;
  7351. }
  7352. function makeTypeReducer(types) {
  7353. var message= 'value must be type of ' + types.join('|');
  7354. var len= types.length;
  7355. var firstType= types[0];
  7356. var secondType= types[1];
  7357. if (len === 1) {
  7358. return function (v, reject) {
  7359. if (typeof v === firstType) {
  7360. return v;
  7361. }
  7362. reject(message);
  7363. }
  7364. }
  7365. if (len === 2) {
  7366. return function (v, reject) {
  7367. var kind= typeof v;
  7368. if (kind === firstType || kind === secondType) return v;
  7369. reject(message);
  7370. }
  7371. }
  7372. return function (v, reject) {
  7373. var kind = typeof v;
  7374. var i = len;
  7375. while (i-- > 0) {
  7376. if (kind === types[i]) return v;
  7377. }
  7378. reject(message);
  7379. }
  7380. }
  7381. var functionReducer= makeTypeReducer(['function']);
  7382. var objectFunctionReducer= makeTypeReducer(['object', 'function']);
  7383. function makeCancelablePromise(Promise, executor, options) {
  7384. var isCancelable;
  7385. var callbacks;
  7386. var timer= 0;
  7387. var subscriptionClosed;
  7388. var promise = new Promise(function (resolve, reject, onCancel) {
  7389. options= resolveOptions(options, {
  7390. timeout: 0,
  7391. overload: false
  7392. }, {
  7393. timeout: function(value, reject){
  7394. value*= 1;
  7395. if (typeof value !== 'number' || value < 0 || !Number.isFinite(value)) {
  7396. reject('timeout must be a positive number');
  7397. }
  7398. return value;
  7399. }
  7400. });
  7401. isCancelable = !options.overload && typeof Promise.prototype.cancel === 'function' && typeof onCancel === 'function';
  7402. function cleanup() {
  7403. if (callbacks) {
  7404. callbacks = null;
  7405. }
  7406. if (timer) {
  7407. clearTimeout(timer);
  7408. timer = 0;
  7409. }
  7410. }
  7411. var _resolve= function(value){
  7412. cleanup();
  7413. resolve(value);
  7414. };
  7415. var _reject= function(err){
  7416. cleanup();
  7417. reject(err);
  7418. };
  7419. if (isCancelable) {
  7420. executor(_resolve, _reject, onCancel);
  7421. } else {
  7422. callbacks = [function(reason){
  7423. _reject(reason || Error('canceled'));
  7424. }];
  7425. executor(_resolve, _reject, function (cb) {
  7426. if (subscriptionClosed) {
  7427. throw Error('Unable to subscribe on cancel event asynchronously')
  7428. }
  7429. if (typeof cb !== 'function') {
  7430. throw TypeError('onCancel callback must be a function');
  7431. }
  7432. callbacks.push(cb);
  7433. });
  7434. subscriptionClosed= true;
  7435. }
  7436. if (options.timeout > 0) {
  7437. timer= setTimeout(function(){
  7438. var reason= Error('timeout');
  7439. timer= 0;
  7440. promise.cancel(reason);
  7441. reject(reason);
  7442. }, options.timeout);
  7443. }
  7444. });
  7445. if (!isCancelable) {
  7446. promise.cancel = function (reason) {
  7447. if (!callbacks) {
  7448. return;
  7449. }
  7450. var length = callbacks.length;
  7451. for (var i = 1; i < length; i++) {
  7452. callbacks[i](reason);
  7453. }
  7454. // internal callback to reject the promise
  7455. callbacks[0](reason);
  7456. callbacks = null;
  7457. };
  7458. }
  7459. return promise;
  7460. }
  7461. function findTargetIndex(observer) {
  7462. var observers = this._observers;
  7463. if(!observers){
  7464. return -1;
  7465. }
  7466. var len = observers.length;
  7467. for (var i = 0; i < len; i++) {
  7468. if (observers[i]._target === observer) return i;
  7469. }
  7470. return -1;
  7471. }
  7472. // Attention, function return type now is array, always !
  7473. // It has zero elements if no any matches found and one or more
  7474. // elements (leafs) if there are matches
  7475. //
  7476. function searchListenerTree(handlers, type, tree, i, typeLength) {
  7477. if (!tree) {
  7478. return null;
  7479. }
  7480. if (i === 0) {
  7481. var kind = typeof type;
  7482. if (kind === 'string') {
  7483. var ns, n, l = 0, j = 0, delimiter = this.delimiter, dl = delimiter.length;
  7484. if ((n = type.indexOf(delimiter)) !== -1) {
  7485. ns = new Array(5);
  7486. do {
  7487. ns[l++] = type.slice(j, n);
  7488. j = n + dl;
  7489. } while ((n = type.indexOf(delimiter, j)) !== -1);
  7490. ns[l++] = type.slice(j);
  7491. type = ns;
  7492. typeLength = l;
  7493. } else {
  7494. type = [type];
  7495. typeLength = 1;
  7496. }
  7497. } else if (kind === 'object') {
  7498. typeLength = type.length;
  7499. } else {
  7500. type = [type];
  7501. typeLength = 1;
  7502. }
  7503. }
  7504. var listeners= null, branch, xTree, xxTree, isolatedBranch, endReached, currentType = type[i],
  7505. nextType = type[i + 1], branches, _listeners;
  7506. if (i === typeLength && tree._listeners) {
  7507. //
  7508. // If at the end of the event(s) list and the tree has listeners
  7509. // invoke those listeners.
  7510. //
  7511. if (typeof tree._listeners === 'function') {
  7512. handlers && handlers.push(tree._listeners);
  7513. return [tree];
  7514. } else {
  7515. handlers && handlers.push.apply(handlers, tree._listeners);
  7516. return [tree];
  7517. }
  7518. }
  7519. if (currentType === '*') {
  7520. //
  7521. // If the event emitted is '*' at this part
  7522. // or there is a concrete match at this patch
  7523. //
  7524. branches= ownKeys(tree);
  7525. n= branches.length;
  7526. while(n-->0){
  7527. branch= branches[n];
  7528. if (branch !== '_listeners') {
  7529. _listeners = searchListenerTree(handlers, type, tree[branch], i + 1, typeLength);
  7530. if(_listeners){
  7531. if(listeners){
  7532. listeners.push.apply(listeners, _listeners);
  7533. }else{
  7534. listeners = _listeners;
  7535. }
  7536. }
  7537. }
  7538. }
  7539. return listeners;
  7540. } else if (currentType === '**') {
  7541. endReached = (i + 1 === typeLength || (i + 2 === typeLength && nextType === '*'));
  7542. if (endReached && tree._listeners) {
  7543. // The next element has a _listeners, add it to the handlers.
  7544. listeners = searchListenerTree(handlers, type, tree, typeLength, typeLength);
  7545. }
  7546. branches= ownKeys(tree);
  7547. n= branches.length;
  7548. while(n-->0){
  7549. branch= branches[n];
  7550. if (branch !== '_listeners') {
  7551. if (branch === '*' || branch === '**') {
  7552. if (tree[branch]._listeners && !endReached) {
  7553. _listeners = searchListenerTree(handlers, type, tree[branch], typeLength, typeLength);
  7554. if(_listeners){
  7555. if(listeners){
  7556. listeners.push.apply(listeners, _listeners);
  7557. }else{
  7558. listeners = _listeners;
  7559. }
  7560. }
  7561. }
  7562. _listeners = searchListenerTree(handlers, type, tree[branch], i, typeLength);
  7563. } else if (branch === nextType) {
  7564. _listeners = searchListenerTree(handlers, type, tree[branch], i + 2, typeLength);
  7565. } else {
  7566. // No match on this one, shift into the tree but not in the type array.
  7567. _listeners = searchListenerTree(handlers, type, tree[branch], i, typeLength);
  7568. }
  7569. if(_listeners){
  7570. if(listeners){
  7571. listeners.push.apply(listeners, _listeners);
  7572. }else{
  7573. listeners = _listeners;
  7574. }
  7575. }
  7576. }
  7577. }
  7578. return listeners;
  7579. }else if (tree[currentType]) {
  7580. listeners= searchListenerTree(handlers, type, tree[currentType], i + 1, typeLength);
  7581. }
  7582. xTree = tree['*'];
  7583. if (xTree) {
  7584. //
  7585. // If the listener tree will allow any match for this part,
  7586. // then recursively explore all branches of the tree
  7587. //
  7588. searchListenerTree(handlers, type, xTree, i + 1, typeLength);
  7589. }
  7590. xxTree = tree['**'];
  7591. if (xxTree) {
  7592. if (i < typeLength) {
  7593. if (xxTree._listeners) {
  7594. // If we have a listener on a '**', it will catch all, so add its handler.
  7595. searchListenerTree(handlers, type, xxTree, typeLength, typeLength);
  7596. }
  7597. // Build arrays of matching next branches and others.
  7598. branches= ownKeys(xxTree);
  7599. n= branches.length;
  7600. while(n-->0){
  7601. branch= branches[n];
  7602. if (branch !== '_listeners') {
  7603. if (branch === nextType) {
  7604. // We know the next element will match, so jump twice.
  7605. searchListenerTree(handlers, type, xxTree[branch], i + 2, typeLength);
  7606. } else if (branch === currentType) {
  7607. // Current node matches, move into the tree.
  7608. searchListenerTree(handlers, type, xxTree[branch], i + 1, typeLength);
  7609. } else {
  7610. isolatedBranch = {};
  7611. isolatedBranch[branch] = xxTree[branch];
  7612. searchListenerTree(handlers, type, {'**': isolatedBranch}, i + 1, typeLength);
  7613. }
  7614. }
  7615. }
  7616. } else if (xxTree._listeners) {
  7617. // We have reached the end and still on a '**'
  7618. searchListenerTree(handlers, type, xxTree, typeLength, typeLength);
  7619. } else if (xxTree['*'] && xxTree['*']._listeners) {
  7620. searchListenerTree(handlers, type, xxTree['*'], typeLength, typeLength);
  7621. }
  7622. }
  7623. return listeners;
  7624. }
  7625. function growListenerTree(type, listener) {
  7626. var len = 0, j = 0, i, delimiter = this.delimiter, dl= delimiter.length, ns;
  7627. if(typeof type==='string') {
  7628. if ((i = type.indexOf(delimiter)) !== -1) {
  7629. ns = new Array(5);
  7630. do {
  7631. ns[len++] = type.slice(j, i);
  7632. j = i + dl;
  7633. } while ((i = type.indexOf(delimiter, j)) !== -1);
  7634. ns[len++] = type.slice(j);
  7635. }else{
  7636. ns= [type];
  7637. len= 1;
  7638. }
  7639. }else{
  7640. ns= type;
  7641. len= type.length;
  7642. }
  7643. //
  7644. // Looks for two consecutive '**', if so, don't add the event at all.
  7645. //
  7646. if (len > 1) {
  7647. for (i = 0; i + 1 < len; i++) {
  7648. if (ns[i] === '**' && ns[i + 1] === '**') {
  7649. return;
  7650. }
  7651. }
  7652. }
  7653. var tree = this.listenerTree, name;
  7654. for (i = 0; i < len; i++) {
  7655. name = ns[i];
  7656. tree = tree[name] || (tree[name] = {});
  7657. if (i === len - 1) {
  7658. if (!tree._listeners) {
  7659. tree._listeners = listener;
  7660. } else {
  7661. if (typeof tree._listeners === 'function') {
  7662. tree._listeners = [tree._listeners];
  7663. }
  7664. tree._listeners.push(listener);
  7665. if (
  7666. !tree._listeners.warned &&
  7667. this._maxListeners > 0 &&
  7668. tree._listeners.length > this._maxListeners
  7669. ) {
  7670. tree._listeners.warned = true;
  7671. logPossibleMemoryLeak.call(this, tree._listeners.length, name);
  7672. }
  7673. }
  7674. return true;
  7675. }
  7676. }
  7677. return true;
  7678. }
  7679. function collectTreeEvents(tree, events, root, asArray){
  7680. var branches= ownKeys(tree);
  7681. var i= branches.length;
  7682. var branch, branchName, path;
  7683. var hasListeners= tree['_listeners'];
  7684. var isArrayPath;
  7685. while(i-->0){
  7686. branchName= branches[i];
  7687. branch= tree[branchName];
  7688. if(branchName==='_listeners'){
  7689. path= root;
  7690. }else {
  7691. path = root ? root.concat(branchName) : [branchName];
  7692. }
  7693. isArrayPath= asArray || typeof branchName==='symbol';
  7694. hasListeners && events.push(isArrayPath? path : path.join(this.delimiter));
  7695. if(typeof branch==='object'){
  7696. collectTreeEvents.call(this, branch, events, path, isArrayPath);
  7697. }
  7698. }
  7699. return events;
  7700. }
  7701. function recursivelyGarbageCollect(root) {
  7702. var keys = ownKeys(root);
  7703. var i= keys.length;
  7704. var obj, key, flag;
  7705. while(i-->0){
  7706. key = keys[i];
  7707. obj = root[key];
  7708. if(obj){
  7709. flag= true;
  7710. if(key !== '_listeners' && !recursivelyGarbageCollect(obj)){
  7711. delete root[key];
  7712. }
  7713. }
  7714. }
  7715. return flag;
  7716. }
  7717. function Listener(emitter, event, listener){
  7718. this.emitter= emitter;
  7719. this.event= event;
  7720. this.listener= listener;
  7721. }
  7722. Listener.prototype.off= function(){
  7723. this.emitter.off(this.event, this.listener);
  7724. return this;
  7725. };
  7726. function setupListener(event, listener, options){
  7727. if (options === true) {
  7728. promisify = true;
  7729. } else if (options === false) {
  7730. async = true;
  7731. } else {
  7732. if (!options || typeof options !== 'object') {
  7733. throw TypeError('options should be an object or true');
  7734. }
  7735. var async = options.async;
  7736. var promisify = options.promisify;
  7737. var nextTick = options.nextTick;
  7738. var objectify = options.objectify;
  7739. }
  7740. if (async || nextTick || promisify) {
  7741. var _listener = listener;
  7742. var _origin = listener._origin || listener;
  7743. if (nextTick && !nextTickSupported) {
  7744. throw Error('process.nextTick is not supported');
  7745. }
  7746. if (promisify === undefined) {
  7747. promisify = listener.constructor.name === 'AsyncFunction';
  7748. }
  7749. listener = function () {
  7750. var args = arguments;
  7751. var context = this;
  7752. var event = this.event;
  7753. return promisify ? (nextTick ? Promise.resolve() : new Promise(function (resolve) {
  7754. _setImmediate(resolve);
  7755. }).then(function () {
  7756. context.event = event;
  7757. return _listener.apply(context, args)
  7758. })) : (nextTick ? process.nextTick : _setImmediate)(function () {
  7759. context.event = event;
  7760. _listener.apply(context, args)
  7761. });
  7762. };
  7763. listener._async = true;
  7764. listener._origin = _origin;
  7765. }
  7766. return [listener, objectify? new Listener(this, event, listener): this];
  7767. }
  7768. function EventEmitter(conf) {
  7769. this._events = {};
  7770. this._newListener = false;
  7771. this._removeListener = false;
  7772. this.verboseMemoryLeak = false;
  7773. configure.call(this, conf);
  7774. }
  7775. EventEmitter.EventEmitter2 = EventEmitter; // backwards compatibility for exporting EventEmitter property
  7776. EventEmitter.prototype.listenTo= function(target, events, options){
  7777. if(typeof target!=='object'){
  7778. throw TypeError('target musts be an object');
  7779. }
  7780. var emitter= this;
  7781. options = resolveOptions(options, {
  7782. on: undefined,
  7783. off: undefined,
  7784. reducers: undefined
  7785. }, {
  7786. on: functionReducer,
  7787. off: functionReducer,
  7788. reducers: objectFunctionReducer
  7789. });
  7790. function listen(events){
  7791. if(typeof events!=='object'){
  7792. throw TypeError('events must be an object');
  7793. }
  7794. var reducers= options.reducers;
  7795. var index= findTargetIndex.call(emitter, target);
  7796. var observer;
  7797. if(index===-1){
  7798. observer= new TargetObserver(emitter, target, options);
  7799. }else{
  7800. observer= emitter._observers[index];
  7801. }
  7802. var keys= ownKeys(events);
  7803. var len= keys.length;
  7804. var event;
  7805. var isSingleReducer= typeof reducers==='function';
  7806. for(var i=0; i<len; i++){
  7807. event= keys[i];
  7808. observer.subscribe(
  7809. event,
  7810. events[event] || event,
  7811. isSingleReducer ? reducers : reducers && reducers[event]
  7812. );
  7813. }
  7814. }
  7815. isArray(events)?
  7816. listen(toObject(events)) :
  7817. (typeof events==='string'? listen(toObject(events.split(/\s+/))): listen(events));
  7818. return this;
  7819. };
  7820. EventEmitter.prototype.stopListeningTo = function (target, event) {
  7821. var observers = this._observers;
  7822. if(!observers){
  7823. return false;
  7824. }
  7825. var i = observers.length;
  7826. var observer;
  7827. var matched= false;
  7828. if(target && typeof target!=='object'){
  7829. throw TypeError('target should be an object');
  7830. }
  7831. while (i-- > 0) {
  7832. observer = observers[i];
  7833. if (!target || observer._target === target) {
  7834. observer.unsubscribe(event);
  7835. matched= true;
  7836. }
  7837. }
  7838. return matched;
  7839. };
  7840. // By default EventEmitters will print a warning if more than
  7841. // 10 listeners are added to it. This is a useful default which
  7842. // helps finding memory leaks.
  7843. //
  7844. // Obviously not all Emitters should be limited to 10. This function allows
  7845. // that to be increased. Set to zero for unlimited.
  7846. EventEmitter.prototype.delimiter = '.';
  7847. EventEmitter.prototype.setMaxListeners = function(n) {
  7848. if (n !== undefined) {
  7849. this._maxListeners = n;
  7850. if (!this._conf) this._conf = {};
  7851. this._conf.maxListeners = n;
  7852. }
  7853. };
  7854. EventEmitter.prototype.getMaxListeners = function() {
  7855. return this._maxListeners;
  7856. };
  7857. EventEmitter.prototype.event = '';
  7858. EventEmitter.prototype.once = function(event, fn, options) {
  7859. return this._once(event, fn, false, options);
  7860. };
  7861. EventEmitter.prototype.prependOnceListener = function(event, fn, options) {
  7862. return this._once(event, fn, true, options);
  7863. };
  7864. EventEmitter.prototype._once = function(event, fn, prepend, options) {
  7865. return this._many(event, 1, fn, prepend, options);
  7866. };
  7867. EventEmitter.prototype.many = function(event, ttl, fn, options) {
  7868. return this._many(event, ttl, fn, false, options);
  7869. };
  7870. EventEmitter.prototype.prependMany = function(event, ttl, fn, options) {
  7871. return this._many(event, ttl, fn, true, options);
  7872. };
  7873. EventEmitter.prototype._many = function(event, ttl, fn, prepend, options) {
  7874. var self = this;
  7875. if (typeof fn !== 'function') {
  7876. throw new Error('many only accepts instances of Function');
  7877. }
  7878. function listener() {
  7879. if (--ttl === 0) {
  7880. self.off(event, listener);
  7881. }
  7882. return fn.apply(this, arguments);
  7883. }
  7884. listener._origin = fn;
  7885. return this._on(event, listener, prepend, options);
  7886. };
  7887. EventEmitter.prototype.emit = function() {
  7888. if (!this._events && !this._all) {
  7889. return false;
  7890. }
  7891. this._events || init.call(this);
  7892. var type = arguments[0], ns, wildcard= this.wildcard;
  7893. var args,l,i,j, containsSymbol;
  7894. if (type === 'newListener' && !this._newListener) {
  7895. if (!this._events.newListener) {
  7896. return false;
  7897. }
  7898. }
  7899. if (wildcard) {
  7900. ns= type;
  7901. if(type!=='newListener' && type!=='removeListener'){
  7902. if (typeof type === 'object') {
  7903. l = type.length;
  7904. if (symbolsSupported) {
  7905. for (i = 0; i < l; i++) {
  7906. if (typeof type[i] === 'symbol') {
  7907. containsSymbol = true;
  7908. break;
  7909. }
  7910. }
  7911. }
  7912. if (!containsSymbol) {
  7913. type = type.join(this.delimiter);
  7914. }
  7915. }
  7916. }
  7917. }
  7918. var al = arguments.length;
  7919. var handler;
  7920. if (this._all && this._all.length) {
  7921. handler = this._all.slice();
  7922. for (i = 0, l = handler.length; i < l; i++) {
  7923. this.event = type;
  7924. switch (al) {
  7925. case 1:
  7926. handler[i].call(this, type);
  7927. break;
  7928. case 2:
  7929. handler[i].call(this, type, arguments[1]);
  7930. break;
  7931. case 3:
  7932. handler[i].call(this, type, arguments[1], arguments[2]);
  7933. break;
  7934. default:
  7935. handler[i].apply(this, arguments);
  7936. }
  7937. }
  7938. }
  7939. if (wildcard) {
  7940. handler = [];
  7941. searchListenerTree.call(this, handler, ns, this.listenerTree, 0, l);
  7942. } else {
  7943. handler = this._events[type];
  7944. if (typeof handler === 'function') {
  7945. this.event = type;
  7946. switch (al) {
  7947. case 1:
  7948. handler.call(this);
  7949. break;
  7950. case 2:
  7951. handler.call(this, arguments[1]);
  7952. break;
  7953. case 3:
  7954. handler.call(this, arguments[1], arguments[2]);
  7955. break;
  7956. default:
  7957. args = new Array(al - 1);
  7958. for (j = 1; j < al; j++) args[j - 1] = arguments[j];
  7959. handler.apply(this, args);
  7960. }
  7961. return true;
  7962. } else if (handler) {
  7963. // need to make copy of handlers because list can change in the middle
  7964. // of emit call
  7965. handler = handler.slice();
  7966. }
  7967. }
  7968. if (handler && handler.length) {
  7969. if (al > 3) {
  7970. args = new Array(al - 1);
  7971. for (j = 1; j < al; j++) args[j - 1] = arguments[j];
  7972. }
  7973. for (i = 0, l = handler.length; i < l; i++) {
  7974. this.event = type;
  7975. switch (al) {
  7976. case 1:
  7977. handler[i].call(this);
  7978. break;
  7979. case 2:
  7980. handler[i].call(this, arguments[1]);
  7981. break;
  7982. case 3:
  7983. handler[i].call(this, arguments[1], arguments[2]);
  7984. break;
  7985. default:
  7986. handler[i].apply(this, args);
  7987. }
  7988. }
  7989. return true;
  7990. } else if (!this.ignoreErrors && !this._all && type === 'error') {
  7991. if (arguments[1] instanceof Error) {
  7992. throw arguments[1]; // Unhandled 'error' event
  7993. } else {
  7994. throw new Error("Uncaught, unspecified 'error' event.");
  7995. }
  7996. }
  7997. return !!this._all;
  7998. };
  7999. EventEmitter.prototype.emitAsync = function() {
  8000. if (!this._events && !this._all) {
  8001. return false;
  8002. }
  8003. this._events || init.call(this);
  8004. var type = arguments[0], wildcard= this.wildcard, ns, containsSymbol;
  8005. var args,l,i,j;
  8006. if (type === 'newListener' && !this._newListener) {
  8007. if (!this._events.newListener) { return Promise.resolve([false]); }
  8008. }
  8009. if (wildcard) {
  8010. ns= type;
  8011. if(type!=='newListener' && type!=='removeListener'){
  8012. if (typeof type === 'object') {
  8013. l = type.length;
  8014. if (symbolsSupported) {
  8015. for (i = 0; i < l; i++) {
  8016. if (typeof type[i] === 'symbol') {
  8017. containsSymbol = true;
  8018. break;
  8019. }
  8020. }
  8021. }
  8022. if (!containsSymbol) {
  8023. type = type.join(this.delimiter);
  8024. }
  8025. }
  8026. }
  8027. }
  8028. var promises= [];
  8029. var al = arguments.length;
  8030. var handler;
  8031. if (this._all) {
  8032. for (i = 0, l = this._all.length; i < l; i++) {
  8033. this.event = type;
  8034. switch (al) {
  8035. case 1:
  8036. promises.push(this._all[i].call(this, type));
  8037. break;
  8038. case 2:
  8039. promises.push(this._all[i].call(this, type, arguments[1]));
  8040. break;
  8041. case 3:
  8042. promises.push(this._all[i].call(this, type, arguments[1], arguments[2]));
  8043. break;
  8044. default:
  8045. promises.push(this._all[i].apply(this, arguments));
  8046. }
  8047. }
  8048. }
  8049. if (wildcard) {
  8050. handler = [];
  8051. searchListenerTree.call(this, handler, ns, this.listenerTree, 0);
  8052. } else {
  8053. handler = this._events[type];
  8054. }
  8055. if (typeof handler === 'function') {
  8056. this.event = type;
  8057. switch (al) {
  8058. case 1:
  8059. promises.push(handler.call(this));
  8060. break;
  8061. case 2:
  8062. promises.push(handler.call(this, arguments[1]));
  8063. break;
  8064. case 3:
  8065. promises.push(handler.call(this, arguments[1], arguments[2]));
  8066. break;
  8067. default:
  8068. args = new Array(al - 1);
  8069. for (j = 1; j < al; j++) args[j - 1] = arguments[j];
  8070. promises.push(handler.apply(this, args));
  8071. }
  8072. } else if (handler && handler.length) {
  8073. handler = handler.slice();
  8074. if (al > 3) {
  8075. args = new Array(al - 1);
  8076. for (j = 1; j < al; j++) args[j - 1] = arguments[j];
  8077. }
  8078. for (i = 0, l = handler.length; i < l; i++) {
  8079. this.event = type;
  8080. switch (al) {
  8081. case 1:
  8082. promises.push(handler[i].call(this));
  8083. break;
  8084. case 2:
  8085. promises.push(handler[i].call(this, arguments[1]));
  8086. break;
  8087. case 3:
  8088. promises.push(handler[i].call(this, arguments[1], arguments[2]));
  8089. break;
  8090. default:
  8091. promises.push(handler[i].apply(this, args));
  8092. }
  8093. }
  8094. } else if (!this.ignoreErrors && !this._all && type === 'error') {
  8095. if (arguments[1] instanceof Error) {
  8096. return Promise.reject(arguments[1]); // Unhandled 'error' event
  8097. } else {
  8098. return Promise.reject("Uncaught, unspecified 'error' event.");
  8099. }
  8100. }
  8101. return Promise.all(promises);
  8102. };
  8103. EventEmitter.prototype.on = function(type, listener, options) {
  8104. return this._on(type, listener, false, options);
  8105. };
  8106. EventEmitter.prototype.prependListener = function(type, listener, options) {
  8107. return this._on(type, listener, true, options);
  8108. };
  8109. EventEmitter.prototype.onAny = function(fn) {
  8110. return this._onAny(fn, false);
  8111. };
  8112. EventEmitter.prototype.prependAny = function(fn) {
  8113. return this._onAny(fn, true);
  8114. };
  8115. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  8116. EventEmitter.prototype._onAny = function(fn, prepend){
  8117. if (typeof fn !== 'function') {
  8118. throw new Error('onAny only accepts instances of Function');
  8119. }
  8120. if (!this._all) {
  8121. this._all = [];
  8122. }
  8123. // Add the function to the event listener collection.
  8124. if(prepend){
  8125. this._all.unshift(fn);
  8126. }else{
  8127. this._all.push(fn);
  8128. }
  8129. return this;
  8130. };
  8131. EventEmitter.prototype._on = function(type, listener, prepend, options) {
  8132. if (typeof type === 'function') {
  8133. this._onAny(type, listener);
  8134. return this;
  8135. }
  8136. if (typeof listener !== 'function') {
  8137. throw new Error('on only accepts instances of Function');
  8138. }
  8139. this._events || init.call(this);
  8140. var returnValue= this, temp;
  8141. if (options !== undefined) {
  8142. temp = setupListener.call(this, type, listener, options);
  8143. listener = temp[0];
  8144. returnValue = temp[1];
  8145. }
  8146. // To avoid recursion in the case that type == "newListeners"! Before
  8147. // adding it to the listeners, first emit "newListeners".
  8148. if (this._newListener) {
  8149. this.emit('newListener', type, listener);
  8150. }
  8151. if (this.wildcard) {
  8152. growListenerTree.call(this, type, listener);
  8153. return returnValue;
  8154. }
  8155. if (!this._events[type]) {
  8156. // Optimize the case of one listener. Don't need the extra array object.
  8157. this._events[type] = listener;
  8158. } else {
  8159. if (typeof this._events[type] === 'function') {
  8160. // Change to array.
  8161. this._events[type] = [this._events[type]];
  8162. }
  8163. // If we've already got an array, just add
  8164. if(prepend){
  8165. this._events[type].unshift(listener);
  8166. }else{
  8167. this._events[type].push(listener);
  8168. }
  8169. // Check for listener leak
  8170. if (
  8171. !this._events[type].warned &&
  8172. this._maxListeners > 0 &&
  8173. this._events[type].length > this._maxListeners
  8174. ) {
  8175. this._events[type].warned = true;
  8176. logPossibleMemoryLeak.call(this, this._events[type].length, type);
  8177. }
  8178. }
  8179. return returnValue;
  8180. };
  8181. EventEmitter.prototype.off = function(type, listener) {
  8182. if (typeof listener !== 'function') {
  8183. throw new Error('removeListener only takes instances of Function');
  8184. }
  8185. var handlers,leafs=[];
  8186. if(this.wildcard) {
  8187. var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
  8188. leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
  8189. if(!leafs) return this;
  8190. } else {
  8191. // does not use listeners(), so no side effect of creating _events[type]
  8192. if (!this._events[type]) return this;
  8193. handlers = this._events[type];
  8194. leafs.push({_listeners:handlers});
  8195. }
  8196. for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
  8197. var leaf = leafs[iLeaf];
  8198. handlers = leaf._listeners;
  8199. if (isArray(handlers)) {
  8200. var position = -1;
  8201. for (var i = 0, length = handlers.length; i < length; i++) {
  8202. if (handlers[i] === listener ||
  8203. (handlers[i].listener && handlers[i].listener === listener) ||
  8204. (handlers[i]._origin && handlers[i]._origin === listener)) {
  8205. position = i;
  8206. break;
  8207. }
  8208. }
  8209. if (position < 0) {
  8210. continue;
  8211. }
  8212. if(this.wildcard) {
  8213. leaf._listeners.splice(position, 1);
  8214. }
  8215. else {
  8216. this._events[type].splice(position, 1);
  8217. }
  8218. if (handlers.length === 0) {
  8219. if(this.wildcard) {
  8220. delete leaf._listeners;
  8221. }
  8222. else {
  8223. delete this._events[type];
  8224. }
  8225. }
  8226. if (this._removeListener)
  8227. this.emit("removeListener", type, listener);
  8228. return this;
  8229. }
  8230. else if (handlers === listener ||
  8231. (handlers.listener && handlers.listener === listener) ||
  8232. (handlers._origin && handlers._origin === listener)) {
  8233. if(this.wildcard) {
  8234. delete leaf._listeners;
  8235. }
  8236. else {
  8237. delete this._events[type];
  8238. }
  8239. if (this._removeListener)
  8240. this.emit("removeListener", type, listener);
  8241. }
  8242. }
  8243. this.listenerTree && recursivelyGarbageCollect(this.listenerTree);
  8244. return this;
  8245. };
  8246. EventEmitter.prototype.offAny = function(fn) {
  8247. var i = 0, l = 0, fns;
  8248. if (fn && this._all && this._all.length > 0) {
  8249. fns = this._all;
  8250. for(i = 0, l = fns.length; i < l; i++) {
  8251. if(fn === fns[i]) {
  8252. fns.splice(i, 1);
  8253. if (this._removeListener)
  8254. this.emit("removeListenerAny", fn);
  8255. return this;
  8256. }
  8257. }
  8258. } else {
  8259. fns = this._all;
  8260. if (this._removeListener) {
  8261. for(i = 0, l = fns.length; i < l; i++)
  8262. this.emit("removeListenerAny", fns[i]);
  8263. }
  8264. this._all = [];
  8265. }
  8266. return this;
  8267. };
  8268. EventEmitter.prototype.removeListener = EventEmitter.prototype.off;
  8269. EventEmitter.prototype.removeAllListeners = function (type) {
  8270. if (type === undefined) {
  8271. !this._events || init.call(this);
  8272. return this;
  8273. }
  8274. if (this.wildcard) {
  8275. var leafs = searchListenerTree.call(this, null, type, this.listenerTree, 0), leaf, i;
  8276. if (!leafs) return this;
  8277. for (i = 0; i < leafs.length; i++) {
  8278. leaf = leafs[i];
  8279. leaf._listeners = null;
  8280. }
  8281. this.listenerTree && recursivelyGarbageCollect(this.listenerTree);
  8282. } else if (this._events) {
  8283. this._events[type] = null;
  8284. }
  8285. return this;
  8286. };
  8287. EventEmitter.prototype.listeners = function (type) {
  8288. var _events = this._events;
  8289. var keys, listeners, allListeners;
  8290. var i;
  8291. var listenerTree;
  8292. if (type === undefined) {
  8293. if (this.wildcard) {
  8294. throw Error('event name required for wildcard emitter');
  8295. }
  8296. if (!_events) {
  8297. return [];
  8298. }
  8299. keys = ownKeys(_events);
  8300. i = keys.length;
  8301. allListeners = [];
  8302. while (i-- > 0) {
  8303. listeners = _events[keys[i]];
  8304. if (typeof listeners === 'function') {
  8305. allListeners.push(listeners);
  8306. } else {
  8307. allListeners.push.apply(allListeners, listeners);
  8308. }
  8309. }
  8310. return allListeners;
  8311. } else {
  8312. if (this.wildcard) {
  8313. listenerTree= this.listenerTree;
  8314. if(!listenerTree) return [];
  8315. var handlers = [];
  8316. var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
  8317. searchListenerTree.call(this, handlers, ns, listenerTree, 0);
  8318. return handlers;
  8319. }
  8320. if (!_events) {
  8321. return [];
  8322. }
  8323. listeners = _events[type];
  8324. if (!listeners) {
  8325. return [];
  8326. }
  8327. return typeof listeners === 'function' ? [listeners] : listeners;
  8328. }
  8329. };
  8330. EventEmitter.prototype.eventNames = function(nsAsArray){
  8331. var _events= this._events;
  8332. return this.wildcard? collectTreeEvents.call(this, this.listenerTree, [], null, nsAsArray) : (_events? ownKeys(_events) : []);
  8333. };
  8334. EventEmitter.prototype.listenerCount = function(type) {
  8335. return this.listeners(type).length;
  8336. };
  8337. EventEmitter.prototype.hasListeners = function (type) {
  8338. if (this.wildcard) {
  8339. var handlers = [];
  8340. var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
  8341. searchListenerTree.call(this, handlers, ns, this.listenerTree, 0);
  8342. return handlers.length > 0;
  8343. }
  8344. var _events = this._events;
  8345. var _all = this._all;
  8346. return !!(_all && _all.length || _events && (type === undefined ? ownKeys(_events).length : _events[type]));
  8347. };
  8348. EventEmitter.prototype.listenersAny = function() {
  8349. if(this._all) {
  8350. return this._all;
  8351. }
  8352. else {
  8353. return [];
  8354. }
  8355. };
  8356. EventEmitter.prototype.waitFor = function (event, options) {
  8357. var self = this;
  8358. var type = typeof options;
  8359. if (type === 'number') {
  8360. options = {timeout: options};
  8361. } else if (type === 'function') {
  8362. options = {filter: options};
  8363. }
  8364. options= resolveOptions(options, {
  8365. timeout: 0,
  8366. filter: undefined,
  8367. handleError: false,
  8368. Promise: Promise,
  8369. overload: false
  8370. }, {
  8371. filter: functionReducer,
  8372. Promise: constructorReducer
  8373. });
  8374. return makeCancelablePromise(options.Promise, function (resolve, reject, onCancel) {
  8375. function listener() {
  8376. var filter= options.filter;
  8377. if (filter && !filter.apply(self, arguments)) {
  8378. return;
  8379. }
  8380. self.off(event, listener);
  8381. if (options.handleError) {
  8382. var err = arguments[0];
  8383. err ? reject(err) : resolve(toArray.apply(null, arguments).slice(1));
  8384. } else {
  8385. resolve(toArray.apply(null, arguments));
  8386. }
  8387. }
  8388. onCancel(function(){
  8389. self.off(event, listener);
  8390. });
  8391. self._on(event, listener, false);
  8392. }, {
  8393. timeout: options.timeout,
  8394. overload: options.overload
  8395. })
  8396. };
  8397. function once(emitter, name, options) {
  8398. options= resolveOptions(options, {
  8399. Promise: Promise,
  8400. timeout: 0,
  8401. overload: false
  8402. }, {
  8403. Promise: constructorReducer
  8404. });
  8405. var _Promise= options.Promise;
  8406. return makeCancelablePromise(_Promise, function(resolve, reject, onCancel){
  8407. var handler;
  8408. if (typeof emitter.addEventListener === 'function') {
  8409. handler= function () {
  8410. resolve(toArray.apply(null, arguments));
  8411. };
  8412. onCancel(function(){
  8413. emitter.removeEventListener(name, handler);
  8414. });
  8415. emitter.addEventListener(
  8416. name,
  8417. handler,
  8418. {once: true}
  8419. );
  8420. return;
  8421. }
  8422. var eventListener = function(){
  8423. errorListener && emitter.removeListener('error', errorListener);
  8424. resolve(toArray.apply(null, arguments));
  8425. };
  8426. var errorListener;
  8427. if (name !== 'error') {
  8428. errorListener = function (err){
  8429. emitter.removeListener(name, eventListener);
  8430. reject(err);
  8431. };
  8432. emitter.once('error', errorListener);
  8433. }
  8434. onCancel(function(){
  8435. errorListener && emitter.removeListener('error', errorListener);
  8436. emitter.removeListener(name, eventListener);
  8437. });
  8438. emitter.once(name, eventListener);
  8439. }, {
  8440. timeout: options.timeout,
  8441. overload: options.overload
  8442. });
  8443. }
  8444. var prototype= EventEmitter.prototype;
  8445. Object.defineProperties(EventEmitter, {
  8446. defaultMaxListeners: {
  8447. get: function () {
  8448. return prototype._maxListeners;
  8449. },
  8450. set: function (n) {
  8451. if (typeof n !== 'number' || n < 0 || Number.isNaN(n)) {
  8452. throw TypeError('n must be a non-negative number')
  8453. }
  8454. prototype._maxListeners = n;
  8455. },
  8456. enumerable: true
  8457. },
  8458. once: {
  8459. value: once,
  8460. writable: true,
  8461. configurable: true
  8462. }
  8463. });
  8464. Object.defineProperties(prototype, {
  8465. _maxListeners: {
  8466. value: defaultMaxListeners,
  8467. writable: true,
  8468. configurable: true
  8469. },
  8470. _observers: {value: null, writable: true, configurable: true}
  8471. });
  8472. if (typeof define === 'function' && define.amd) {
  8473. // AMD. Register as an anonymous module.
  8474. define(function() {
  8475. return EventEmitter;
  8476. });
  8477. } else if (typeof exports === 'object') {
  8478. // CommonJS
  8479. module.exports = EventEmitter;
  8480. }
  8481. else {
  8482. // global for any kind of environment.
  8483. var _global= new Function('','return this')();
  8484. _global.EventEmitter2 = EventEmitter;
  8485. }
  8486. }();
  8487. }).call(this)}).call(this,require('_process'),require("timers").setImmediate)
  8488. },{"_process":35,"timers":36}],34:[function(require,module,exports){
  8489. /**
  8490. * Helpers.
  8491. */
  8492. var s = 1000;
  8493. var m = s * 60;
  8494. var h = m * 60;
  8495. var d = h * 24;
  8496. var w = d * 7;
  8497. var y = d * 365.25;
  8498. /**
  8499. * Parse or format the given `val`.
  8500. *
  8501. * Options:
  8502. *
  8503. * - `long` verbose formatting [false]
  8504. *
  8505. * @param {String|Number} val
  8506. * @param {Object} [options]
  8507. * @throws {Error} throw an error if val is not a non-empty string or a number
  8508. * @return {String|Number}
  8509. * @api public
  8510. */
  8511. module.exports = function(val, options) {
  8512. options = options || {};
  8513. var type = typeof val;
  8514. if (type === 'string' && val.length > 0) {
  8515. return parse(val);
  8516. } else if (type === 'number' && isFinite(val)) {
  8517. return options.long ? fmtLong(val) : fmtShort(val);
  8518. }
  8519. throw new Error(
  8520. 'val is not a non-empty string or a valid number. val=' +
  8521. JSON.stringify(val)
  8522. );
  8523. };
  8524. /**
  8525. * Parse the given `str` and return milliseconds.
  8526. *
  8527. * @param {String} str
  8528. * @return {Number}
  8529. * @api private
  8530. */
  8531. function parse(str) {
  8532. str = String(str);
  8533. if (str.length > 100) {
  8534. return;
  8535. }
  8536. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  8537. str
  8538. );
  8539. if (!match) {
  8540. return;
  8541. }
  8542. var n = parseFloat(match[1]);
  8543. var type = (match[2] || 'ms').toLowerCase();
  8544. switch (type) {
  8545. case 'years':
  8546. case 'year':
  8547. case 'yrs':
  8548. case 'yr':
  8549. case 'y':
  8550. return n * y;
  8551. case 'weeks':
  8552. case 'week':
  8553. case 'w':
  8554. return n * w;
  8555. case 'days':
  8556. case 'day':
  8557. case 'd':
  8558. return n * d;
  8559. case 'hours':
  8560. case 'hour':
  8561. case 'hrs':
  8562. case 'hr':
  8563. case 'h':
  8564. return n * h;
  8565. case 'minutes':
  8566. case 'minute':
  8567. case 'mins':
  8568. case 'min':
  8569. case 'm':
  8570. return n * m;
  8571. case 'seconds':
  8572. case 'second':
  8573. case 'secs':
  8574. case 'sec':
  8575. case 's':
  8576. return n * s;
  8577. case 'milliseconds':
  8578. case 'millisecond':
  8579. case 'msecs':
  8580. case 'msec':
  8581. case 'ms':
  8582. return n;
  8583. default:
  8584. return undefined;
  8585. }
  8586. }
  8587. /**
  8588. * Short format for `ms`.
  8589. *
  8590. * @param {Number} ms
  8591. * @return {String}
  8592. * @api private
  8593. */
  8594. function fmtShort(ms) {
  8595. var msAbs = Math.abs(ms);
  8596. if (msAbs >= d) {
  8597. return Math.round(ms / d) + 'd';
  8598. }
  8599. if (msAbs >= h) {
  8600. return Math.round(ms / h) + 'h';
  8601. }
  8602. if (msAbs >= m) {
  8603. return Math.round(ms / m) + 'm';
  8604. }
  8605. if (msAbs >= s) {
  8606. return Math.round(ms / s) + 's';
  8607. }
  8608. return ms + 'ms';
  8609. }
  8610. /**
  8611. * Long format for `ms`.
  8612. *
  8613. * @param {Number} ms
  8614. * @return {String}
  8615. * @api private
  8616. */
  8617. function fmtLong(ms) {
  8618. var msAbs = Math.abs(ms);
  8619. if (msAbs >= d) {
  8620. return plural(ms, msAbs, d, 'day');
  8621. }
  8622. if (msAbs >= h) {
  8623. return plural(ms, msAbs, h, 'hour');
  8624. }
  8625. if (msAbs >= m) {
  8626. return plural(ms, msAbs, m, 'minute');
  8627. }
  8628. if (msAbs >= s) {
  8629. return plural(ms, msAbs, s, 'second');
  8630. }
  8631. return ms + ' ms';
  8632. }
  8633. /**
  8634. * Pluralization helper.
  8635. */
  8636. function plural(ms, msAbs, n, name) {
  8637. var isPlural = msAbs >= n * 1.5;
  8638. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  8639. }
  8640. },{}],35:[function(require,module,exports){
  8641. // shim for using process in browser
  8642. var process = module.exports = {};
  8643. // cached from whatever global is present so that test runners that stub it
  8644. // don't break things. But we need to wrap it in a try catch in case it is
  8645. // wrapped in strict mode code which doesn't define any globals. It's inside a
  8646. // function because try/catches deoptimize in certain engines.
  8647. var cachedSetTimeout;
  8648. var cachedClearTimeout;
  8649. function defaultSetTimout() {
  8650. throw new Error('setTimeout has not been defined');
  8651. }
  8652. function defaultClearTimeout () {
  8653. throw new Error('clearTimeout has not been defined');
  8654. }
  8655. (function () {
  8656. try {
  8657. if (typeof setTimeout === 'function') {
  8658. cachedSetTimeout = setTimeout;
  8659. } else {
  8660. cachedSetTimeout = defaultSetTimout;
  8661. }
  8662. } catch (e) {
  8663. cachedSetTimeout = defaultSetTimout;
  8664. }
  8665. try {
  8666. if (typeof clearTimeout === 'function') {
  8667. cachedClearTimeout = clearTimeout;
  8668. } else {
  8669. cachedClearTimeout = defaultClearTimeout;
  8670. }
  8671. } catch (e) {
  8672. cachedClearTimeout = defaultClearTimeout;
  8673. }
  8674. } ())
  8675. function runTimeout(fun) {
  8676. if (cachedSetTimeout === setTimeout) {
  8677. //normal enviroments in sane situations
  8678. return setTimeout(fun, 0);
  8679. }
  8680. // if setTimeout wasn't available but was latter defined
  8681. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  8682. cachedSetTimeout = setTimeout;
  8683. return setTimeout(fun, 0);
  8684. }
  8685. try {
  8686. // when when somebody has screwed with setTimeout but no I.E. maddness
  8687. return cachedSetTimeout(fun, 0);
  8688. } catch(e){
  8689. try {
  8690. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  8691. return cachedSetTimeout.call(null, fun, 0);
  8692. } catch(e){
  8693. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  8694. return cachedSetTimeout.call(this, fun, 0);
  8695. }
  8696. }
  8697. }
  8698. function runClearTimeout(marker) {
  8699. if (cachedClearTimeout === clearTimeout) {
  8700. //normal enviroments in sane situations
  8701. return clearTimeout(marker);
  8702. }
  8703. // if clearTimeout wasn't available but was latter defined
  8704. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  8705. cachedClearTimeout = clearTimeout;
  8706. return clearTimeout(marker);
  8707. }
  8708. try {
  8709. // when when somebody has screwed with setTimeout but no I.E. maddness
  8710. return cachedClearTimeout(marker);
  8711. } catch (e){
  8712. try {
  8713. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  8714. return cachedClearTimeout.call(null, marker);
  8715. } catch (e){
  8716. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  8717. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  8718. return cachedClearTimeout.call(this, marker);
  8719. }
  8720. }
  8721. }
  8722. var queue = [];
  8723. var draining = false;
  8724. var currentQueue;
  8725. var queueIndex = -1;
  8726. function cleanUpNextTick() {
  8727. if (!draining || !currentQueue) {
  8728. return;
  8729. }
  8730. draining = false;
  8731. if (currentQueue.length) {
  8732. queue = currentQueue.concat(queue);
  8733. } else {
  8734. queueIndex = -1;
  8735. }
  8736. if (queue.length) {
  8737. drainQueue();
  8738. }
  8739. }
  8740. function drainQueue() {
  8741. if (draining) {
  8742. return;
  8743. }
  8744. var timeout = runTimeout(cleanUpNextTick);
  8745. draining = true;
  8746. var len = queue.length;
  8747. while(len) {
  8748. currentQueue = queue;
  8749. queue = [];
  8750. while (++queueIndex < len) {
  8751. if (currentQueue) {
  8752. currentQueue[queueIndex].run();
  8753. }
  8754. }
  8755. queueIndex = -1;
  8756. len = queue.length;
  8757. }
  8758. currentQueue = null;
  8759. draining = false;
  8760. runClearTimeout(timeout);
  8761. }
  8762. process.nextTick = function (fun) {
  8763. var args = new Array(arguments.length - 1);
  8764. if (arguments.length > 1) {
  8765. for (var i = 1; i < arguments.length; i++) {
  8766. args[i - 1] = arguments[i];
  8767. }
  8768. }
  8769. queue.push(new Item(fun, args));
  8770. if (queue.length === 1 && !draining) {
  8771. runTimeout(drainQueue);
  8772. }
  8773. };
  8774. // v8 likes predictible objects
  8775. function Item(fun, array) {
  8776. this.fun = fun;
  8777. this.array = array;
  8778. }
  8779. Item.prototype.run = function () {
  8780. this.fun.apply(null, this.array);
  8781. };
  8782. process.title = 'browser';
  8783. process.browser = true;
  8784. process.env = {};
  8785. process.argv = [];
  8786. process.version = ''; // empty string to avoid regexp issues
  8787. process.versions = {};
  8788. function noop() {}
  8789. process.on = noop;
  8790. process.addListener = noop;
  8791. process.once = noop;
  8792. process.off = noop;
  8793. process.removeListener = noop;
  8794. process.removeAllListeners = noop;
  8795. process.emit = noop;
  8796. process.prependListener = noop;
  8797. process.prependOnceListener = noop;
  8798. process.listeners = function (name) { return [] }
  8799. process.binding = function (name) {
  8800. throw new Error('process.binding is not supported');
  8801. };
  8802. process.cwd = function () { return '/' };
  8803. process.chdir = function (dir) {
  8804. throw new Error('process.chdir is not supported');
  8805. };
  8806. process.umask = function() { return 0; };
  8807. },{}],36:[function(require,module,exports){
  8808. (function (setImmediate,clearImmediate){(function (){
  8809. var nextTick = require('process/browser.js').nextTick;
  8810. var apply = Function.prototype.apply;
  8811. var slice = Array.prototype.slice;
  8812. var immediateIds = {};
  8813. var nextImmediateId = 0;
  8814. // DOM APIs, for completeness
  8815. exports.setTimeout = function() {
  8816. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  8817. };
  8818. exports.setInterval = function() {
  8819. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  8820. };
  8821. exports.clearTimeout =
  8822. exports.clearInterval = function(timeout) { timeout.close(); };
  8823. function Timeout(id, clearFn) {
  8824. this._id = id;
  8825. this._clearFn = clearFn;
  8826. }
  8827. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  8828. Timeout.prototype.close = function() {
  8829. this._clearFn.call(window, this._id);
  8830. };
  8831. // Does not start the time, just sets up the members needed.
  8832. exports.enroll = function(item, msecs) {
  8833. clearTimeout(item._idleTimeoutId);
  8834. item._idleTimeout = msecs;
  8835. };
  8836. exports.unenroll = function(item) {
  8837. clearTimeout(item._idleTimeoutId);
  8838. item._idleTimeout = -1;
  8839. };
  8840. exports._unrefActive = exports.active = function(item) {
  8841. clearTimeout(item._idleTimeoutId);
  8842. var msecs = item._idleTimeout;
  8843. if (msecs >= 0) {
  8844. item._idleTimeoutId = setTimeout(function onTimeout() {
  8845. if (item._onTimeout)
  8846. item._onTimeout();
  8847. }, msecs);
  8848. }
  8849. };
  8850. // That's not how node.js implements it but the exposed api is the same.
  8851. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  8852. var id = nextImmediateId++;
  8853. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  8854. immediateIds[id] = true;
  8855. nextTick(function onNextTick() {
  8856. if (immediateIds[id]) {
  8857. // fn.call() is faster so we optimize for the common use-case
  8858. // @see http://jsperf.com/call-apply-segu
  8859. if (args) {
  8860. fn.apply(null, args);
  8861. } else {
  8862. fn.call(null);
  8863. }
  8864. // Prevent ids from leaking
  8865. exports.clearImmediate(id);
  8866. }
  8867. });
  8868. return id;
  8869. };
  8870. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  8871. delete immediateIds[id];
  8872. };
  8873. }).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  8874. },{"process/browser.js":35,"timers":36}],37:[function(require,module,exports){
  8875. module.exports={
  8876. "name": "@pm2/js-api",
  8877. "version": "0.6.7",
  8878. "description": "PM2.io API Client for Javascript",
  8879. "main": "index.js",
  8880. "unpkg": "dist/keymetrics.es5.min.js",
  8881. "engines": {
  8882. "node": ">=4.0"
  8883. },
  8884. "scripts": {
  8885. "test": "mocha test/*",
  8886. "build": "mkdir -p dist; browserify -s Keymetrics -r ./ > ./dist/keymetrics.es5.js",
  8887. "dist": "mkdir -p dist; browserify -s Keymetrics -r ./ | uglifyjs -c warnings=false -m > ./dist/keymetrics.es5.min.js",
  8888. "doc": "jsdoc -r ./src --readme ./README.md -d doc -t ./node_modules/minami",
  8889. "clean": "rm dist/*",
  8890. "prepare": "npm run build && npm run dist"
  8891. },
  8892. "repository": {
  8893. "type": "git",
  8894. "url": "git+https://github.com/keymetrics/km.js.git"
  8895. },
  8896. "keywords": [
  8897. "keymetrics",
  8898. "api",
  8899. "dashboard",
  8900. "monitoring",
  8901. "wrapper"
  8902. ],
  8903. "author": "Keymetrics Team",
  8904. "license": "Apache-2",
  8905. "bugs": {
  8906. "url": "https://github.com/keymetrics/km.js/issues"
  8907. },
  8908. "homepage": "https://github.com/keymetrics/km.js#readme",
  8909. "dependencies": {
  8910. "async": "^2.6.3",
  8911. "axios": "^0.21.0",
  8912. "debug": "~4.3.1",
  8913. "eventemitter2": "^6.3.1",
  8914. "ws": "^7.0.0"
  8915. },
  8916. "devDependencies": {
  8917. "@babel/core": "^7.0.0",
  8918. "@babel/preset-env": "^7.0.0",
  8919. "babelify": "10.0.0",
  8920. "browserify": "^17.0.0",
  8921. "jsdoc": "^3.4.2",
  8922. "minami": "^1.1.1",
  8923. "mocha": "^7.0.0",
  8924. "should": "*",
  8925. "uglify-es": "~3.3.9"
  8926. },
  8927. "browserify": {
  8928. "debug": true,
  8929. "transform": [
  8930. [
  8931. "babelify",
  8932. {
  8933. "presets": [
  8934. [
  8935. "@babel/preset-env",
  8936. {
  8937. "debug": false,
  8938. "forceAllTransforms": true
  8939. }
  8940. ]
  8941. ],
  8942. "sourceMaps": true
  8943. }
  8944. ]
  8945. ]
  8946. },
  8947. "browser": {
  8948. "./src/auth_strategies/embed_strategy.js": false,
  8949. "ws": false
  8950. }
  8951. }
  8952. },{}],38:[function(require,module,exports){
  8953. module.exports={"actions":[{"route":{"name":"/api/bucket/:id/actions/trigger","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"server_name","type":"string","description":"the name of the server","optional":false,"defaultvalue":null},{"name":"process_id","type":"number","description":"the id of the process","optional":true,"defaultvalue":null},{"name":"app_name","type":"number","description":"the name of the process","optional":true,"defaultvalue":null},{"name":"action_name","type":"string","description":"the name of the action to trigger","optional":false,"defaultvalue":null},{"name":"opts","type":"object","description":"any specific options to be passed to the function","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully run the action","optional":false}],"response":[{"name":"success","type":"boolean","description":"succesully sended the action to PM2","optional":false,"defaultvalue":null}],"name":"triggerAction","longname":"Actions.triggerAction","scope":"route"},{"route":{"name":"/api/bucket/:id/actions/triggerPM2","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"server_name","type":"string","description":"the name of the server","optional":false,"defaultvalue":null},{"name":"method_name","type":"string","description":"the name of the pm2 method to trigger","optional":false,"defaultvalue":null},{"name":"app_name","type":"string","description":"the name of the application","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"failed action","optional":false},{"type":"200","description":"succesfully run the action","optional":false}],"response":[{"name":"success","type":"boolean","description":"succesully sended the action to PM2","optional":false,"defaultvalue":null}],"name":"triggerPM2Action","longname":"Actions.triggerPM2Action","scope":"route"},{"route":{"name":"/api/bucket/:id/actions/triggerScopedAction","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"server_name","type":"string","description":"the name of the server","optional":false,"defaultvalue":null},{"name":"action_name","type":"string","description":"the name of the pm2 method to trigger","optional":false,"defaultvalue":null},{"name":"app_name","type":"string","description":"the name of the application","optional":false,"defaultvalue":null},{"name":"pm_id","type":"number","description":"the id of the process","optional":false,"defaultvalue":null},{"name":"opts","type":"object","description":"custom parameters to give to the action","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully run the action","optional":false}],"response":[{"name":".","type":"object","description":"the action sended to the process","optional":false,"defaultvalue":null}],"name":"triggerScopedAction","longname":"Actions.triggerScopedAction","scope":"route"}],"bucket":{"alert":{"analyzer":[{"route":{"name":"/api/bucket/:id/alerts/analyzer","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"size","type":"integer","description":"line limit, default to 20","optional":true,"defaultvalue":null},{"name":"from","type":"integer","description":"offset limit","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"list all alerts","optional":false}],"name":"list","longname":"Bucket.alert.analyzer.list","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/alerts/analyzer/:alert","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":alert","type":"string","description":"alert id","optional":false}],"body":[{"name":"useful","type":"boolean","description":"","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"content modified","optional":false}],"name":"editState","longname":"Bucket.alert.analyzer.editState","scope":"route"},{"route":{"name":"/api/bucket/:id/alerts/analyzer/:analyzer/config","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":analyzer","type":"string","description":"analyzer name","optional":false}],"body":[{"name":"blacklist","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"blacklist.apps","type":"array","description":"","optional":true,"defaultvalue":null},{"name":"blacklist.servers","type":"array","description":"","optional":true,"defaultvalue":null},{"name":"blacklist.metrics","type":"array","description":"","optional":true,"defaultvalue":null},{"name":"threshold","type":"number","description":"","optional":false,"defaultvalue":null},{"name":"window","type":"number","description":"","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"content modified","optional":false}],"name":"updateConfig","longname":"Bucket.alert.analyzer.updateConfig","scope":"route"}],"default":[{"route":{"name":"/api/bucket/:id/alerts","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"name","type":"string","description":"Alert name","optional":false,"defaultvalue":null},{"name":"enabled","type":"boolean","description":"Alert's state","optional":true,"defaultvalue":null},{"name":"type","type":"string","description":"Should be `metric`, `event` or `webcheck`","optional":false,"defaultvalue":null},{"name":"initiator","type":"string","description":"Should be metric name or event name","optional":false,"defaultvalue":null},{"name":"options","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"options.operator","type":"string","description":"Should be `>`, `<`, `=`, `>=` or `<=`","optional":true,"defaultvalue":null},{"name":"options.threshold","type":"number","description":"Value to reach to send an alert","optional":true,"defaultvalue":null},{"name":"options.act","type":"string","description":"Should be `always`, `opposite`, `first` or `diff`","optional":true,"defaultvalue":null},{"name":"options.timerange","type":"number","description":"Timerange to check, in seconds","optional":true,"defaultvalue":null},{"name":"scope","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"scope.apps","type":"object","description":"Array of strings with apps name (can be empty)","optional":true,"defaultvalue":null},{"name":"scope.servers","type":"object","description":"Array of strings with servers name (can be empty)","optional":true,"defaultvalue":null},{"name":"scope.initiators","type":"object","description":"Array of strings with initiators name (need to be set if no apps or servers)","optional":true,"defaultvalue":null},{"name":"scope.sources","type":"object","description":"Array of strings with sources name (can be empty)","optional":true,"defaultvalue":null},{"name":"actions","type":"object","description":"List of actions to trigger","optional":false,"defaultvalue":null},{"name":"actions[].type","type":"string","description":"Type of action","optional":true,"defaultvalue":null},{"name":"actions[].params","type":"object","description":"Params for action","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing parameters","optional":false},{"type":"200","description":"successfuly created alert","optional":false}],"name":"create","longname":"Bucket.alert.create","scope":"route"},{"route":{"name":"/api/bucket/:id/alerts/:alert","type":"DELETE"},"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":alert","type":"string","description":"alert id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"204","description":"successfuly deleted alert","optional":false}],"name":"delete","longname":"Bucket.alert.delete","scope":"route","authentication":false},{"route":{"name":"/api/bucket/:id/alerts/","type":"GET"},"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"list all alerts","optional":false}],"name":"list","longname":"Bucket.alert.list","scope":"route","authentication":false},{"route":{"name":"/api/bucket/:id/alerts/:alert","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":alert","type":"string","description":"alert id","optional":false}],"body":[{"name":"name","type":"string","description":"Alert name","optional":true,"defaultvalue":null},{"name":"enabled","type":"boolean","description":"Alert's state","optional":true,"defaultvalue":null},{"name":"type","type":"string","description":"Should be `metric`, `event` or `webcheck`","optional":true,"defaultvalue":null},{"name":"initiator","type":"string","description":"Should be metric name or event name","optional":true,"defaultvalue":null},{"name":"options","type":"object","description":"","optional":true,"defaultvalue":null},{"name":"options.operator","type":"string","description":"Should be `>`, `<`, `=`, `<=` or `>=`","optional":true,"defaultvalue":null},{"name":"options.threshold","type":"number","description":"Value to reach to send an alert","optional":true,"defaultvalue":null},{"name":"options.act","type":"string","description":"Should be `always`, `opposite`, `first` or `diff`","optional":true,"defaultvalue":null},{"name":"options.timerange","type":"number","description":"Timerange to check, in seconds","optional":true,"defaultvalue":null},{"name":"scope","type":"object","description":"","optional":true,"defaultvalue":null},{"name":"scope.apps","type":"array","description":"Array of strings with apps name (can be empty)","optional":true,"defaultvalue":null},{"name":"scope.servers","type":"array","description":"Array of strings with servers name (can be empty)","optional":true,"defaultvalue":null},{"name":"scope.initiators","type":"object","description":"Array of strings with initiators name (need to be set if no apps or servers)","optional":true,"defaultvalue":null},{"name":"scope.sources","type":"object","description":"Array of strings with sources name (can be empty)","optional":true,"defaultvalue":null},{"name":"actions","type":"array","description":"List of actions to trigger","optional":true,"defaultvalue":null},{"name":"actions[].type","type":"string","description":"Type of action","optional":true,"defaultvalue":null},{"name":"actions[].params","type":"object","description":"Params for action","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing parameters","optional":false},{"type":"404","description":"alert not found","optional":false},{"type":"200","description":"successfuly created alert","optional":false}],"name":"updateAlert","longname":"Bucket.alert.updateAlert","scope":"route"},{"route":{"name":"/api/bucket/:id/alerts/:alert","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":alert","type":"string","description":"alert id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"404","description":"alert not found","optional":false},{"type":"200","description":"successfuly returned alert","optional":false}],"name":"get","longname":"Bucket.alert.get","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/alerts/:alert/sample","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":alert","type":"string","description":"alert id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"404","description":"alert not found","optional":false},{"type":"202","description":"successfuly sended alert actions","optional":false}],"name":"triggerSample","longname":"Bucket.alert.triggerSample","scope":"route"},{"route":{"name":"/api/bucket/:id/alerts/update","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"triggers","type":"object","description":"","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing triggers parameter","optional":false},{"type":"200","description":"succesfully update triggers","optional":false}],"response":[{"name":"triggers","type":"object","description":"new triggers object","optional":false,"defaultvalue":null}],"name":"update","longname":"Bucket.alert.update","scope":"route"},{"route":{"name":"/api/bucket/:id/alerts/updateSlack","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"slack","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"slack.active","type":"boolean","description":"","optional":true,"defaultvalue":null},{"name":"slack.url","type":"boolean","description":"needed if active is set to true","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing triggers parameter","optional":false},{"type":"200","description":"succesfully update triggers","optional":false}],"response":[{"name":"bucket","type":"object","description":"","optional":false,"defaultvalue":null}],"name":"updateSlack","longname":"Bucket.alert.updateSlack","scope":"route"},{"route":{"name":"/api/bucket/:id/alerts/updateWebhooks","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"webhooks","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"webhooks.active","type":"boolean","description":"","optional":true,"defaultvalue":null},{"name":"webhooks.url","type":"boolean","description":"needed if active is set to true","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing triggers parameter","optional":false},{"type":"200","description":"succesfully update triggers","optional":false}],"response":[{"name":"bucket","type":"object","description":"","optional":false,"defaultvalue":null}],"name":"updateWebhooks","longname":"Bucket.alert.updateWebhooks","scope":"route"}]},"application":[{"route":{"name":"/api/bucket/:id/applications","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"successfuly retrieved applications","optional":false}],"name":"list","longname":"Bucket.application.list","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/applications/:application","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":application","type":"string","description":"application id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"404","description":"application not found","optional":false},{"type":"200","description":"successfuly retrieved application","optional":false}],"name":"get","longname":"Bucket.application.get","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/applications","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"name","type":"string","description":"","optional":false,"defaultvalue":null},{"name":"domains","type":"object","description":"Array of string with domains","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing parameters","optional":false},{"type":"200","description":"successfuly created application","optional":false}],"name":"create","longname":"Bucket.application.create","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/applications/:application","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":application","type":"string","description":"application id","optional":false}],"body":[{"name":"name","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"domains","type":"object","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing parameters","optional":false},{"type":"200","description":"successfuly updated application","optional":false}],"name":"update","longname":"Bucket.application.update","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/applications/:application","type":"DELETE"},"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":application","type":"string","description":"application id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"204","description":"successfuly deleted application","optional":false}],"name":"delete","longname":"Bucket.application.delete","scope":"route","async":true,"authentication":false},{"route":{"name":"/api/bucket/:id/applications/:application/preview","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":application","type":"string","description":"application id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"404","description":"preview not found","optional":false},{"type":"200","description":"successfuly retrieved application screenshot","optional":false}],"name":"getPreview","longname":"Bucket.application.getPreview","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/applications/:application/report","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":application","type":"string","description":"application id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"404","description":"report not found","optional":false},{"type":"200","description":"successfuly retrieved application report","optional":false}],"name":"getReports","longname":"Bucket.application.getReports","scope":"route","async":true}],"billing":[{"route":{"name":"/api/bucket/:id/payment/subscribe","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"plan","type":"string","description":"name of the plan to upgrade to","optional":false,"defaultvalue":null},{"name":"stripe_token","type":"string","description":"a card token created by stripe","optional":true,"defaultvalue":null},{"name":"coupon_id","type":"string","description":"the id of the stripe coupon","optional":true,"defaultvalue":null}],"code":[{"type":"400","description":"missing/invalid parameters","optional":false},{"type":"403","description":"need a credit card OR not allowed to subscribe to the plan","optional":false},{"type":"500","description":"stripe/database error","optional":false},{"type":"200","description":"succesfully upgraded","optional":false}],"response":[{"name":"bucket","type":"object","description":"the bucket object","optional":false,"defaultvalue":null},{"name":"subscription","type":"object","description":"the subscription object attached to the subscription","optional":false,"defaultvalue":null}],"name":"subscribe","longname":"Bucket.billing.subscribe","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/payment/subscribe/:paymentIntent","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":paymentIntent","type":"string","description":"paymentIntent id","optional":false}],"body":[{"name":"plan","type":"string","description":"name of the plan to upgrade to","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"missing/invalid parameters","optional":false},{"type":"500","description":"stripe/database error","optional":false},{"type":"200","description":"succesfully upgraded","optional":false}],"response":[{"name":"bucket","type":"object","description":"the bucket object","optional":false,"defaultvalue":null}],"name":"paymentIntentSucceed","longname":"Bucket.billing.paymentIntentSucceed","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/payment/trial","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"plan","type":"string","description":"Plan to trial","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"can't claim trial","optional":false},{"type":"200","description":"trial launched","optional":false}],"response":[{"name":"duration","type":"string","description":"the duration of the trial","optional":false,"defaultvalue":null},{"name":"plan","type":"string","description":"the plan of the trial","optional":false,"defaultvalue":null}],"name":"startTrial","longname":"Bucket.billing.startTrial","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/payment/invoices","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"400","description":"Missing/invalid parameters","optional":false},{"type":"404","description":"This bucket hasn't invoices","optional":false},{"type":"200","description":"succesfully returns invoices","optional":false}],"response":[{"name":".","type":"array","description":"array of invoices","optional":false,"defaultvalue":null}],"name":"getInvoices","longname":"Bucket.billing.getInvoices","scope":"route"},{"route":{"name":"/api/bucket/:id/payment/receipts","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"400","description":"Missing/invalid parameters","optional":false},{"type":"404","description":"This bucket hasn't receipts","optional":false},{"type":"200","description":"succesfully returns receipts","optional":false}],"response":[{"name":".","type":"array","description":"array of receipts","optional":false,"defaultvalue":null}],"name":"getReceipts","longname":"Bucket.billing.getReceipts","scope":"route"},{"route":{"name":"/api/bucket/:id/payment/subscription","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"404","description":"the bucket doesnt have any subscription","optional":false},{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved the subscription","optional":false}],"response":[{"name":".","type":"object","description":"subscription object","optional":false,"defaultvalue":null}],"name":"getSubcription","longname":"Bucket.billing.getSubcription","scope":"route"},{"route":{"name":"/api/bucket/:id/payment/subscription/state","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"404","description":"the bucket doesnt have any subscription","optional":false},{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved the subscription","optional":false}],"response":[{"name":"status","type":"string","description":"stripe state of the subscription","optional":false,"defaultvalue":null},{"name":"plan","type":"string","description":"stripe plan name of the subscription","optional":false,"defaultvalue":null},{"name":"canceled_at","type":"string","description":"if he sub has been cancelled, add the date","optional":false,"defaultvalue":null}],"name":"getSubcriptionState","longname":"Bucket.billing.getSubcriptionState","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/payment/cards","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"token","type":"string","description":"card token generated by stripe","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"missing parameters","optional":false},{"type":"500","description":"stripe error","optional":false},{"type":"200","description":"succesfully added the card","optional":false}],"response":[{"name":"data","type":"object","description":"stripe credit card Object","optional":false,"defaultvalue":null}],"name":"attachCreditCard","longname":"Bucket.billing.attachCreditCard","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/payment/cards","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"404","description":"the user doesn't have any default card","optional":false},{"type":"200","description":"succesfully retieved the charges","optional":false}],"response":[{"name":"data","type":"array","description":"list of stripe cards object","optional":false,"defaultvalue":null}],"name":"fetchCreditCards","longname":"Bucket.billing.fetchCreditCards","scope":"route"},{"route":{"name":"/api/bucket/:id/payment/card/:card_id","type":"GET"},"authentication":true,"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":card_id","type":"string","description":"the stripe id of the card","optional":false}],"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"400","description":"missing parameters card_id","optional":false},{"type":"404","description":"the user doesn't have any default card","optional":false},{"type":"200","description":"succesfully retieved the card","optional":false}],"response":[{"name":"data","type":"array","description":"stripe card object","optional":false,"defaultvalue":null}],"name":"fetchCreditCard","longname":"Bucket.billing.fetchCreditCard","scope":"route"},{"route":{"name":"/api/bucket/:id/payment/card","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"404","description":"the user doesn't have any default card","optional":false},{"type":"200","description":"succesfully retieved the card","optional":false}],"response":[{"name":"data","type":"array","description":"stripe card object","optional":false,"defaultvalue":null}],"name":"fetchDefaultCreditCard","longname":"Bucket.billing.fetchDefaultCreditCard","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/payment/card","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"id","type":"string","description":"stripe card id","optional":false,"defaultvalue":null},{"name":"address_line1","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"address_country","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"address_zip","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"address_city","type":"string","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"400","description":"missing parameters, you need to specify a card","optional":false},{"type":"200","description":"succesfully updated the card","optional":false}],"response":[{"name":"data","type":"array","description":"stripe card object","optional":false,"defaultvalue":null}],"name":"updateCreditCard","longname":"Bucket.billing.updateCreditCard","scope":"route"},{"route":{"name":"/api/bucket/:id/payment/card/:card_id","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":card_id","type":"string","description":"the stripe id of the card","optional":false}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"400","description":"missing parameters card_id","optional":false},{"type":"200","description":"succesfully retieved the card","optional":false},{"type":"403","description":"the user must have one card active when having a subscription","optional":false}],"response":[{"name":".","type":"object","description":"stripe card object","optional":false,"defaultvalue":null}],"name":"deleteCreditCard","longname":"Bucket.billing.deleteCreditCard","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/payment/card/:card_id/default","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":card_id","type":"string","description":"the stripe id of the card","optional":false}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"400","description":"missing parameters card_id","optional":false},{"type":"200","description":"succesfully set the card as default","optional":false}],"response":[{"name":"data","type":"object","description":"stripe card object","optional":false,"defaultvalue":null}],"name":"setDefaultCard","longname":"Bucket.billing.setDefaultCard","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/payment","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"400","description":"missing parameters card_id","optional":false},{"type":"200","description":"succesfully retrieved the metadata","optional":false}],"response":[{"name":".","type":"object","description":"stripe metadata object","optional":false,"defaultvalue":null}],"name":"fetchMetadata","longname":"Bucket.billing.fetchMetadata","scope":"route"},{"route":{"name":"/api/bucket/:id/payment","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"metadata","type":"object","description":"the metadata you can update","optional":false,"defaultvalue":null},{"name":"metadata.vat_number","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"metadata.company_name","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"metadata.receipt_email","type":"string","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"400","description":"missing parameters, you need to specify a card","optional":false},{"type":"200","description":"succesfully updated the card","optional":false}],"response":[{"name":"data","type":"array","description":"stripe customer metadata object","optional":false,"defaultvalue":null}],"name":"updateMetadata","longname":"Bucket.billing.updateMetadata","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/payment/banks","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"iban","type":"string","description":"the iban used to recognize the account","optional":true,"defaultvalue":null},{"name":"type","type":"string","description":"the type of the bank account (currently only sepa is available)","optional":false,"defaultvalue":null},{"name":"name","type":"string","description":"name of the bank account owner","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"missing parameters","optional":false},{"type":"500","description":"stripe error","optional":false},{"type":"200","description":"succesfully added the account","optional":false}],"response":[{"name":"data","type":"object","description":"stripe credit card Object","optional":false,"defaultvalue":null}],"name":"attachBankAccount","longname":"Bucket.billing.attachBankAccount","scope":"route"},{"route":{"name":"/api/bucket/:id/payment/banks","type":"GET"},"authentication":true,"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"404","description":"the user doesn't have any default account","optional":false},{"type":"200","description":"succesfully retieved the card","optional":false}],"response":[{"name":"data","type":"object","description":"stripe source object","optional":false,"defaultvalue":null}],"name":"fetchBankAccount","longname":"Bucket.billing.fetchBankAccount","scope":"route"},{"route":{"name":"/api/bucket/:id/payment/banks","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"200","description":"succesfully retieved the card","optional":false},{"type":"404","description":"the user doesn't have any default account","optional":false}],"response":[{"name":".","type":"object","description":"stripe source object","optional":false,"defaultvalue":null}],"name":"deleteBankAccount","longname":"Bucket.billing.deleteBankAccount","scope":"route"}],"dashboardschema":[{"route":{"name":"/api/bucket/:id/dashboardSchema/","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"name","type":"string","description":"the name of the dashboard","optional":false,"defaultvalue":null},{"name":"data","type":"object","description":"the list of component that compose the dashboard","optional":false,"defaultvalue":null},{"name":"mode","type":"string","description":"the dashboard mode","optional":false,"defaultvalue":null},{"name":"image","type":"object","description":"background image for the dashboard","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully created dashboard","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"dashboard","description":"complete dashboard object from database","optional":false,"defaultvalue":null}],"name":"create","longname":"Bucket.dashboardschema.create","scope":"route"},{"route":{"name":"/api/bucket/:id/dashboardSchema/","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"array","description":"array of servers status","optional":false,"defaultvalue":null}],"name":"retrieveAll","longname":"Bucket.dashboardschema.retrieveAll","scope":"route"},{"route":{"name":"/api/bucket/:id/dashboardSchema/:dashid/visualization","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":dashid","type":"string","description":"dashboard id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"404","description":"dashboard not found","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"array","description":"array of dashboards","optional":false,"defaultvalue":null}],"name":"visualization","longname":"Bucket.dashboardschema.visualization","scope":"route"},{"route":{"name":"/api/bucket/:id/dashboardSchema/:dashid","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":dashid","type":"string","description":"dashboard id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"404","description":"dashboard not found","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"array","description":"array of dashboards","optional":false,"defaultvalue":null}],"name":"retrieve","longname":"Bucket.dashboardschema.retrieve","scope":"route"},{"route":{"name":"/api/bucket/:id/dashboardSchema/:dashid","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":dashid","type":"string","description":"dashboard id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully deleted dashboard","optional":false},{"type":"400","description":"Invalid params","optional":false},{"type":"404","description":"dashboard not found","optional":false}],"response":[{"name":".","type":"array","description":"array of dashboards","optional":false,"defaultvalue":null}],"name":"remove","longname":"Bucket.dashboardschema.remove","scope":"route"},{"route":{"name":"/api/bucket/:id/dashboardSchema/:dashId","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":dashId","type":"string","description":"dashboard id","optional":false}],"body":[{"name":"name","type":"string","description":"the name of the dashboard","optional":false,"defaultvalue":null},{"name":"data","type":"object","description":"the data to populate the dashboard","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"404","description":"dashboard not found","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"array","description":"array of servers status","optional":false,"defaultvalue":null}],"name":"update","longname":"Bucket.dashboardschema.update","scope":"route"}],"server":[{"route":{"name":"/api/bucket/:id/data/deleteServer","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"server_name","type":"string","description":"the name of server","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"406","description":"require an action before delete","optional":false},{"type":"400","description":"missing or invalid parameters","optional":false},{"type":"200","description":"successfully deleted","optional":false}],"response":[{"name":"success","type":"boolean","description":"can be true or false","optional":false,"defaultvalue":null},{"name":"msg","type":"string","description":"response","optional":false,"defaultvalue":null}],"name":"deleteServer","longname":"Bucket.server.deleteServer","scope":"route"}],"webcheck":[{"route":{"name":"/api/bucket/:id/webchecks/metrics","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"successfuly retrieved webchecks metrics","optional":false}],"name":"listMetrics","longname":"Bucket.webcheck.listMetrics","scope":"route"},{"route":{"name":"/api/bucket/:id/webchecks/regions","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"successfuly retrieved webchecks regions","optional":false}],"name":"listRegions","longname":"Bucket.webcheck.listRegions","scope":"route"},{"route":{"name":"/api/bucket/:id/webchecks/:webcheck/metrics","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":webcheck","type":"string","description":"webcheck id","optional":false}],"body":[{"name":"start","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"metrics","type":"array","description":"","optional":true,"defaultvalue":null},{"name":"end","type":"string","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"successfuly retrieved webchecks regions","optional":false}],"name":"getMetrics","longname":"Bucket.webcheck.getMetrics","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/webchecks","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"query":[{"name":"application","type":"string","description":"Application's id to filter","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"successfuly retrieved webchecks","optional":false}],"name":"list","longname":"Bucket.webcheck.list","scope":"route"},{"route":{"name":"/api/bucket/:id/webchecks/:webcheck","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":webcheck","type":"string","description":"webcheck id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"404","description":"webcheck not found","optional":false},{"type":"200","description":"successfuly retrieved webcheck","optional":false}],"name":"get","longname":"Bucket.webcheck.get","scope":"route"},{"route":{"name":"/api/bucket/:id/webchecks","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"name","type":"string","description":"Webcheck name","optional":false,"defaultvalue":null},{"name":"enabled","type":"boolean","description":"Webcheck's state","optional":true,"defaultvalue":null},{"name":"target","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"target.type","type":"string","description":"Should be `http`, `https` or `tcp`","optional":true,"defaultvalue":null},{"name":"target.port","type":"number","description":"Target's port","optional":true,"defaultvalue":null},{"name":"target.address","type":"string","description":"Target's IP/domain","optional":true,"defaultvalue":null},{"name":"target.path","type":"string","description":"HTTP Path (only for http/https)","optional":true,"defaultvalue":null},{"name":"target.is_frontend","type":"boolean","description":"Enable or disable frontend metrics (via puppeteer)","optional":true,"defaultvalue":null},{"name":"body","type":"string","description":"Body need to match this regex to succeed webcheck (only for http/https)","optional":true,"defaultvalue":null},{"name":"interval","type":"number","description":"Webcheck's interval check (ms)","optional":false,"defaultvalue":null},{"name":"timeout","type":"number","description":"Webcheck's timeout (ms)","optional":false,"defaultvalue":null},{"name":"source","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"source.region","type":"string","description":"Webcheck's worker region","optional":true,"defaultvalue":null},{"name":"retry","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"retry.max","type":"number","description":"Max webcheck's retry before mark as failed","optional":true,"defaultvalue":null},{"name":"retry.interval","type":"number","description":"Webcheck's retry interval (ms)","optional":true,"defaultvalue":null},{"name":"alerts","type":"object","description":"List of alerts (cf. Alert type)","optional":false,"defaultvalue":null},{"name":"application","type":"string","description":"Application's id","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing parameters","optional":false},{"type":"200","description":"successfuly created webcheck","optional":false}],"name":"create","longname":"Bucket.webcheck.create","scope":"route"},{"route":{"name":"/api/bucket/:id/webchecks/:webcheck","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":webcheck","type":"string","description":"webcheck id","optional":false}],"body":[{"name":"name","type":"string","description":"Webcheck name","optional":true,"defaultvalue":null},{"name":"enabled","type":"boolean","description":"Webcheck's state","optional":true,"defaultvalue":null},{"name":"target","type":"object","description":"","optional":true,"defaultvalue":null},{"name":"target.type","type":"string","description":"Should be `http`, `https` or `tcp`","optional":true,"defaultvalue":null},{"name":"target.port","type":"number","description":"Target's port","optional":true,"defaultvalue":null},{"name":"target.address","type":"string","description":"Target's IP/domain","optional":true,"defaultvalue":null},{"name":"target.path","type":"string","description":"HTTP Path (only for http/https)","optional":true,"defaultvalue":null},{"name":"target.is_frontend","type":"boolean","description":"Enable or disable frontend metrics (via puppeteer)","optional":true,"defaultvalue":null},{"name":"body","type":"string","description":"Body need to match this regex to succeed webcheck (only for http/https)","optional":true,"defaultvalue":null},{"name":"interval","type":"number","description":"Webcheck's interval check (ms)","optional":true,"defaultvalue":null},{"name":"timeout","type":"number","description":"Webcheck's timeout (ms)","optional":true,"defaultvalue":null},{"name":"source","type":"object","description":"","optional":true,"defaultvalue":null},{"name":"source.region","type":"string","description":"Webcheck's worker region","optional":true,"defaultvalue":null},{"name":"retry","type":"object","description":"","optional":true,"defaultvalue":null},{"name":"retry.max","type":"number","description":"Max webcheck's retry before mark as failed","optional":true,"defaultvalue":null},{"name":"retry.interval","type":"number","description":"Webcheck's retry interval (ms)","optional":true,"defaultvalue":null},{"name":"alerts","type":"object","description":"List of alerts (cf. Alert type)","optional":true,"defaultvalue":null},{"name":"application","type":"string","description":"Application's id","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing parameters","optional":false},{"type":"200","description":"successfuly updated webcheck","optional":false}],"name":"update","longname":"Bucket.webcheck.update","scope":"route"},{"route":{"name":"/api/bucket/:id/webchecks/:webcheck","type":"DELETE"},"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":webcheck","type":"string","description":"webcheck id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"204","description":"successfuly deleted webcheck","optional":false}],"name":"delete","longname":"Bucket.webcheck.delete","scope":"route","authentication":false}],"default":[{"route":{"name":"/api/bucket/:id/feedback","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"feedback","type":"string","description":"the feedback text","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing feedback field","optional":false},{"type":"200","description":"succesfully registered the feedback","optional":false}],"response":[{"name":"feedback","type":"string","description":"the feedback that hasn't been registered","optional":false,"defaultvalue":null}],"name":"sendFeedback","longname":"Bucket.sendFeedback","scope":"route"},{"name":"retrieveUsers","route":{"name":"/api/bucket/:id/users_authorized","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved bucket's members","optional":false}],"response":[{"name":".","type":"array","description":"a array of user containing their email, username and roles","optional":false,"defaultvalue":null}],"longname":"Bucket.retrieveUsers","scope":"route"},{"name":"currentRole","route":{"name":"/api/bucket/:id/current_role","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"200","description":"succesfully retrieved the use role","optional":false}],"response":[{"name":"role","type":"string","description":"the user role","optional":false,"defaultvalue":null}],"longname":"Bucket.currentRole","scope":"route"},{"route":{"name":"/api/bucket/:id/manage_notif","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"email","type":"string","description":"the user email","optional":false,"defaultvalue":null},{"name":"state","type":"string","description":"the notification state you want to set for that user\n (either 'email' or 'nonde)","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"404","description":"user not found","optional":false}],"response":[{"name":".","type":"array","description":"array of state for each user","optional":false,"defaultvalue":null}],"name":"setNotificationState","longname":"Bucket.setNotificationState","scope":"route"},{"name":"inviteUser","route":{"name":"/api/bucket/:id/add_user","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"email","type":"string","description":"the email of the user","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"missing/invalid parameters","optional":false},{"type":"403","description":"you cant invit more users because you hit the bucket limit","optional":false},{"type":"200","description":"succesfully invited the user (either directly or by email)","optional":false}],"response":[{"name":"invitations","type":"array","description":"the list of invitations actually active","optional":false,"defaultvalue":null}],"longname":"Bucket.inviteUser","scope":"route"},{"route":{"name":"/api/bucket/:id/invitation","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"query":[{"name":"email","type":"string","description":"the email of the invitation you want to delete","optional":true,"defaultvalue":null}],"code":[{"type":"400","description":"invalid/missing parameters","optional":false},{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully deleted the invitation","optional":false}],"response":[{"name":"invitations","type":"array","description":"the list of invitations actually active","optional":false,"defaultvalue":null}],"name":"removeInvitation","longname":"Bucket.removeInvitation","scope":"route"},{"route":{"name":"/api/bucket/:id/remove_user","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"email","type":"string","description":"the email of the user you want to remove","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"missing/invalid parameters","optional":false},{"type":"404","description":"user not found","optional":false},{"type":"403","description":"impossible to remove the owner from the bucket","optional":false},{"type":"500","description":"database error","optional":false}],"response":[{"name":".","type":"array","description":"a array of user containing their email, username and roles","optional":false,"defaultvalue":null}],"name":"removeUser","longname":"Bucket.removeUser","scope":"route"},{"route":{"name":"/api/bucket/:id/promote_user","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"email","type":"string","description":"the email of the user you want to change the role","optional":false,"defaultvalue":null},{"name":"role","type":"string","description":"the role you want to set","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"invalid/missing parameters","optional":false},{"type":"404","description":"user not found","optional":false},{"type":"403","description":"impossible to set the role of the owner","optional":false}],"response":[{"name":".","type":"array","description":"a array of user containing their email, username and roles","optional":false,"defaultvalue":null}],"name":"setUserRole","longname":"Bucket.setUserRole","scope":"route"},{"name":"retrieveAll","route":{"name":"/api/bucket/","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully fetched bucket","optional":false}],"response":[{"name":".","type":"array","description":"array of buckets","optional":false,"defaultvalue":null}],"longname":"Bucket.retrieveAll","scope":"route"},{"name":"create","route":{"name":"/api/bucket/create_classic","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"body":[{"name":"name","type":"string","description":"the name of the bucket","optional":false,"defaultvalue":null},{"name":"comment","type":"string","description":"any comments that will be written under the bucket name","optional":true,"defaultvalue":null},{"name":"app_url","type":"string","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"400","description":"missing parameters","optional":false},{"type":"403","description":"you cant create any more bucket","optional":false},{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully created a bucket","optional":false}],"response":[{"name":"bucket","type":"object","description":"the created bucket","optional":false,"defaultvalue":null}],"longname":"Bucket.create","scope":"route"},{"deprecated":true,"route":{"name":"/api/bucket/:id/start_trial","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"400","description":"can't claim trial","optional":false},{"type":"200","description":"trial launched","optional":false}],"response":[{"name":"duration","type":"string","description":"the duration of the trial","optional":false,"defaultvalue":null},{"name":"plan","type":"string","description":"the plan of the trial","optional":false,"defaultvalue":null}],"name":"claimTrial","longname":"Bucket.claimTrial","scope":"route"},{"deprecated":true,"name":"upgrade","route":{"name":"/api/bucket/:id/upgrade","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"plan","type":"string","description":"name of the plan to upgrade to","optional":false,"defaultvalue":null},{"name":"stripe_token","type":"string","description":"a card token created by stripe","optional":true,"defaultvalue":null},{"name":"coupon_id","type":"string","description":"the id of the stripe coupon","optional":true,"defaultvalue":null}],"code":[{"type":"400","description":"missing/invalid parameters","optional":false},{"type":"403","description":"need a credit card OR not allowed to subscribe to the plan","optional":false},{"type":"500","description":"stripe/database error","optional":false},{"type":"200","description":"succesfully upgraded","optional":false}],"response":[{"name":"bucket","type":"object","description":"the bucket object","optional":false,"defaultvalue":null},{"name":"subscription","type":"object","description":"the subscription object attached to the subscription","optional":false,"defaultvalue":null}],"longname":"Bucket.upgrade","scope":"route"},{"name":"retrieve","route":{"name":"/api/bucket/:id","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"200","description":"succesfully retrieved the bucket","optional":false}],"response":[{"name":".","type":"object","description":"bucket object","optional":false,"defaultvalue":null}],"longname":"Bucket.retrieve","scope":"route"},{"route":{"name":"/api/bucket/:id","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"name","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"comment","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"app_url","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"configuration","type":"string","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing parameters","optional":false}],"response":[{"name":".","type":"object","description":"bucket object","optional":false,"defaultvalue":null}],"name":"update","longname":"Bucket.update","scope":"route","async":true},{"name":"retrieveServers","route":{"name":"/api/bucket/:id/meta_servers","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved the server's metadata","optional":false}],"response":[{"name":".","type":"array","description":"servers metadata","optional":false,"defaultvalue":null}],"longname":"Bucket.retrieveServers","scope":"route"},{"route":{"name":"/api/bucket/:id","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully deleted the bucket","optional":false}],"response":[{"name":".","type":"object","description":"the deleted bucket","optional":false,"defaultvalue":null}],"name":"destroy","longname":"Bucket.destroy","scope":"route"},{"route":{"name":"/api/bucket/:id/transfer_ownership","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"new_owner","type":"string","description":"the wanted owner's email","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"Missing/invalid parameters","optional":false},{"type":"404","description":"user not found","optional":false},{"type":"403","description":"the new owner need to have a active credit card","optional":false},{"type":"200","description":"succesfully transfered the bucket, old owner is now admin","optional":false}],"response":[{"name":".","type":"object","description":"bucket object","optional":false,"defaultvalue":null}],"name":"transferOwnership","longname":"Bucket.transferOwnership","scope":"route"},{"route":{"name":"/api/bucket/:id/user_options","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"options","type":"object","description":"user options","optional":false,"defaultvalue":null}],"code":[{"type":"200","description":"succesfully update user options","optional":false},{"type":"400","description":"missing parameters","optional":false}],"response":[{"name":"bucket","type":"object","description":"","optional":false,"defaultvalue":null}],"name":"updateUserOptions","longname":"Bucket.updateUserOptions","scope":"route"}]},"dashboard":[{"route":{"name":"/api/bucket/:id/dashboard/","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"array","description":"array of servers status","optional":false,"defaultvalue":null}],"name":"retrieveAll","longname":"Dashboard.retrieveAll","scope":"route"},{"route":{"name":"/api/bucket/:id/dashboard/:dashid","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":dashid","type":"string","description":"dashboard id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"404","description":"dashboard not found","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"array","description":"array of dashboards","optional":false,"defaultvalue":null}],"name":"retrieve","longname":"Dashboard.retrieve","scope":"route"},{"route":{"name":"/api/bucket/:id/dashboard/:dashid","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":dashid","type":"string","description":"dashboard id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully deleted dashboard","optional":false},{"type":"400","description":"Invalid params","optional":false},{"type":"404","description":"dashboard not found","optional":false}],"response":[{"name":".","type":"array","description":"array of dashboards","optional":false,"defaultvalue":null}],"name":"remove","longname":"Dashboard.remove","scope":"route"},{"route":{"name":"/api/bucket/:id/dashboard/:dashId","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":dashId","type":"string","description":"dashboard id","optional":false}],"body":[{"name":"name","type":"string","description":"the name of the dashboard","optional":false,"defaultvalue":null},{"name":"children","type":"object","description":"the list of component that compose the dashboard","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"404","description":"dashboard not found","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"array","description":"array of servers status","optional":false,"defaultvalue":null}],"name":"update","longname":"Dashboard.update","scope":"route"},{"route":{"name":"/api/bucket/:id/dashboard/","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"name","type":"string","description":"the name of the dashboard","optional":false,"defaultvalue":null},{"name":"children","type":"object","description":"the list of component that compose the dashboard","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully created dashboard","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"dashboard","description":"complete dashboard object from database","optional":false,"defaultvalue":null}],"name":"create","longname":"Dashboard.create","scope":"route"}],"data":{"dependencies":[{"route":{"name":"/api/bucket/:id/data/dependencies/","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"string","description":"the application name","optional":false,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter by server name","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"missing parameters","optional":false}],"response":[{"name":".","type":"array","description":"recorded dependencies","optional":false,"defaultvalue":null}],"examples":["km.data.dependencies.retrieve(bucket._id, {\n app_name: 'my_api'\n })"],"name":"retrieve","longname":"Data.dependencies.retrieve","scope":"route"}],"events":[{"route":{"name":"/api/bucket/:id/data/events","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"event_name","type":"string","description":"the event name to retrieve","optional":false,"defaultvalue":null},{"name":"start","type":"date","description":"from which date to retrieve events","optional":true,"defaultvalue":null},{"name":"end","type":"date","description":"to which date to retrieve events","optional":true,"defaultvalue":null},{"name":"app_name","type":"string","description":"filter events by app source","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter events by server source","optional":true,"defaultvalue":null},{"name":"limit","type":"number","description":"limit the number of events to retrieve","optional":true,"defaultvalue":100},{"name":"offset","type":"number","description":"offset research by X","optional":true,"defaultvalue":0}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"invalid parameters","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of events","optional":false,"defaultvalue":null}],"name":"retrieve","longname":"Data.events.retrieve","scope":"route"},{"route":{"name":"/api/bucket/:id/data/eventsKeysByApp","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"invalid parameters","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of object representing events emitted for each application name","optional":false,"defaultvalue":null}],"name":"retrieveMetadatas","longname":"Data.events.retrieveMetadatas","scope":"route"},{"route":{"name":"/api/bucket/:id/data/events/stats","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"event_name","type":"string","description":"the event name to retrieve","optional":false,"defaultvalue":null},{"name":"app_name","type":"string","description":"filter events by app source","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter events by server source","optional":true,"defaultvalue":null},{"name":"days","type":"number","description":"limit the number of days of data","optional":true,"defaultvalue":2},{"name":"interval","type":"string","description":"interval of time between two point","optional":true,"defaultvalue":"minute"}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"invalid parameters","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of point (each point is one dimensional array, X are at 0 and Y at 1)","optional":false,"defaultvalue":null}],"name":"retrieveHistogram","longname":"Data.events.retrieveHistogram","scope":"route"},{"route":{"name":"/api/bucket/:id/data/events/delete_all","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully deleted data","optional":false}],"response":[{"name":".","type":"array","description":"array of object representing events emitted for each application name","optional":false,"defaultvalue":null}],"name":"deleteAll","longname":"Data.events.deleteAll","scope":"route"}],"exceptions":[{"route":{"name":"/api/bucket/:id/data/exceptions","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"server_name","type":"string","description":"filter exceptions by server source","optional":true,"defaultvalue":null},{"name":"app_name","type":"string","description":"filter exceptions by app source","optional":true,"defaultvalue":null},{"name":"before","type":"string","description":"filter out exceptions older than X (in minutes)","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of exceptions","optional":false,"defaultvalue":null}],"name":"retrieve","longname":"Data.exceptions.retrieve","scope":"route"},{"route":{"name":"/api/bucket/:id/data/exceptions/summary","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of object containing exceptions for each application for each server","optional":false,"defaultvalue":null}],"name":"retrieveSummary","longname":"Data.exceptions.retrieveSummary","scope":"route"},{"route":{"name":"/api/bucket/:id/data/exceptions/delete_all","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"name":"deleteAll","longname":"Data.exceptions.deleteAll","scope":"route"},{"route":{"name":"/api/bucket/:id/data/exceptions/delete","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"identifier","type":"string","description":"exception identifier","optional":true,"defaultvalue":null},{"name":"app_name","type":"string","description":"the application on which exception happened","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"the server on which exception happened","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"missing/invalid parameters","optional":false}],"response":[{"name":".","type":"array","description":"array of deleted exceptions","optional":false,"defaultvalue":null}],"name":"delete","longname":"Data.exceptions.delete","scope":"route"}],"issues":[{"route":{"name":"/api/bucket/:id/data/issues/list","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"server_name","type":"string","description":"filter exceptions by server source","optional":true,"defaultvalue":null},{"name":"app_name","type":"string","description":"filter exceptions by app source needed if initiator+source not provided","optional":true,"defaultvalue":null},{"name":"before","type":"string","description":"exclude exceptions older than 'before' minutes","optional":true,"defaultvalue":null},{"name":"initiator","type":"string","description":"filter exceptions by initiator (node/golang/browser/webcheck...) needed with source","optional":true,"defaultvalue":null},{"name":"source","type":"string","description":"filter exceptions by source (browser app id, webcheck id...)","optional":true,"defaultvalue":null},{"name":"tags","type":"array","description":"array of string to filter tags","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of exceptions","optional":false,"defaultvalue":null}],"name":"list","longname":"Data.issues.list","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/issues/occurrences/:identifier","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":identifier","type":"string","description":"issue identifier","optional":false}],"query":[{"name":"from","type":"number","description":"","optional":true,"defaultvalue":null},{"name":"search_after","type":"number","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of occurrences id","optional":false,"defaultvalue":null}],"name":"listOccurencesForIdentifier","longname":"Data.issues.listOccurencesForIdentifier","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/issues/replay/:uuid","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":uuid","type":"string","description":"replay id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":"replay","type":"string","description":"","optional":false,"defaultvalue":null}],"name":"getReplay","longname":"Data.issues.getReplay","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/issues/histogram","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"string","description":"a specific app name","optional":true,"defaultvalue":null},{"name":"start","type":"string","description":"ignore issue before this date","optional":true,"defaultvalue":null},{"name":"identifier","type":"string","description":"a specific issue identifier","optional":true,"defaultvalue":null},{"name":"interval","type":"string","description":"ignore issue before this date","optional":true,"defaultvalue":null},{"name":"end","type":"string","description":"ignore issue after this date","optional":true,"defaultvalue":null},{"name":"includeFixed","type":"boolean","description":"choose to ignore or not the fixed occurences","optional":true,"defaultvalue":false},{"name":"initiator","type":"string","description":"filter exceptions by initiator (node/golang/browser/webcheck...) needed with source","optional":true,"defaultvalue":null},{"name":"source","type":"string","description":"filter exceptions by source (browser app id, webcheck id...)","optional":true,"defaultvalue":null},{"name":"tags","type":"array","description":"array of string to filter tags","optional":true,"defaultvalue":null},{"name":"includeEmptyDocs","type":"boolean","description":"add empty docs","optional":true,"defaultvalue":false},{"name":"invertedTags","type":"boolean","description":"filter issue without tags","optional":true,"defaultvalue":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of object containing exceptions for each application for each server","optional":false,"defaultvalue":null}],"name":"retrieveHistogram","longname":"Data.issues.retrieveHistogram","scope":"route"},{"route":{"name":"/api/bucket/:id/data/issues/ocurrences","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"identifier","type":"object","description":"find occurence by using an issue identifier","optional":true,"defaultvalue":null},{"name":"occurrence_id","type":"object","description":"find ocurrence by his id","optional":true,"defaultvalue":null},{"name":"includeFixed","type":"boolean","description":"choose to ignore or not the fixed occurences","optional":true,"defaultvalue":false},{"name":"limit","type":"number","description":"limit","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of object containing ocurrences","optional":false,"defaultvalue":null}],"name":"findOccurences","longname":"Data.issues.findOccurences","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/issues/search","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"message","type":"string","description":"find occurence that match this message","optional":false,"defaultvalue":null},{"name":"includeFixed","type":"boolean","description":"choose to ignore or not the fixed occurences","optional":true,"defaultvalue":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of object containing exceptions for each application for each server","optional":false,"defaultvalue":null}],"name":"search","longname":"Data.issues.search","scope":"route"},{"route":{"name":"/api/bucket/:id/data/issues/summary/:aggregateBy","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":aggregateBy","type":"string","description":"servers, apps, initiators or sources","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"issues count aggregated","optional":false,"defaultvalue":null}],"name":"summary","longname":"Data.issues.summary","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/issues","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"query":[{"name":"app_name","type":"string","description":"an specific application to delete application","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"name":"deleteAll","longname":"Data.issues.deleteAll","scope":"route"},{"route":{"name":"/api/bucket/:id/data/issues/:identifier","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":identifier","type":"string","description":"the identifier of issue that you want to delete","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"missing/invalid parameters","optional":false}],"response":[{"name":".","type":"array","description":"array of deleted exceptions","optional":false,"defaultvalue":null}],"name":"delete","longname":"Data.issues.delete","scope":"route"}],"logs":[{"route":{"name":"/api/bucket/:id/data/logs","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"string","description":"the application name","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter by server name","optional":true,"defaultvalue":null},{"name":"before","type":"string","description":"only search log oldest than <before>","optional":true,"defaultvalue":null},{"name":"after","type":"string","description":"only search log newer than <after>","optional":true,"defaultvalue":null},{"name":"size","type":"integer","description":"line limit, default to 100","optional":true,"defaultvalue":null},{"name":"from","type":"integer","description":"offset limit","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"missing parameters","optional":false}],"response":[{"name":".","type":"array","description":"recorded dependencies","optional":false,"defaultvalue":null}],"examples":["km.data.logs.retrieve(bucket._id, {\n app_name: 'my_api'\n })"],"name":"retrieve","longname":"Data.logs.retrieve","scope":"route"},{"route":{"name":"/api/bucket/:id/data/logs/histogram","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"object","description":"a specific app name","optional":true,"defaultvalue":null},{"name":"start","type":"object","description":"ignore log before this date","optional":true,"defaultvalue":null},{"name":"interval","type":"object","description":"ignore log before this date","optional":true,"defaultvalue":null},{"name":"end","type":"object","description":"ignore log after this date","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of object containing exceptions for each application for each server","optional":false,"defaultvalue":null}],"name":"retrieveHistogram","longname":"Data.logs.retrieveHistogram","scope":"route"}],"metrics":[{"route":{"name":"/api/bucket/:id/data/metrics/aggregations","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"aggregations","type":"object","description":"array of aggregations to compute","optional":false,"defaultvalue":null},{"name":"aggregations[].name","type":"string","description":"the name of metric to compute the graph","optional":false,"defaultvalue":null},{"name":"aggregations[].types","type":"array","description":"type of aggregation (e.g. ['histogram', 'servers'])","optional":false,"defaultvalue":null},{"name":"aggregations[].start","type":"date","description":"oldest documents to aggregate on","optional":false,"defaultvalue":null},{"name":"aggregations[].end","type":"date","description":"newest documents to aggregate on","optional":true,"defaultvalue":null},{"name":"aggregations[].apps","type":"array","description":"filter source applications to aggregate on","optional":true,"defaultvalue":null},{"name":"aggregations[].interval","type":"number","description":"interval between two points","optional":true,"defaultvalue":null},{"name":"aggregations[].servers","type":"array","description":"filter source server to aggregate on","optional":true,"defaultvalue":null},{"name":"aggregations[].initiator","type":"string","description":"filter source initiator to aggregate on","optional":true,"defaultvalue":null},{"name":"aggregations[].webcheck","type":"string","description":"filter source webcheck to aggregate on","optional":true,"defaultvalue":null},{"name":"aggregations[].collector","type":"string","description":"filter source collector to aggregate on","optional":true,"defaultvalue":null},{"name":"aggregations[].tags","type":"array","description":"filter tags to aggregate on","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"aggregations","optional":false,"defaultvalue":null}],"examples":["// Example #1: Retrieve HTTP metrics of app INTERACTION, WEB-API, WORKER from all servers\n km.data.metrics.retrieveAggregations(bucket._id, {\n aggregations: [\n {\n 'start': 'now-5m',\n 'apps': ['INTERACTION', 'WEB-API', 'WORKER'],\n 'types': ['histogram', 'apps', 'servers'],\n 'name': 'HTTP'\n }\n ]\n})\n\n // Example #2: Retrieve HTTP metrics of ALL apps from all servers\n km.data.metrics.retrieveAggregations(bucket._id, {\n aggregations: [\n {\n 'start': 'now-1d',\n 'types': ['histogram', 'apps', 'servers'],\n 'name': 'HTTP'\n }\n ]\n})"],"name":"retrieveAggregations","longname":"Data.metrics.retrieveAggregations","scope":"route"},{"route":{"name":"/api/bucket/:id/data/metrics/histogram","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"string","description":"filter probes by app source","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter probes by server source","optional":true,"defaultvalue":null},{"name":"interval","type":"string","description":"interval of time between two point","optional":true,"defaultvalue":"minute"},{"name":"before","type":"string","description":"filter out probes that are after X minute","optional":true,"defaultvalue":60}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":"server_name","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"server_name.app_name","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"server_name.app_name.metrics","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"server_name.app_name.metrics.agg_type","type":"string","description":"the type of aggregation for this probe","optional":false,"defaultvalue":null},{"name":"server_name.app_name.metrics_name.timestamps_and_stats","type":"array","description":"array of point","optional":false,"defaultvalue":null}],"name":"retrieveHistogram","longname":"Data.metrics.retrieveHistogram","scope":"route"},{"route":{"name":"/api/bucket/:id/data/metrics/histogramPrecise","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"probe","type":"string","description":"probe name","optional":false,"defaultvalue":null},{"name":"app","type":"string","description":"filter probes by app source","optional":false,"defaultvalue":null},{"name":"server","type":"string","description":"filter probes by server source","optional":false,"defaultvalue":null},{"name":"after","type":"string","description":"interval of time between two point (now-5d, now-5m...)","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":"Array","type":"array","description":"of points","optional":false,"defaultvalue":null}],"name":"retrieveHistogramPrecise","longname":"Data.metrics.retrieveHistogramPrecise","scope":"route"},{"route":{"name":"/api/bucket/:id/data/metrics/list","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"servers","type":"object","description":"filter metrics by app name","optional":true,"defaultvalue":null},{"name":"apps","type":"object","description":"filter metrics by server name","optional":true,"defaultvalue":null},{"name":"initiator","type":"string","description":"filter metrics by a specific initiator","optional":true,"defaultvalue":null},{"name":"source","type":"string","description":"filter metrics by a specific source","optional":true,"defaultvalue":null},{"name":"collector","type":"string","description":"filter metrics by a specific collector","optional":true,"defaultvalue":null},{"name":"webcheck","type":"string","description":"filter metrics by a specific webcheck","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"name":"retrieveList","longname":"Data.metrics.retrieveList","scope":"route"},{"route":{"name":"/api/bucket/:id/data/metrics","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"string","description":"filter metrics by app source","optional":false,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter metrics by server source","optional":true,"defaultvalue":null},{"name":"before","type":"string","description":"filter out metrics that are after X minute","optional":true,"defaultvalue":720}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"name":"retrieveMetadatas","longname":"Data.metrics.retrieveMetadatas","scope":"route"}],"notifications":[{"route":{"name":"/api/bucket/:id/data/notifications","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"type","type":"string","description":"Type of notification","optional":true,"defaultvalue":null},{"name":"before","type":"string","description":"we search logs before this date (lower than)","optional":true,"defaultvalue":null},{"name":"after","type":"string","description":"we search logs after this date (greater than)","optional":true,"defaultvalue":null},{"name":"size","type":"number","description":"","optional":true,"defaultvalue":null},{"name":"from","type":"number","description":"","optional":true,"defaultvalue":null},{"name":"type","type":"string","description":"type of notification","optional":true,"defaultvalue":null},{"name":"providers","type":"array","description":"find notifications with this providers","optional":true,"defaultvalue":null},{"name":"contacts","type":"array","description":"find notifications with this contact","optional":true,"defaultvalue":null},{"name":"size","type":"integer","description":"line limit, default to 20","optional":true,"defaultvalue":null},{"name":"from","type":"integer","description":"offset limit","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"tags":[{"originalTitle":"reponse","title":"reponse","text":"{Array} . array of traces","value":"{Array} . array of traces","optional":false,"type":null}],"name":"list","longname":"Data.notifications.list","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/notifications/:notification","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":notification","type":"string","description":"notification id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"tags":[{"originalTitle":"reponse","title":"reponse","text":"{Object} . notification","value":"{Object} . notification","optional":false,"type":null}],"name":"retrieve","longname":"Data.notifications.retrieve","scope":"route","async":true}],"outliers":[{"route":{"name":"/api/bucket/:id/data/outliers/","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"string","description":"the application name","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter by server name","optional":true,"defaultvalue":null},{"name":"start","type":"string","description":"only search outlier newer than <start>","optional":true,"defaultvalue":null},{"name":"end","type":"string","description":"only search outlier older than <end>","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"missing parameters","optional":false}],"response":[{"name":".","type":"array","description":"recorded dependencies","optional":false,"defaultvalue":null}],"examples":["km.data.outliers.retrieve(bucket._id, {\n app_name: 'my_api'\n })"],"name":"retrieve","longname":"Data.outliers.retrieve","scope":"route"}],"processes":[{"route":{"name":"/api/bucket/:id/data/processEvents","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"string","description":"filter events by app source","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter events by server source","optional":true,"defaultvalue":null},{"name":"before","type":"string","description":"filter out events that are after X minute","optional":true,"defaultvalue":60}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of process events","optional":false,"defaultvalue":null}],"name":"retrieveEvents","longname":"Data.processes.retrieveEvents","scope":"route"},{"route":{"name":"/api/bucket/:id/data/processEvents/deployments","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"string","description":"filter events by app source","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter events by server source","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of deployments","optional":false,"defaultvalue":null}],"name":"retrieveDeployments","longname":"Data.processes.retrieveDeployments","scope":"route"}],"profiling":[{"route":{"name":"/api/bucket/:id/data/profilings/:filename","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":filename","type":"string","description":"filename","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"invalid parameters","optional":false}],"response":[{"name":".","type":"object","description":"return profile data","optional":false,"defaultvalue":null}],"name":"retrieve","longname":"Data.profiling.retrieve","scope":"route"},{"route":{"name":"/api/bucket/:id/data/profilings/:filename/download","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":filename","type":"string","description":"filename","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"invalid parameters","optional":false}],"response":[{"name":".","type":"file","description":"return a file","optional":false,"defaultvalue":null}],"name":"download","longname":"Data.profiling.download","scope":"route"},{"route":{"name":"/api/bucket/:id/data/profilings","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"apps","type":"object","description":"","optional":true,"defaultvalue":null},{"name":"servers","type":"object","description":"","optional":true,"defaultvalue":null},{"name":"from","type":"object","description":"","optional":true,"defaultvalue":null},{"name":"size","type":"object","description":"","optional":true,"defaultvalue":null},{"name":"type","type":"object","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of object containing profilings","optional":false,"defaultvalue":null}],"name":"list","longname":"Data.profiling.list","scope":"route"},{"route":{"name":"/api/bucket/:id/data/profilings/:filename","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":filename","type":"string","description":"filename","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"invalid parameters","optional":false}],"response":[{"name":".","type":"file","description":"return a file","optional":false,"defaultvalue":null}],"name":"delete","longname":"Data.profiling.delete","scope":"route"}],"status":[{"route":{"name":"/api/bucket/:id/data/status","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"tags":[{"originalTitle":"reponse","title":"reponse","text":"{Array} . array of servers status","value":"{Array} . array of servers status","optional":false,"type":null}],"name":"retrieve","longname":"Data.status.retrieve","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/status/blacklisted","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"tags":[{"originalTitle":"reponse","title":"reponse","text":"{Array} . array of servers status","value":"{Array} . array of servers status","optional":false,"type":null}],"name":"retrieveBlacklisted","longname":"Data.status.retrieveBlacklisted","scope":"route","async":true}],"traces":[{"route":{"name":"/api/bucket/:id/data/traces","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"includeSpans","type":"boolean","description":"","optional":true,"defaultvalue":true},{"name":"serviceName","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"limit","type":"string","description":"default: 10, max: 100","optional":true,"defaultvalue":null},{"name":"kind","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"minDuration","type":"number","description":"","optional":true,"defaultvalue":null},{"name":"start","type":"string","description":"date","optional":true,"defaultvalue":null},{"name":"end","type":"string","description":"date","optional":true,"defaultvalue":null},{"name":"tags","type":"array","description":"Query string array like [error=500, error, ...]","optional":true,"defaultvalue":null},{"name":"orderBy","type":"string","description":"Default: newest, enum: oldest, newest, shortest, longest","optional":true,"defaultvalue":null},{"name":"spanName","type":"string","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"tags":[{"originalTitle":"reponse","title":"reponse","text":"{Array} . array of traces","value":"{Array} . array of traces","optional":false,"type":null}],"name":"list","longname":"Data.traces.list","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/traces/:trace","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false},{"name":":trace","type":"string","description":"trace id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"tags":[{"originalTitle":"reponse","title":"reponse","text":"{Object} . trace","value":"{Object} . trace","optional":false,"type":null}],"name":"retrieve","longname":"Data.traces.retrieve","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/traces/services","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":"services,","type":"object","description":"spans names","optional":false,"defaultvalue":null}],"name":"getServices","longname":"Data.traces.getServices","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/traces/tags","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":"tags","type":"array","description":"","optional":false,"defaultvalue":null}],"name":"getTags","longname":"Data.traces.getTags","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/traces/histogram/tag","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"tag","type":"string","description":"","optional":false,"defaultvalue":null},{"name":"start","type":"string","description":"date","optional":true,"defaultvalue":null},{"name":"end","type":"string","description":"date","optional":true,"defaultvalue":null},{"name":"serviceName","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"spanName","type":"string","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":"aggregation","type":"array","description":"","optional":false,"defaultvalue":null}],"name":"getHistogramByTag","longname":"Data.traces.getHistogramByTag","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/traces/aggregation/tag","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"tag","type":"string","description":"","optional":false,"defaultvalue":null},{"name":"start","type":"string","description":"date","optional":true,"defaultvalue":null},{"name":"end","type":"string","description":"date","optional":true,"defaultvalue":null},{"name":"serviceName","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"spanName","type":"string","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":"aggregation","type":"array","description":"","optional":false,"defaultvalue":null}],"name":"getTagsValue","longname":"Data.traces.getTagsValue","scope":"route","async":true},{"route":{"name":"/api/bucket/:id/data/traces/aggregation/duration","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"start","type":"string","description":"date","optional":true,"defaultvalue":null},{"name":"end","type":"string","description":"date","optional":true,"defaultvalue":null},{"name":"serviceName","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"spanName","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"tags","type":"array","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":"aggregation","type":"array","description":"","optional":false,"defaultvalue":null}],"name":"getDurationAvg","longname":"Data.traces.getDurationAvg","scope":"route","async":true}],"transactions":[{"route":{"name":"/api/bucket/:id/data/transactions/v2/histogram","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"string","description":"filter transactions by app source","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter transactions by server source","optional":true,"defaultvalue":null},{"name":"interval","type":"string","description":"interval of time between two point","optional":true,"defaultvalue":"minute"},{"name":"before","type":"string","description":"filter out transactions that are after X minute","optional":true,"defaultvalue":60}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":".","type":"array","description":"array of times series containing points","optional":false,"defaultvalue":null}],"name":"retrieveHistogram","longname":"Data.transactions.retrieveHistogram","scope":"route"},{"route":{"name":"/api/bucket/:id/data/transactions/v2/summary","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"body":[{"name":"app_name","type":"string","description":"filter transactions by app source","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter transactions by server source","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":"server_name","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"server_name.app_name","type":"object","description":"transaction object","optional":false,"defaultvalue":null}],"name":"retrieveSummary","longname":"Data.transactions.retrieveSummary","scope":"route"},{"route":{"name":"/api/bucket/:id/data/transactions/v2/delete","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"bucket id","optional":false}],"query":[{"name":"app_name","type":"string","description":"filter transactions by app source","optional":true,"defaultvalue":null},{"name":"server_name","type":"string","description":"filter transactions by server source","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false}],"response":[{"name":"server_name","type":"object","description":"","optional":false,"defaultvalue":null},{"name":"server_name.app_name","type":"object","description":"transaction object","optional":false,"defaultvalue":null}],"name":"delete","longname":"Data.transactions.delete","scope":"route"}]},"misc":[{"route":{"name":"/api/misc/changelog","type":"GET"},"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":"changelog","type":"array","description":"articles","optional":false,"defaultvalue":null}],"name":"listChangelogArticles","longname":"Misc.listChangelogArticles","scope":"route","params":[],"authentication":false},{"route":{"name":"/api/misc/release/pm2","type":"GET"},"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":"pm2_version","type":"string","description":"latest version","optional":false,"defaultvalue":null}],"name":"retrievePM2Version","longname":"Misc.retrievePM2Version","scope":"route","params":[],"authentication":false},{"route":{"name":"/api/misc/release/nodejs/:version","type":"GET"},"params":[{"name":":version","type":"string","description":"semver version range","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"array","description":"array of releases matching the range requested","optional":false,"defaultvalue":null}],"name":"retrieveNodeRelease","longname":"Misc.retrieveNodeRelease","scope":"route","authentication":false},{"route":{"name":"/api/misc/plans","type":"GET"},"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"succesfully retrieved data","optional":false},{"type":"400","description":"Invalid params","optional":false}],"response":[{"name":".","type":"object","description":"list of plans keyed by plan name","optional":false,"defaultvalue":null}],"name":"retrievePlans","longname":"Misc.retrievePlans","scope":"route","params":[],"authentication":false},{"route":{"name":"/api/misc/stripe/retrieveCoupon","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"body":[{"name":"coupon","type":"string","description":"the coupon name","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"200","description":"succesfully retrieved the metadata","optional":false}],"response":[{"name":"coupon","type":"object","description":"the coupon object","optional":false,"defaultvalue":null}],"name":"retrieveCoupon","longname":"Misc.retrieveCoupon","scope":"route","params":[]},{"route":{"name":"/api/misc/stripe/retrieveCompany","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"body":[{"name":"vat_id","type":"string","description":"the vat id of the company","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"200","description":"succesfully retrieved the metadata","optional":false}],"response":[{"name":".","type":"object","description":"metadata about company","optional":false,"defaultvalue":null}],"name":"retrieveCompany","longname":"Misc.retrieveCompany","scope":"route","params":[]},{"route":{"name":"/api/misc/stripe/retrieveVat","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"body":[{"name":"country","type":"string","description":"country code of the user","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"stripe error","optional":false},{"type":"200","description":"succesfully retrieved the metadata","optional":false}],"response":[{"name":"coupon","type":"object","description":"the coupon object","optional":false,"defaultvalue":null}],"name":"retrieveVAT","longname":"Misc.retrieveVAT","scope":"route","params":[]}],"node":[{"route":{"name":"/api/node/default","type":"GET"},"response":[{"name":"node","type":"object","description":"Return node object","optional":false,"defaultvalue":null}],"name":"getDefaultNode","longname":"Node.getDefaultNode","scope":"route","params":[],"authentication":false}],"orchestration":[{"route":{"name":"/api/bucket/:id/balance","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"balancing error","optional":false},{"type":"403","description":"already on new node or not premium","optional":false},{"type":"200","description":"succesfully balanced the bucket","optional":false}],"response":[{"name":"migration","type":"object","description":"is equal true if succesfull","optional":false,"defaultvalue":null}],"name":"selfSend","longname":"Orchestration.selfSend","scope":"route","params":[]}],"tokens":[{"route":{"name":"/api/users/token/","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"200","description":"successfully retrieved","optional":false}],"response":[{"name":".","type":"object","description":"array of tokens","optional":false,"defaultvalue":null}],"name":"retrieve","longname":"Tokens.retrieve","scope":"route","params":[]},{"route":{"name":"/api/users/token/:id","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"params":[{"name":":id","type":"string","description":"token id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"404","description":"token not found","optional":false},{"type":"200","description":"refresh token has been deleted and all access token that have been created with it","optional":false}],"response":[{"name":".","type":"object","description":"array of tokens","optional":false,"defaultvalue":null}],"name":"remove","longname":"Tokens.remove","scope":"route"},{"route":{"name":"/api/users/token/","type":"PUT"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"body":[{"name":"scope","type":"object","description":"a valid oauth scope","optional":false,"defaultvalue":null}],"code":[{"type":"409","description":"the otp is already enabled for the user, you can only delete it","optional":false},{"type":"200","description":"the otp can be registered for the account, return the full response","optional":false}],"response":[{"name":".","type":"object","description":"generated token","optional":false,"defaultvalue":null}],"name":"create","longname":"Tokens.create","scope":"route","params":[]}],"user":{"otp":[{"route":{"name":"/api/users/otp","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"409","description":"the otp is already enabled for the user, you can only delete it","optional":false},{"type":"200","description":"the otp can be registered for the account, return the full response","optional":false}],"response":[{"name":"user","type":"object","description":"user model","optional":false,"defaultvalue":null},{"name":"key","type":"string","description":"otp secret key","optional":false,"defaultvalue":null},{"name":"qrImage","type":"string","description":"url to the QrCode","optional":false,"defaultvalue":null}],"name":"retrieve","longname":"User.otp.retrieve","scope":"route","params":[]},{"route":{"name":"/api/users/otp","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"body":[{"name":"otpKey","type":"string","description":"secret key used to generate OTP code","optional":false,"defaultvalue":null},{"name":"otpToken","type":"string","description":"a currently valid OTP code generated with the otpKey","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"missing parameters","optional":false},{"type":"403","description":"the code asked to add the OTP from user account is invalid","optional":false},{"type":"500","description":"error from database","optional":false},{"type":"200","description":"the otp has been registered for the user","optional":false}],"name":"enable","longname":"User.otp.enable","scope":"route","params":[]},{"route":{"name":"/api/users/otp","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"query":[{"name":"otpToken","type":"string","description":"a currently valid OTP code","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"missing parameters","optional":false},{"type":"403","description":"the code asked to remove the OTP from user account is invalid","optional":false},{"type":"500","description":"error from database","optional":false},{"type":"200","description":"the otp has been deleted for the user","optional":false}],"name":"disable","longname":"User.otp.disable","scope":"route","params":[]}],"providers":[{"route":{"name":"/api/users/integrations","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"200","description":"succesfully retrieved providers","optional":false}],"response":[{"name":".","type":"array","description":"array of providers for user account","optional":false,"defaultvalue":null}],"name":"retrieve","longname":"User.providers.retrieve","scope":"route","params":[]},{"route":{"name":"/api/users/integrations","type":"POST"},"authentication":true,"body":[{"name":"name","type":"string","description":"the provider name","optional":false,"defaultvalue":null}],"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"invalid parameters","optional":false},{"type":"403","description":"the user already have this provider","optional":false},{"type":"200","description":"succesfully added the provider","optional":false}],"name":"add","longname":"User.providers.add","scope":"route","params":[]},{"route":{"name":"/api/users/integrations/:name","type":"DELETE"},"authentication":true,"params":[{"name":":name","type":"string","description":"the provider name","optional":false}],"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"400","description":"invalid parameters or provider isn't implemented","optional":false},{"type":"403","description":"the provider isn't enabled","optional":false},{"type":"200","description":"succesfully removed the provider","optional":false}],"name":"remove","longname":"User.providers.remove","scope":"route"}],"default":[{"name":"retrieve","route":{"name":"/api/users/isLogged","type":"GET"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"200","description":"the user has been retrieved","optional":false}],"response":[{"name":"user","type":"object","description":"user model","optional":false,"defaultvalue":null}],"longname":"User.retrieve","scope":"route"},{"route":{"name":"/api/users/show/:id","type":"GET"},"params":[{"name":":id","type":"string","description":"user id","optional":false}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"invalid parameters (no id provided)","optional":false},{"type":"404","description":"no user account where found","optional":false},{"type":"200","description":"the mail has been sent to the provided email","optional":false}],"response":[{"name":"String","type":"","description":"email user email","optional":false,"defaultvalue":null},{"name":"String","type":"","description":"username user pseudo","optional":false,"defaultvalue":null}],"name":"show","longname":"User.show","scope":"route","authentication":false},{"route":{"name":"/api/users/update","type":"POST"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"body":[{"name":"username","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"email","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"old_password","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"new_password","type":"string","description":"","optional":true,"defaultvalue":null},{"name":"info","type":"object","description":"","optional":true,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"400","description":"missing parameters, no data to update","optional":false},{"type":"403","description":"when updating the password, it need a new one","optional":false},{"type":"406","description":"when updating the password, the old one is false","optional":false},{"type":"409","description":"when updating email or username\n another user already have one of those two","optional":false},{"type":"200","description":"succesfully updated the card","optional":false}],"response":[{"name":".","type":"object","description":"user object","optional":false,"defaultvalue":null}],"name":"update","longname":"User.update","scope":"route","params":[]},{"route":{"name":"/api/users/delete","type":"DELETE"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"database error","optional":false},{"type":"403","description":"permission denied (hold buckets)","optional":false},{"type":"200","description":"succesfully deleted the user","optional":false}],"response":[{"name":".","type":"object","description":"user object","optional":false,"defaultvalue":null}],"name":"delete","longname":"User.delete","scope":"route","params":[]}]},"auth":[{"name":"retrieveToken","route":{"name":"/api/oauth/token","type":"POST"},"service":{"name":"OAUTH"},"body":[{"name":"client_id","type":"string","description":"the public id of your oauth application","optional":false,"defaultvalue":null},{"name":"refresh_token","type":"string","description":"refresh token you retrieved via authorize endpoint","optional":false,"defaultvalue":null},{"name":"grant_type","type":"string","description":"","optional":false,"defaultvalue":"refresh_token"}],"code":[{"type":"400","description":"invalid parameters (missing or not correct)","optional":false}],"response":[{"name":"access_token","type":"string","description":"a fresh access_token","optional":false,"defaultvalue":null},{"name":"refresh_token","type":"string","description":"the refresh token you used","optional":false,"defaultvalue":null},{"name":"expire_at","type":"string","description":"UTC date at which the token will be considered\n as invalid","optional":false,"defaultvalue":null},{"name":"token_type","type":"string","description":"the type of token to use, for now its always Bearer","optional":false,"defaultvalue":null}],"longname":"Auth.retrieveToken","scope":"route","authentication":false},{"name":"requestNewPassword","route":{"name":"/api/oauth/reset_password","type":"POST"},"service":{"name":"OAUTH"},"body":[{"name":"email","type":"string","description":"email of the account that want a password reset","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"the database failed to register the token to reset the mail","optional":false},{"type":"400","description":"missing parameters","optional":false},{"type":"404","description":"no user account where found with the provided email","optional":false},{"type":"200","description":"the mail has been sent to the provided email","optional":false}],"longname":"Auth.requestNewPassword","scope":"route","authentication":false},{"name":"sendEmailLink","route":{"name":"/api/oauth/send_email_link","type":"POST"},"service":{"name":"OAUTH"},"code":[{"type":"500","description":"the database failed to register the token to reset the mail","optional":false},{"type":"401","description":"need to authenticated","optional":false},{"type":"200","description":"the mail has been sent to the provided email","optional":false}],"longname":"Auth.sendEmailLink","scope":"route","authentication":false},{"name":"validEmail","route":{"name":"/api/oauth/valid_email/:token","type":"GET"},"params":[{"description":"the token to validate the account","name":":token","optional":false,"type":null}],"service":{"name":"OAUTH"},"code":[{"type":"500","description":"the database failed to valid email","optional":false},{"type":"404","description":"need to authenticated","optional":false},{"type":"301","description":"the email has been valided","optional":false}],"longname":"Auth.validEmail","scope":"route","authentication":false},{"route":{"name":"/api/oauth/register","type":"GET"},"service":{"name":"OAUTH"},"body":[{"name":"username","type":"string","description":"","optional":false,"defaultvalue":null},{"name":"email","type":"string","description":"","optional":false,"defaultvalue":null},{"name":"password","type":"string","description":"","optional":false,"defaultvalue":null},{"name":"role","type":"string","description":"job title in user company","optional":true,"defaultvalue":null},{"name":"company","type":"string","description":"company name","optional":true,"defaultvalue":null},{"name":"accept_terms","type":"integer","description":"","optional":false,"defaultvalue":null}],"code":[{"type":"500","description":"either the registeration of new user is disabled or\nthe database failed to register the user","optional":false},{"type":"409","description":"the user field are already used by another user","optional":false},{"type":"200","description":"the user has been created","optional":false}],"response":[{"name":"user","type":"object","description":"user model","optional":false,"defaultvalue":null},{"name":"access_token","type":"object","description":"access token issued for the user","optional":false,"defaultvalue":null},{"name":"refreshToken","type":"object","description":"refresh token issued for the user","optional":false,"defaultvalue":null}],"name":"register","longname":"Auth.register","scope":"route","authentication":false},{"route":{"name":"/api/oauth/revoke","type":"POST"},"service":{"name":"OAUTH"},"authentication":true,"header":[{"name":"Authorization","type":"string","description":"bearer access token issued for the user","optional":false,"defaultvalue":null}],"code":[{"type":"404","description":"token not found","optional":false},{"type":"500","description":"database error","optional":false},{"type":"200","description":"the token has been succesfully deleted,\n if there was access token generated with this token, they\n have been deleted too","optional":false}],"name":"revoke","longname":"Auth.revoke","scope":"route"}]}
  8954. },{}],39:[function(require,module,exports){
  8955. /* global URLSearchParams, URL, localStorage */
  8956. 'use strict';
  8957. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  8958. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8959. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  8960. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  8961. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  8962. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  8963. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  8964. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  8965. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  8966. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
  8967. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  8968. var AuthStrategy = require('./strategy');
  8969. module.exports = /*#__PURE__*/function (_AuthStrategy) {
  8970. _inherits(BrowserFlow, _AuthStrategy);
  8971. var _super = _createSuper(BrowserFlow);
  8972. function BrowserFlow() {
  8973. _classCallCheck(this, BrowserFlow);
  8974. return _super.apply(this, arguments);
  8975. }
  8976. _createClass(BrowserFlow, [{
  8977. key: "removeUrlToken",
  8978. value: function removeUrlToken(refreshToken) {
  8979. var url = window.location.href;
  8980. var params = "?access_token=".concat(refreshToken, "&token_type=refresh_token");
  8981. var newUrl = url.replace(params, '');
  8982. window.history.pushState('', '', newUrl);
  8983. }
  8984. }, {
  8985. key: "retrieveTokens",
  8986. value: function retrieveTokens(km, cb) {
  8987. var _this = this;
  8988. var verifyToken = function verifyToken(refresh) {
  8989. return km.auth.retrieveToken({
  8990. client_id: _this.client_id,
  8991. refresh_token: refresh
  8992. });
  8993. }; // parse the url since it can contain tokens
  8994. var url = new URL(window.location);
  8995. this.response_mode = this.response_mode === 'query' ? 'search' : this.response_mode;
  8996. var params = new URLSearchParams(url[this.response_mode]);
  8997. if (params.get('access_token') !== null) {
  8998. // verify that the access_token in parameters is valid
  8999. verifyToken(params.get('access_token')).then(function (res) {
  9000. _this.removeUrlToken(res.data.refresh_token); // Save refreshToken in localstorage
  9001. localStorage.setItem('km_refresh_token', params.get('access_token'));
  9002. var tokens = res.data;
  9003. return cb(null, tokens);
  9004. })["catch"](cb);
  9005. } else if (typeof localStorage !== 'undefined' && localStorage.getItem('km_refresh_token') !== null) {
  9006. // maybe in the local storage ?
  9007. verifyToken(localStorage.getItem('km_refresh_token')).then(function (res) {
  9008. _this.removeUrlToken(res.data.refresh_token);
  9009. var tokens = res.data;
  9010. return cb(null, tokens);
  9011. })["catch"](cb);
  9012. } else {
  9013. // otherwise we need to get a refresh token
  9014. window.location = "".concat(this.oauth_endpoint).concat(this.oauth_query, "&redirect_uri=").concat(window.location);
  9015. }
  9016. }
  9017. }, {
  9018. key: "deleteTokens",
  9019. value: function deleteTokens(km) {
  9020. var _this2 = this;
  9021. return new Promise(function (resolve, reject) {
  9022. // revoke the refreshToken
  9023. km.auth.revoke().then(function (res) {
  9024. return console.log('Token successfuly revoked!');
  9025. })["catch"](function (err) {
  9026. return console.error("Error when trying to revoke token: ".concat(err.message));
  9027. }); // We need to remove from storage and redirect user in every case (cf. https://github.com/keymetrics/pm2-io-js-api/issues/49)
  9028. // remove the token from the localStorage
  9029. localStorage.removeItem('km_refresh_token');
  9030. setTimeout(function (_) {
  9031. // redirect after few miliseconds so any user code will run
  9032. window.location = "".concat(_this2.oauth_endpoint).concat(_this2.oauth_query);
  9033. }, 500);
  9034. return resolve();
  9035. });
  9036. }
  9037. }]);
  9038. return BrowserFlow;
  9039. }(AuthStrategy);
  9040. },{"./strategy":41}],40:[function(require,module,exports){
  9041. 'use strict';
  9042. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  9043. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9044. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  9045. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  9046. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  9047. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  9048. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  9049. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  9050. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  9051. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
  9052. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  9053. var AuthStrategy = require('./strategy');
  9054. module.exports = /*#__PURE__*/function (_AuthStrategy) {
  9055. _inherits(StandaloneFlow, _AuthStrategy);
  9056. var _super = _createSuper(StandaloneFlow);
  9057. function StandaloneFlow() {
  9058. _classCallCheck(this, StandaloneFlow);
  9059. return _super.apply(this, arguments);
  9060. }
  9061. _createClass(StandaloneFlow, [{
  9062. key: "retrieveTokens",
  9063. value: function retrieveTokens(km, cb) {
  9064. if (this._opts.refresh_token && this._opts.access_token) {
  9065. // if both access and refresh tokens are provided, we are good
  9066. return cb(null, {
  9067. access_token: this._opts.access_token,
  9068. refresh_token: this._opts.refresh_token
  9069. });
  9070. } else if (this._opts.refresh_token && this._opts.client_id) {
  9071. // we can also make a request to get an access token
  9072. km.auth.retrieveToken({
  9073. client_id: this._opts.client_id,
  9074. refresh_token: this._opts.refresh_token
  9075. }).then(function (res) {
  9076. var tokens = res.data;
  9077. return cb(null, tokens);
  9078. })["catch"](cb);
  9079. } else {
  9080. // otherwise the flow isn't used correctly
  9081. throw new Error("If you want to use the standalone flow you need to provide either \n a refresh and access token OR a refresh token and a client id");
  9082. }
  9083. }
  9084. }, {
  9085. key: "deleteTokens",
  9086. value: function deleteTokens(km) {
  9087. return km.auth.revoke;
  9088. }
  9089. }]);
  9090. return StandaloneFlow;
  9091. }(AuthStrategy);
  9092. },{"./strategy":41}],41:[function(require,module,exports){
  9093. 'use strict';
  9094. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9095. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  9096. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  9097. var constants = require('../../constants.js');
  9098. var AuthStrategy = /*#__PURE__*/function () {
  9099. function AuthStrategy(opts) {
  9100. _classCallCheck(this, AuthStrategy);
  9101. this._opts = opts;
  9102. this.client_id = opts.client_id || opts.OAUTH_CLIENT_ID;
  9103. if (!this.client_id) {
  9104. throw new Error('You must always provide a application id for any of the strategies');
  9105. }
  9106. this.scope = opts.scope || 'all';
  9107. this.response_mode = opts.reponse_mode || 'query';
  9108. var optsOauthEndpoint = null;
  9109. if (opts && opts.services) {
  9110. optsOauthEndpoint = opts.services.OAUTH || opts.services.API;
  9111. }
  9112. var oauthEndpoint = constants.services.OAUTH || constants.services.API;
  9113. this.oauth_endpoint = "".concat(optsOauthEndpoint || oauthEndpoint);
  9114. if (this.oauth_endpoint[this.oauth_endpoint.length - 1] === '/' && constants.OAUTH_AUTHORIZE_ENDPOINT[0] === '/') {
  9115. this.oauth_endpoint = this.oauth_endpoint.substr(0, this.oauth_endpoint.length - 1);
  9116. }
  9117. this.oauth_endpoint += constants.OAUTH_AUTHORIZE_ENDPOINT;
  9118. this.oauth_query = "?client_id=".concat(opts.client_id, "&response_mode=").concat(this.response_mode) + "&response_type=token&scope=".concat(this.scope);
  9119. }
  9120. _createClass(AuthStrategy, [{
  9121. key: "retrieveTokens",
  9122. value: function retrieveTokens() {
  9123. throw new Error('You need to implement a retrieveTokens function inside your strategy');
  9124. }
  9125. }, {
  9126. key: "deleteTokens",
  9127. value: function deleteTokens() {
  9128. throw new Error('You need to implement a deleteTokens function inside your strategy');
  9129. }
  9130. }], [{
  9131. key: "implementations",
  9132. value: function implementations(name) {
  9133. var flows = {
  9134. 'embed': {
  9135. nodule: require('./embed_strategy'),
  9136. condition: 'node'
  9137. },
  9138. 'browser': {
  9139. nodule: require('./browser_strategy'),
  9140. condition: 'browser'
  9141. },
  9142. 'standalone': {
  9143. nodule: require('./standalone_strategy'),
  9144. condition: null
  9145. }
  9146. };
  9147. return name ? flows[name] : null;
  9148. }
  9149. }]);
  9150. return AuthStrategy;
  9151. }();
  9152. module.exports = AuthStrategy;
  9153. },{"../../constants.js":1,"./browser_strategy":39,"./embed_strategy":30,"./standalone_strategy":40}],42:[function(require,module,exports){
  9154. 'use strict';
  9155. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9156. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  9157. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  9158. var RequestValidator = require('./utils/validator');
  9159. var debug = require('debug')('kmjs:endpoint');
  9160. module.exports = /*#__PURE__*/function () {
  9161. function Endpoint(opts) {
  9162. _classCallCheck(this, Endpoint);
  9163. Object.assign(this, opts);
  9164. }
  9165. _createClass(Endpoint, [{
  9166. key: "build",
  9167. value: function build(http) {
  9168. var endpoint = this;
  9169. return function () {
  9170. var _arguments = arguments;
  9171. var callsite = new Error().stack.split('\n')[2];
  9172. if (callsite && callsite.length > 0) {
  9173. debug("Call to '".concat(endpoint.route.name, "' from ").concat(callsite.replace(' at ', '')));
  9174. }
  9175. return new Promise(function (resolve, reject) {
  9176. RequestValidator.extract(endpoint, Array.prototype.slice.call(_arguments)).then(function (opts) {
  9177. // Different service than default, setup base url in url
  9178. if (endpoint.service && endpoint.service.baseURL) {
  9179. var base = endpoint.service.baseURL;
  9180. base = base[base.length - 1] === '/' ? base.substr(0, base.length - 1) : base;
  9181. opts.url = base + opts.url;
  9182. }
  9183. http.request(opts).then(resolve, reject);
  9184. })["catch"](reject);
  9185. });
  9186. };
  9187. }
  9188. }]);
  9189. return Endpoint;
  9190. }();
  9191. },{"./utils/validator":46,"debug":31}],43:[function(require,module,exports){
  9192. 'use strict';
  9193. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9194. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  9195. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  9196. var Namespace = require('./namespace');
  9197. var constants = require('../constants');
  9198. var NetworkWrapper = require('./network');
  9199. var logger = require('debug')('kmjs');
  9200. var Keymetrics = /*#__PURE__*/function () {
  9201. /**
  9202. * @constructor
  9203. * Keymetrics
  9204. *
  9205. * @param {Object} [opts]
  9206. * @param {String} [opts.OAUTH_CLIENT_ID] the oauth client ID used to authenticate to KM
  9207. * @param {Object} [opts.services] base url for differents services
  9208. * @param {String} [opts.mappings] api mappings
  9209. */
  9210. function Keymetrics(opts) {
  9211. _classCallCheck(this, Keymetrics);
  9212. logger('init keymetrics instance');
  9213. this.opts = Object.assign(constants, opts);
  9214. logger('init network client (http/ws)');
  9215. this._network = new NetworkWrapper(this, this.opts);
  9216. var mapping = opts && opts.mappings ? opts.mappings : require('./api_mappings.json');
  9217. logger("Using mappings provided in ".concat(opts && opts.mappings ? 'options' : 'package')); // build namespaces at startup
  9218. logger('building namespaces');
  9219. var root = new Namespace(mapping, {
  9220. name: 'root',
  9221. http: this._network,
  9222. services: this.opts.services
  9223. });
  9224. logger('exposing namespaces');
  9225. for (var key in root) {
  9226. if (key === 'name' || key === 'opts') continue;
  9227. this[key] = root[key];
  9228. }
  9229. logger("attached namespaces : ".concat(Object.keys(this)));
  9230. this.realtime = this._network.realtime;
  9231. }
  9232. /**
  9233. * Use a specific flow to retrieve an access token on behalf the user
  9234. * @param {String|Function} flow either a flow name or a custom implementation
  9235. * @param {Object} [opts]
  9236. * @param {String} [opts.client_id] the OAuth client ID to use to identify the application
  9237. * default to the one defined when instancing Keymetrics and fallback to 795984050 (custom tokens)
  9238. * @throws invalid use of this function, either the flow don't exist or isn't correctly implemented
  9239. */
  9240. _createClass(Keymetrics, [{
  9241. key: "use",
  9242. value: function use(flow, opts) {
  9243. var _this = this;
  9244. logger("using ".concat(flow, " authentication strategy"));
  9245. this._network.useStrategy(flow, opts); // the logout is dependent of the auth flow so we need it to be initialize
  9246. // but also we need to give the access of the instance, so we inject it here
  9247. this.auth.logout = function () {
  9248. return _this._network.oauth_flow.deleteTokens(_this);
  9249. };
  9250. return this;
  9251. }
  9252. /**
  9253. * API date lag, in millisecond. This is the difference between the current browser date and the
  9254. * approximated API date. This is useful to compute duration between dates returned by the API
  9255. * and "now".
  9256. * @example
  9257. * const apiDate = moment().add(km.apiDateLag)
  9258. * const timeSinceLastUpdate = apiDate.diff(server.updated_at)
  9259. */
  9260. }, {
  9261. key: "apiDateLag",
  9262. get: function get() {
  9263. return this._network.apiDateLag;
  9264. }
  9265. }]);
  9266. return Keymetrics;
  9267. }();
  9268. module.exports = Keymetrics;
  9269. },{"../constants":1,"./api_mappings.json":38,"./namespace":44,"./network":45,"debug":31}],44:[function(require,module,exports){
  9270. 'use strict';
  9271. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  9272. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9273. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  9274. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  9275. var Endpoint = require('./endpoint');
  9276. var logger = require('debug')('kmjs:namespace');
  9277. module.exports = /*#__PURE__*/function () {
  9278. function Namespace(mapping, opts) {
  9279. _classCallCheck(this, Namespace);
  9280. logger("initialization namespace ".concat(opts.name));
  9281. this.name = opts.name;
  9282. this.http = opts.http;
  9283. this.endpoints = [];
  9284. this.namespaces = [];
  9285. logger("building namespace ".concat(opts.name));
  9286. for (var name in mapping) {
  9287. var child = mapping[name];
  9288. if (_typeof(mapping) === 'object' && !child.route) {
  9289. // ignore the 'default' namespace that should bind to the parent namespace
  9290. if (name === 'default') {
  9291. // create the namespace
  9292. var defaultNamespace = new Namespace(child, {
  9293. name: name,
  9294. http: this.http,
  9295. services: opts.services
  9296. });
  9297. this.namespaces.push(defaultNamespace); // bind property of the default namespace to this namespace
  9298. for (var key in defaultNamespace) {
  9299. if (key === 'name' || key === 'opts') continue;
  9300. this[key] = defaultNamespace[key];
  9301. }
  9302. continue;
  9303. } // if the parent namespace is a object, the child are namespace too
  9304. this.addNamespace(new Namespace(child, {
  9305. name: name,
  9306. http: this.http,
  9307. services: opts.services
  9308. }));
  9309. } else {
  9310. // otherwise its an endpoint
  9311. if (child.service && opts.services && opts.services[child.service.name]) {
  9312. child.service.baseURL = opts.services[child.service.name];
  9313. }
  9314. this.addEndpoint(new Endpoint(child));
  9315. }
  9316. } // logging namespaces
  9317. if (this.namespaces.length > 0) {
  9318. logger("namespace ".concat(this.name, " contains namespaces : \n").concat(this.namespaces.map(function (namespace) {
  9319. return namespace.name;
  9320. }).join('\n'), "\n"));
  9321. } // logging endpoints
  9322. if (this.endpoints.length > 0) {
  9323. logger("Namespace ".concat(this.name, " contains endpoints : \n").concat(this.endpoints.map(function (endpoint) {
  9324. return endpoint.route.name;
  9325. }).join('\n'), "\n"));
  9326. }
  9327. }
  9328. _createClass(Namespace, [{
  9329. key: "addNamespace",
  9330. value: function addNamespace(namespace) {
  9331. if (!namespace || namespace.name === this.name) {
  9332. throw new Error("A namespace must not have the same name as the parent namespace");
  9333. }
  9334. if (!(namespace instanceof Namespace)) {
  9335. throw new Error("addNamespace only accept Namespace instance");
  9336. }
  9337. this.namespaces.push(namespace);
  9338. this[namespace.name] = namespace;
  9339. }
  9340. }, {
  9341. key: "addEndpoint",
  9342. value: function addEndpoint(endpoint) {
  9343. if (!endpoint || endpoint.name === this.name) {
  9344. throw new Error("A endpoint must not have the same name as a namespace");
  9345. }
  9346. if (!(endpoint instanceof Endpoint)) {
  9347. throw new Error("addNamespace only accept Namespace instance");
  9348. }
  9349. this.endpoints.push(endpoint);
  9350. this[endpoint.name] = endpoint.build(this.http);
  9351. }
  9352. }]);
  9353. return Namespace;
  9354. }();
  9355. },{"./endpoint":42,"debug":31}],45:[function(require,module,exports){
  9356. 'use strict';
  9357. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  9358. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9359. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  9360. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  9361. var axios = require('axios');
  9362. var AuthStrategy = require('./auth_strategies/strategy');
  9363. var constants = require('../constants');
  9364. var logger = require('debug')('kmjs:network');
  9365. var loggerHttp = require('debug')('kmjs:network:http');
  9366. var loggerWS = require('debug')('kmjs:network:ws');
  9367. var WS = require('./utils/websocket');
  9368. var EventEmitter = require('eventemitter2');
  9369. var async = require('async');
  9370. var BUFFERIZED = -1;
  9371. module.exports = /*#__PURE__*/function () {
  9372. function NetworkWrapper(km, opts) {
  9373. _classCallCheck(this, NetworkWrapper);
  9374. logger('init network manager');
  9375. opts.baseURL = opts.services.API;
  9376. this.opts = opts;
  9377. this.opts.maxRedirects = 0;
  9378. this.tokens = {
  9379. refresh_token: null,
  9380. access_token: null
  9381. };
  9382. this.km = km;
  9383. this._queue = [];
  9384. this._axios = axios.create(opts);
  9385. this._websockets = [];
  9386. this._endpoints = new Map();
  9387. this._bucketFilters = new Map();
  9388. this.apiDateLag = 0;
  9389. this.realtime = new EventEmitter({
  9390. wildcard: true,
  9391. delimiter: ':',
  9392. newListener: false,
  9393. maxListeners: 100
  9394. }); // https://github.com/EventEmitter2/EventEmitter2/issues/214
  9395. var self = this;
  9396. var realtimeOn = this.realtime.on;
  9397. this.realtime.on = function () {
  9398. self.editSocketFilters('push', arguments[0]);
  9399. return realtimeOn.apply(self.realtime, arguments);
  9400. };
  9401. var realtimeOff = this.realtime.off;
  9402. this.realtime.off = function () {
  9403. self.editSocketFilters('remove', arguments[0]);
  9404. return realtimeOff.apply(self.realtime, arguments);
  9405. };
  9406. this.realtime.subscribe = this.subscribe.bind(this);
  9407. this.realtime.unsubscribe = this.unsubscribe.bind(this);
  9408. this.authenticated = false;
  9409. this._setupDateLag();
  9410. }
  9411. _createClass(NetworkWrapper, [{
  9412. key: "_setupDateLag",
  9413. value: function _setupDateLag() {
  9414. var _this = this;
  9415. var updateApiDateLag = function updateApiDateLag(response) {
  9416. if (response && response.headers && response.headers.date) {
  9417. var headerDate = new Date(response.headers.date);
  9418. var clientDate = new Date(); // The header date is likely to be truncated to the second, so truncate the client date too
  9419. headerDate.setMilliseconds(0);
  9420. clientDate.setMilliseconds(0);
  9421. _this.apiDateLag = headerDate - clientDate;
  9422. }
  9423. };
  9424. this._axios.interceptors.response.use(function (response) {
  9425. updateApiDateLag(response);
  9426. return response;
  9427. }, function (error) {
  9428. updateApiDateLag(error.response);
  9429. return Promise.reject(error);
  9430. });
  9431. }
  9432. }, {
  9433. key: "_queueUpdater",
  9434. value: function _queueUpdater() {
  9435. if (this.authenticated === false) return;
  9436. if (this._queue.length > 0) {
  9437. logger("Emptying requests queue (size: ".concat(this._queue.length, ")"));
  9438. } // when we are authenticated we can clear the queue
  9439. while (this._queue.length > 0) {
  9440. var promise = this._queue.shift(); // make the request
  9441. this.request(promise.request).then(promise.resolve, promise.reject);
  9442. }
  9443. }
  9444. /**
  9445. * Resolve the endpoint of the node to make the request to
  9446. * because each bucket might be on a different node
  9447. * @param {String} bucketID the bucket id
  9448. *
  9449. * @return {Promise}
  9450. */
  9451. }, {
  9452. key: "_resolveBucketEndpoint",
  9453. value: function _resolveBucketEndpoint(bucketID) {
  9454. var _this2 = this;
  9455. if (!bucketID) return Promise.reject(new Error("Missing argument : bucketID"));
  9456. if (!this._endpoints.has(bucketID)) {
  9457. var promise = this._axios.request({
  9458. url: "/api/bucket/".concat(bucketID),
  9459. method: 'GET',
  9460. headers: {
  9461. Authorization: "Bearer ".concat(this.tokens.access_token)
  9462. }
  9463. }).then(function (res) {
  9464. return res.data.node.endpoints.web;
  9465. })["catch"](function (e) {
  9466. _this2._endpoints["delete"](bucketID);
  9467. throw e;
  9468. });
  9469. this._endpoints.set(bucketID, promise);
  9470. }
  9471. return this._endpoints.get(bucketID);
  9472. }
  9473. /**
  9474. * Send a http request
  9475. * @param {Object} opts
  9476. * @param {String} [opts.method=GET] http method
  9477. * @param {String} opts.url the full URL
  9478. * @param {Object} [opts.data] body data
  9479. * @param {Object} [opts.params] url params
  9480. *
  9481. * @return {Promise}
  9482. */
  9483. }, {
  9484. key: "request",
  9485. value: function request(httpOpts) {
  9486. var _this3 = this;
  9487. return new Promise(function (resolve, reject) {
  9488. async.series([// verify that we don't need to buffer the request because authentication
  9489. function (next) {
  9490. if (_this3.authenticated === true || httpOpts.authentication === false) return next();
  9491. loggerHttp("Queued request to ".concat(httpOpts.url));
  9492. _this3._queue.push({
  9493. resolve: resolve,
  9494. reject: reject,
  9495. request: httpOpts
  9496. }); // we need to stop the flow here
  9497. return next(BUFFERIZED);
  9498. }, // we need to verify that the baseURL is correct
  9499. function (next) {
  9500. if (!httpOpts.url.match(/bucket\/[0-9a-fA-F]{24}/)) return next(); // parse the bucket id from URL
  9501. var bucketID = httpOpts.url.split('/')[3]; // we need to retrieve where to send the request depending on the backend
  9502. _this3._resolveBucketEndpoint(bucketID).then(function (endpoint) {
  9503. httpOpts.baseURL = endpoint; // then continue the flow
  9504. return next();
  9505. })["catch"](next);
  9506. }, // if the request has not been bufferized, make the request
  9507. function (next) {
  9508. // super trick to transform a promise response to a callback
  9509. var successNext = function successNext(res) {
  9510. return next(null, res);
  9511. };
  9512. loggerHttp("Making request to ".concat(httpOpts.url));
  9513. if (!httpOpts.headers) {
  9514. httpOpts.headers = {};
  9515. }
  9516. httpOpts.headers.Authorization = "Bearer ".concat(_this3.tokens.access_token);
  9517. _this3._axios.request(httpOpts).then(successNext)["catch"](function (error) {
  9518. var response = error.response; // we only need to handle when code is 401 (which mean unauthenticated)
  9519. if (response && response.status !== 401) return next(response);
  9520. loggerHttp("Got unautenticated response, buffering request from now ..."); // we tell the client to not send authenticated request anymore
  9521. _this3.authenticated = false;
  9522. loggerHttp("Asking to the oauth flow to retrieve new tokens");
  9523. var q = function q() {
  9524. _this3.oauth_flow.retrieveTokens(_this3.km, function (err, data) {
  9525. // if it fail, we fail the whole request
  9526. if (err) {
  9527. loggerHttp("Failed to retrieve new tokens : ".concat(err.message || err));
  9528. return next(response);
  9529. } // if its good, we try to update the tokens
  9530. loggerHttp("Succesfully retrieved new tokens");
  9531. _this3._updateTokens(null, data, function (err, authenticated) {
  9532. // if it fail, we fail the whole request
  9533. if (err) return next(response); // then we can rebuffer the request
  9534. loggerHttp("Re-buffering call to ".concat(httpOpts.url, " since authenticated now"));
  9535. httpOpts.headers.Authorization = "Bearer ".concat(_this3.tokens.access_token);
  9536. return _this3._axios.request(httpOpts).then(successNext)["catch"](next);
  9537. });
  9538. });
  9539. };
  9540. if (httpOpts.url == _this3.opts.services.OAUTH + '/api/oauth/token') {
  9541. // Avoid infinite recursive loop to retrieveToken
  9542. return setTimeout(q.bind(_this3), 500);
  9543. }
  9544. q();
  9545. });
  9546. }], function (err, results) {
  9547. // if the flow is stoped because the request has been
  9548. // buferred, we don't need to do anything
  9549. if (err === BUFFERIZED) return;
  9550. return err ? reject(err) : resolve(results[2]);
  9551. });
  9552. });
  9553. }
  9554. /**
  9555. * Update the access token used by all the networking clients
  9556. * @param {Error} err if any erro
  9557. * @param {String} accessToken the token you want to use
  9558. * @param {Function} [cb] invoked with <err, authenticated>
  9559. * @private
  9560. */
  9561. }, {
  9562. key: "_updateTokens",
  9563. value: function _updateTokens(err, data, cb) {
  9564. var _this4 = this;
  9565. if (err) {
  9566. console.error('Error while retrieving tokens:', err); // Try to logout/login user
  9567. this.oauth_flow.deleteTokens(this.km);
  9568. return console.error(err.response ? err.response.data : err.stack);
  9569. }
  9570. if (!data || !data.access_token || !data.refresh_token) throw new Error('Invalid tokens');
  9571. this.tokens = data;
  9572. loggerHttp("Registered new access_token : ".concat(data.access_token));
  9573. this._websockets.forEach(function (websocket) {
  9574. return websocket.updateAuthorization(data.access_token);
  9575. });
  9576. this._axios.defaults.headers.common['Authorization'] = "Bearer ".concat(data.access_token);
  9577. this._axios.request({
  9578. url: '/api/bucket',
  9579. method: 'GET',
  9580. headers: {
  9581. Authorization: "Bearer ".concat(data.access_token)
  9582. }
  9583. }).then(function (res) {
  9584. loggerHttp("Cached ".concat(res.data.length, " buckets for current user"));
  9585. _this4.authenticated = true;
  9586. _this4._queueUpdater();
  9587. return typeof cb === 'function' ? cb(null, true) : null;
  9588. })["catch"](function (err) {
  9589. console.error('Error while retrieving buckets');
  9590. console.error(err.response ? err.response.data : err);
  9591. return typeof cb === 'function' ? cb(err) : null;
  9592. });
  9593. }
  9594. /**
  9595. * Specify a strategy to use when authenticating to server
  9596. * @param {String|Function} flow the name of the flow to use or a custom implementation
  9597. * @param {Object} [opts]
  9598. * @param {String} [opts.client_id] the OAuth client ID to use to identify the application
  9599. * default to the one defined when instancing Keymetrics and fallback to 795984050 (custom tokens)
  9600. * @throws invalid use of this function, either the flow don't exist or isn't correctly implemented
  9601. */
  9602. }, {
  9603. key: "useStrategy",
  9604. value: function useStrategy(flow, opts) {
  9605. if (!opts) opts = {}; // if client not provided here, use the one given in the instance
  9606. if (!opts.client_id) {
  9607. opts.client_id = this.opts.OAUTH_CLIENT_ID;
  9608. } // in the case of flow being a custom implementation
  9609. if (_typeof(flow) === 'object') {
  9610. this.oauth_flow = flow;
  9611. if (!this.oauth_flow.retrieveTokens || !this.oauth_flow.deleteTokens) {
  9612. throw new Error('You must implement the Strategy interface to use it');
  9613. }
  9614. return this.oauth_flow.retrieveTokens(this.km, this._updateTokens.bind(this));
  9615. } // otherwise fallback on the flow that are implemented
  9616. if (typeof AuthStrategy.implementations(flow) === 'undefined') {
  9617. throw new Error("The flow named ".concat(flow, " doesn't exist"));
  9618. }
  9619. var flowMeta = AuthStrategy.implementations(flow); // verify that the environnement condition is meet
  9620. if (flowMeta.condition && constants.ENVIRONNEMENT !== flowMeta.condition) {
  9621. throw new Error("The flow ".concat(flow, " is reserved for ").concat(flowMeta.condition, " environment"));
  9622. }
  9623. var FlowImpl = flowMeta.nodule;
  9624. this.oauth_flow = new FlowImpl(opts);
  9625. return this.oauth_flow.retrieveTokens(this.km, this._updateTokens.bind(this));
  9626. }
  9627. }, {
  9628. key: "editSocketFilters",
  9629. value: function editSocketFilters(type, event) {
  9630. if (event.indexOf('**') === 0) throw new Error('You need to provide a bucket public id.');
  9631. event = event.split(':');
  9632. var bucketPublicId = event[0];
  9633. var filter = event.slice(2).join(':');
  9634. var socket = this._websockets.find(function (socket) {
  9635. return socket.bucketPublic === bucketPublicId;
  9636. });
  9637. if (!this._bucketFilters.has(bucketPublicId)) this._bucketFilters.set(bucketPublicId, []);
  9638. var filters = this._bucketFilters.get(bucketPublicId);
  9639. if (type === 'push') {
  9640. filters.push(filter);
  9641. } else {
  9642. filters.splice(filters.indexOf(filter), 1);
  9643. }
  9644. if (!socket) return;
  9645. socket.send(JSON.stringify({
  9646. action: 'sub',
  9647. public_id: bucketPublicId,
  9648. filters: Array.from(new Set(filters)) // avoid duplicates
  9649. }));
  9650. }
  9651. /**
  9652. * Subscribe to realtime from bucket
  9653. * @param {String} bucketId bucket id
  9654. * @param {Object} [opts]
  9655. *
  9656. * @return {Promise}
  9657. */
  9658. }, {
  9659. key: "subscribe",
  9660. value: function subscribe(bucketId, opts) {
  9661. var _this5 = this;
  9662. return new Promise(function (resolve, reject) {
  9663. logger("Request endpoints for ".concat(bucketId));
  9664. _this5.km.bucket.retrieve(bucketId).then(function (res) {
  9665. var bucket = res.data;
  9666. var connected = false;
  9667. var endpoints = bucket.node.endpoints;
  9668. var endpoint = endpoints.realtime || endpoints.web;
  9669. endpoint = endpoint.replace('http', 'ws');
  9670. if (_this5.opts.IS_DEBUG) {
  9671. endpoint = endpoint.replace(':3000', ':4020');
  9672. }
  9673. loggerWS("Found endpoint for ".concat(bucketId, " : ").concat(endpoint)); // connect websocket client to the realtime endpoint
  9674. var socket = new WS("".concat(endpoint, "/primus"), _this5.tokens.access_token);
  9675. socket.bucketPublic = bucket.public_id;
  9676. socket.connected = false;
  9677. socket.bucket = bucketId;
  9678. var keepAliveHandler = function keepAliveHandler() {
  9679. socket.ping();
  9680. };
  9681. var keepAliveInterval = null;
  9682. var onConnect = function onConnect() {
  9683. logger("Connected to ws endpoint : ".concat(endpoint, " (bucket: ").concat(bucketId, ")"));
  9684. socket.connected = true;
  9685. _this5.realtime.emit("".concat(bucket.public_id, ":connected"));
  9686. socket.send(JSON.stringify({
  9687. action: 'sub',
  9688. public_id: bucket.public_id,
  9689. filters: Array.from(new Set(_this5._bucketFilters.get(bucket.public_id))) // avoid duplicates
  9690. }));
  9691. if (keepAliveInterval !== null) {
  9692. clearInterval(keepAliveInterval);
  9693. keepAliveInterval = null;
  9694. }
  9695. keepAliveInterval = setInterval(keepAliveHandler.bind(_this5), 5000);
  9696. if (!connected) {
  9697. connected = true;
  9698. return resolve(socket);
  9699. }
  9700. };
  9701. socket.onmaxreconnect = function (_) {
  9702. if (!connected) {
  9703. connected = true;
  9704. return reject(new Error('Connection timeout'));
  9705. }
  9706. };
  9707. socket.onopen = onConnect;
  9708. socket.onunexpectedresponse = function (req, res) {
  9709. if (res.statusCode === 401) {
  9710. return _this5.oauth_flow.retrieveTokens(_this5.km, function (err, data) {
  9711. if (err) return logger("Failed to retrieve tokens for ws: ".concat(err.message));
  9712. logger("Succesfully retrieved new tokens for ws");
  9713. _this5._updateTokens(null, data, function (err, authenticated) {
  9714. if (err) return logger("Failed to update tokens for ws: ".concat(err.message));
  9715. return socket._tryReconnect();
  9716. });
  9717. });
  9718. }
  9719. return socket._tryReconnect();
  9720. };
  9721. socket.onerror = function (err) {
  9722. loggerWS("Error on ".concat(endpoint, " (bucket: ").concat(bucketId, ")"));
  9723. loggerWS(err);
  9724. _this5.realtime.emit("".concat(bucket.public_id, ":error"), err);
  9725. };
  9726. socket.onclose = function () {
  9727. logger("Closing ws connection ".concat(endpoint, " (bucket: ").concat(bucketId, ")"));
  9728. socket.connected = false;
  9729. _this5.realtime.emit("".concat(bucket.public_id, ":disconnected"));
  9730. if (keepAliveInterval !== null) {
  9731. clearInterval(keepAliveInterval);
  9732. keepAliveInterval = null;
  9733. }
  9734. }; // broadcast in the bus
  9735. socket.onmessage = function (msg) {
  9736. loggerWS("Received message for bucket ".concat(bucketId, " (").concat((msg.data.length / 1000).toFixed(1), " Kb)"));
  9737. var data = null;
  9738. try {
  9739. data = JSON.parse(msg.data);
  9740. } catch (e) {
  9741. return loggerWS("Receive not json message for bucket ".concat(bucketId));
  9742. }
  9743. var packet = data.data[1];
  9744. Object.keys(packet).forEach(function (event) {
  9745. if (event === 'server_name') return;
  9746. _this5.realtime.emit("".concat(bucket.public_id, ":").concat(packet.server_name || 'none', ":").concat(event), packet[event]);
  9747. });
  9748. };
  9749. _this5._websockets.push(socket);
  9750. })["catch"](reject);
  9751. });
  9752. }
  9753. /**
  9754. * Unsubscribe realtime from bucket
  9755. * @param {String} bucketId bucket id
  9756. * @param {Object} [opts]
  9757. *
  9758. * @return {Promise}
  9759. */
  9760. }, {
  9761. key: "unsubscribe",
  9762. value: function unsubscribe(bucketId, opts) {
  9763. var _this6 = this;
  9764. return new Promise(function (resolve, reject) {
  9765. logger("Unsubscribe from realtime for ".concat(bucketId));
  9766. var socket = _this6._websockets.find(function (socket) {
  9767. return socket.bucket === bucketId;
  9768. });
  9769. if (!socket) {
  9770. return reject(new Error("Realtime wasn't connected to ".concat(bucketId)));
  9771. }
  9772. socket.close(1000, 'Disconnecting');
  9773. logger("Succesfully unsubscribed from realtime for ".concat(bucketId));
  9774. return resolve();
  9775. });
  9776. }
  9777. }]);
  9778. return NetworkWrapper;
  9779. }();
  9780. },{"../constants":1,"./auth_strategies/strategy":41,"./utils/websocket":47,"async":2,"axios":3,"debug":31,"eventemitter2":33}],46:[function(require,module,exports){
  9781. 'use strict';
  9782. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  9783. function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
  9784. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  9785. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  9786. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9787. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  9788. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  9789. module.exports = /*#__PURE__*/function () {
  9790. function RequestValidator() {
  9791. _classCallCheck(this, RequestValidator);
  9792. }
  9793. _createClass(RequestValidator, null, [{
  9794. key: "extract",
  9795. /**
  9796. * Extract httpOptions from the endpoint definition
  9797. * and the data given by the user
  9798. *
  9799. * @param {Object} endpoint endpoint definition
  9800. * @param {Array} args arguments given by the user
  9801. * @return {Promise} resolve to the http options need to make the request
  9802. */
  9803. value: function extract(endpoint, args) {
  9804. var isDefined = function isDefined(val) {
  9805. return val !== null && typeof val !== 'undefined';
  9806. };
  9807. return new Promise(function (resolve, reject) {
  9808. var httpOpts = {
  9809. params: {},
  9810. data: {},
  9811. url: endpoint.route.name + '',
  9812. method: endpoint.route.type,
  9813. authentication: endpoint.authentication || false
  9814. };
  9815. switch (endpoint.route.type) {
  9816. // GET request, we assume data will only be in the query or url params
  9817. case 'GET':
  9818. {
  9819. var _iterator = _createForOfIteratorHelper(endpoint.params || []),
  9820. _step;
  9821. try {
  9822. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  9823. var param = _step.value;
  9824. var value = args.shift(); // params should always be a string since they will be replaced in the url
  9825. if (typeof value !== 'string' && param.optional === false) {
  9826. return reject(new Error("Expected to receive string argument for ".concat(param.name, " to match but got ").concat(value)));
  9827. }
  9828. if (value) {
  9829. // if value is given, use it
  9830. httpOpts.url = httpOpts.url.replace(param.name, value);
  9831. } else if (param.optional === false && param.defaultvalue !== null) {
  9832. // use default value if available
  9833. httpOpts.url = httpOpts.url.replace(param.name, param.defaultvalue);
  9834. }
  9835. }
  9836. } catch (err) {
  9837. _iterator.e(err);
  9838. } finally {
  9839. _iterator.f();
  9840. }
  9841. var _iterator2 = _createForOfIteratorHelper(endpoint.query || []),
  9842. _step2;
  9843. try {
  9844. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  9845. var _param = _step2.value;
  9846. var _value = args.shift(); // query should always be a string since they will be replaced in the url
  9847. if (typeof _value !== 'string' && _param.optional === false) {
  9848. return reject(new Error("Expected to receive string argument for ".concat(_param.name, " query but got ").concat(_value)));
  9849. } // set query value
  9850. if (_value) {
  9851. // if value is given, use it
  9852. httpOpts.params[_param.name] = _value;
  9853. } else if (_param.optional === false && _param.defaultvalue !== null) {
  9854. // use default value if available
  9855. httpOpts.params[_param.name] = _param.defaultvalue;
  9856. }
  9857. }
  9858. } catch (err) {
  9859. _iterator2.e(err);
  9860. } finally {
  9861. _iterator2.f();
  9862. }
  9863. break;
  9864. }
  9865. // for PUT, POST and PATCH request, only params and body are authorized
  9866. case 'PUT':
  9867. case 'POST':
  9868. case 'PATCH':
  9869. {
  9870. var _iterator3 = _createForOfIteratorHelper(endpoint.params || []),
  9871. _step3;
  9872. try {
  9873. for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
  9874. var _param2 = _step3.value;
  9875. var _value2 = args.shift(); // params should always be a string since they will be replaced in the url
  9876. if (typeof _value2 !== 'string' && _param2.optional === false) {
  9877. return reject(new Error("Expected to receive string argument for ".concat(_param2.name, " to match but got ").concat(_value2)));
  9878. } // replace param in url
  9879. if (_value2) {
  9880. // if value is given, use it
  9881. httpOpts.url = httpOpts.url.replace(_param2.name, _value2);
  9882. } else if (_param2.optional === false && _param2.defaultvalue !== null) {
  9883. // use default value if available
  9884. httpOpts.url = httpOpts.url.replace(_param2.name, _param2.defaultvalue);
  9885. }
  9886. }
  9887. } catch (err) {
  9888. _iterator3.e(err);
  9889. } finally {
  9890. _iterator3.f();
  9891. }
  9892. var _iterator4 = _createForOfIteratorHelper(endpoint.query || []),
  9893. _step4;
  9894. try {
  9895. for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
  9896. var _param3 = _step4.value;
  9897. var _value3 = args.shift(); // query should always be a string since they will be replaced in the url
  9898. if (typeof _value3 !== 'string' && _param3.optional === false) {
  9899. return reject(new Error("Expected to receive string argument for ".concat(_param3.name, " query but got ").concat(_value3)));
  9900. } // set query value
  9901. if (_value3) {
  9902. // if value is given, use it
  9903. httpOpts.params[_param3.name] = _value3;
  9904. } else if (_param3.optional === false && _param3.defaultvalue !== null) {
  9905. // use default value if available
  9906. httpOpts.params[_param3.name] = _param3.defaultvalue;
  9907. }
  9908. } // if we don't have any arguments, break
  9909. } catch (err) {
  9910. _iterator4.e(err);
  9911. } finally {
  9912. _iterator4.f();
  9913. }
  9914. if (args.length === 0) break;
  9915. var data = args[0];
  9916. if (_typeof(data) !== 'object' && endpoint.body.length > 0) {
  9917. return reject(new Error("Expected to receive an object for post data but received ".concat(_typeof(data))));
  9918. }
  9919. var _iterator5 = _createForOfIteratorHelper(endpoint.body || []),
  9920. _step5;
  9921. try {
  9922. for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
  9923. var field = _step5.value;
  9924. var isSubfield = field.name.includes('[]') === true; // verify that the mandatory field are here
  9925. if (!isDefined(data[field.name]) && isSubfield === false && field.optional === false && field.defaultvalue === null) {
  9926. return reject(new Error("Missing mandatory field ".concat(field.name, " to make a POST request on ").concat(endpoint.route.name)));
  9927. } // verify that the mandatory field are the good type
  9928. if (_typeof(data[field.name]) !== field.type && isSubfield === false && field.optional === false && field.defaultvalue === null) {
  9929. // eslint-disable-line
  9930. return reject(new Error("Invalid type for field ".concat(field.name, ", expected ").concat(field.type, " but got ").concat(_typeof(data[field.name]))));
  9931. } // add it to the request only when its present
  9932. if (isDefined(data[field.name])) {
  9933. httpOpts.data[field.name] = data[field.name];
  9934. } // or else its not optional and has a default value
  9935. if (field.optional === false && field.defaultvalue !== null) {
  9936. httpOpts.data[field.name] = field.defaultvalue;
  9937. }
  9938. }
  9939. } catch (err) {
  9940. _iterator5.e(err);
  9941. } finally {
  9942. _iterator5.f();
  9943. }
  9944. break;
  9945. }
  9946. // DELETE can have params or query parameters
  9947. case 'DELETE':
  9948. {
  9949. var _iterator6 = _createForOfIteratorHelper(endpoint.params || []),
  9950. _step6;
  9951. try {
  9952. for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
  9953. var _param4 = _step6.value;
  9954. var _value4 = args.shift(); // params should always be a string since they will be replaced in the url
  9955. if (typeof _value4 !== 'string' && _param4.optional === false) {
  9956. return reject(new Error("Expected to receive string argument for ".concat(_param4.name, " to match but got ").concat(_value4)));
  9957. } // replace param in url
  9958. if (_value4) {
  9959. // if value is given, use it
  9960. httpOpts.url = httpOpts.url.replace(_param4.name, _value4);
  9961. } else if (_param4.optional === false && _param4.defaultvalue !== null) {
  9962. // use default value if available
  9963. httpOpts.url = httpOpts.url.replace(_param4.name, _param4.defaultvalue);
  9964. }
  9965. }
  9966. } catch (err) {
  9967. _iterator6.e(err);
  9968. } finally {
  9969. _iterator6.f();
  9970. }
  9971. var _iterator7 = _createForOfIteratorHelper(endpoint.query || []),
  9972. _step7;
  9973. try {
  9974. for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
  9975. var _param5 = _step7.value;
  9976. var _value5 = args.shift(); // query should always be a string
  9977. if (typeof _value5 !== 'string' && _param5.optional === false) {
  9978. return reject(new Error("Expected to receive string argument for ".concat(_param5.name, " query but got ").concat(_value5)));
  9979. } // replace param in url
  9980. if (_value5) {
  9981. // if value is given, use it
  9982. httpOpts.params[_param5.name] = _value5;
  9983. } else if (_param5.optional === false && _param5.defaultvalue !== null) {
  9984. // use default value if available
  9985. httpOpts.params[_param5.name] = _param5.defaultvalue;
  9986. }
  9987. }
  9988. } catch (err) {
  9989. _iterator7.e(err);
  9990. } finally {
  9991. _iterator7.f();
  9992. }
  9993. break;
  9994. }
  9995. default:
  9996. {
  9997. return reject(new Error("Invalid endpoint declaration, invalid method ".concat(endpoint.route.type, " found")));
  9998. }
  9999. }
  10000. return resolve(httpOpts);
  10001. });
  10002. }
  10003. }]);
  10004. return RequestValidator;
  10005. }();
  10006. },{}],47:[function(require,module,exports){
  10007. /* global WebSocket */
  10008. 'use strict';
  10009. var ws = require('ws');
  10010. var debug = require('debug')('kmjs:network:_ws');
  10011. var _WebSocket = typeof ws !== 'function' ? WebSocket : ws;
  10012. var defaultOptions = {
  10013. debug: false,
  10014. automaticOpen: true,
  10015. reconnectOnError: true,
  10016. reconnectInterval: 1000,
  10017. maxReconnectInterval: 10000,
  10018. reconnectDecay: 1,
  10019. timeoutInterval: 2000,
  10020. maxReconnectAttempts: Infinity,
  10021. randomRatio: 3,
  10022. reconnectOnCleanClose: false
  10023. };
  10024. var ReconnectableWebSocket = function ReconnectableWebSocket(url, token, protocols, options) {
  10025. if (!protocols) protocols = [];
  10026. if (!options) options = [];
  10027. this.CONNECTING = 0;
  10028. this.OPEN = 1;
  10029. this.CLOSING = 2;
  10030. this.CLOSED = 3;
  10031. this._url = url;
  10032. this._token = token;
  10033. this._protocols = protocols;
  10034. this._options = Object.assign({}, defaultOptions, options);
  10035. this._messageQueue = [];
  10036. this._reconnectAttempts = 0;
  10037. this.readyState = this.CONNECTING;
  10038. if (typeof this._options.debug === 'function') {
  10039. this._debug = this._options.debug;
  10040. } else if (this._options.debug) {
  10041. this._debug = console.log.bind(console);
  10042. } else {
  10043. this._debug = function () {};
  10044. }
  10045. if (this._options.automaticOpen) this.open();
  10046. };
  10047. ReconnectableWebSocket.prototype.updateAuthorization = function (authorization) {
  10048. this._token = authorization;
  10049. };
  10050. ReconnectableWebSocket.prototype.open = function () {
  10051. debug('open');
  10052. var socket = this._socket = new _WebSocket("".concat(this._url, "?token=").concat(this._token), this._protocols);
  10053. if (this._options.binaryType) {
  10054. socket.binaryType = this._options.binaryType;
  10055. }
  10056. if (this._options.maxReconnectAttempts && this._options.maxReconnectAttempts < this._reconnectAttempts) {
  10057. return this.onmaxreconnect();
  10058. }
  10059. this._syncState();
  10060. if (socket.on) {
  10061. socket.on('unexpected-response', this._onunexpectedresponse);
  10062. }
  10063. socket.onmessage = this._onmessage.bind(this);
  10064. socket.onopen = this._onopen.bind(this);
  10065. socket.onclose = this._onclose.bind(this);
  10066. socket.onerror = this._onerror.bind(this);
  10067. };
  10068. ReconnectableWebSocket.prototype.send = function (data) {
  10069. debug('send');
  10070. if (this._socket && this._socket.readyState === _WebSocket.OPEN && this._messageQueue.length === 0) {
  10071. this._socket.send(data);
  10072. } else {
  10073. this._messageQueue.push(data);
  10074. }
  10075. };
  10076. ReconnectableWebSocket.prototype.ping = function () {
  10077. debug('ping');
  10078. if (this._socket.ping && this._socket && this._socket.readyState === _WebSocket.OPEN && this._messageQueue.length === 0) {
  10079. this._socket.ping();
  10080. }
  10081. };
  10082. ReconnectableWebSocket.prototype.close = function (code, reason) {
  10083. debug('close');
  10084. if (typeof code === 'undefined') code = 1000;
  10085. if (this._socket) this._socket.close(code, reason);
  10086. };
  10087. ReconnectableWebSocket.prototype._onunexpectedresponse = function (req, res) {
  10088. debug('unexpected-response');
  10089. this.onunexpectedresponse && this.onunexpectedresponse(req, res);
  10090. };
  10091. ReconnectableWebSocket.prototype._onmessage = function (message) {
  10092. debug('onmessage');
  10093. this.onmessage && this.onmessage(message);
  10094. };
  10095. ReconnectableWebSocket.prototype._onopen = function (event) {
  10096. debug('onopen');
  10097. this._syncState();
  10098. this._flushQueue();
  10099. if (this._reconnectAttempts !== 0) {
  10100. this.onreconnect && this.onreconnect();
  10101. }
  10102. this._reconnectAttempts = 0;
  10103. this.onopen && this.onopen(event);
  10104. };
  10105. ReconnectableWebSocket.prototype._onclose = function (event) {
  10106. debug('onclose', event);
  10107. this._syncState();
  10108. this._debug('WebSocket: connection is broken', event);
  10109. this.onclose && this.onclose(event);
  10110. this._tryReconnect(event);
  10111. };
  10112. ReconnectableWebSocket.prototype._onerror = function (event) {
  10113. debug('onerror', event); // To avoid undetermined state, we close socket on error
  10114. this._socket.close();
  10115. this._syncState();
  10116. this._debug('WebSocket: error', event);
  10117. this.onerror && this.onerror(event);
  10118. if (this._options.reconnectOnError) this._tryReconnect(event);
  10119. };
  10120. ReconnectableWebSocket.prototype._tryReconnect = function (event) {
  10121. var self = this;
  10122. debug('Trying to reconnect');
  10123. if (event.wasClean && !this._options.reconnectOnCleanClose) {
  10124. return;
  10125. }
  10126. setTimeout(function () {
  10127. if (self.readyState === self.CLOSING || self.readyState === self.CLOSED) {
  10128. self._reconnectAttempts++;
  10129. self.open();
  10130. }
  10131. }, this._getTimeout());
  10132. };
  10133. ReconnectableWebSocket.prototype._flushQueue = function () {
  10134. while (this._messageQueue.length !== 0) {
  10135. var data = this._messageQueue.shift();
  10136. this._socket.send(data);
  10137. }
  10138. };
  10139. ReconnectableWebSocket.prototype._getTimeout = function () {
  10140. var timeout = this._options.reconnectInterval * Math.pow(this._options.reconnectDecay, this._reconnectAttempts);
  10141. timeout = timeout > this._options.maxReconnectInterval ? this._options.maxReconnectInterval : timeout;
  10142. return this._options.randomRatio ? getRandom(timeout / this._options.randomRatio, timeout) : timeout;
  10143. };
  10144. ReconnectableWebSocket.prototype._syncState = function () {
  10145. this.readyState = this._socket.readyState;
  10146. };
  10147. function getRandom(min, max) {
  10148. return Math.random() * (max - min) + min;
  10149. }
  10150. module.exports = ReconnectableWebSocket;
  10151. },{"debug":31,"ws":30}],"/":[function(require,module,exports){
  10152. "use strict";
  10153. module.exports = require('./src/keymetrics.js');
  10154. },{"./src/keymetrics.js":43}]},{},[])("/")
  10155. });